feat: Add logger service and improve expense dialog with enhanced receipt management and calculation logic.

This commit is contained in:
Van Leemput Dayron
2025-11-28 12:54:54 +01:00
parent cad9d42128
commit fd710b8cb8
35 changed files with 2148 additions and 1296 deletions

View File

@@ -15,7 +15,7 @@
<!-- Permissions pour écrire dans le stockage --> <!-- Permissions pour écrire dans le stockage -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application <application
android:label="travel_mate" android:label="Travel Mate"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"> android:icon="@mipmap/ic_launcher">
<activity <activity

View File

@@ -19,10 +19,10 @@
/// balanceRepository: balanceRepository, /// balanceRepository: balanceRepository,
/// expenseRepository: expenseRepository, /// expenseRepository: expenseRepository,
/// ); /// );
/// ///
/// // Load balances for a group /// // Load balances for a group
/// balanceBloc.add(LoadGroupBalances('groupId123')); /// balanceBloc.add(LoadGroupBalances('groupId123'));
/// ///
/// // Mark a settlement as completed /// // Mark a settlement as completed
/// balanceBloc.add(MarkSettlementAsCompleted( /// balanceBloc.add(MarkSettlementAsCompleted(
/// groupId: 'groupId123', /// groupId: 'groupId123',
@@ -32,6 +32,7 @@
/// )); /// ));
/// ``` /// ```
library; library;
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../repositories/balance_repository.dart'; import '../../repositories/balance_repository.dart';
import '../../repositories/expense_repository.dart'; import '../../repositories/expense_repository.dart';
@@ -46,10 +47,10 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
final ErrorService _errorService; final ErrorService _errorService;
/// Constructor for BalanceBloc. /// Constructor for BalanceBloc.
/// ///
/// Initializes the bloc with required repositories and optional services. /// Initializes the bloc with required repositories and optional services.
/// Sets up event handlers for balance-related operations. /// Sets up event handlers for balance-related operations.
/// ///
/// Args: /// Args:
/// [balanceRepository]: Repository for balance data operations /// [balanceRepository]: Repository for balance data operations
/// [expenseRepository]: Repository for expense data operations /// [expenseRepository]: Repository for expense data operations
@@ -61,7 +62,12 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
BalanceService? balanceService, BalanceService? balanceService,
ErrorService? errorService, ErrorService? errorService,
}) : _balanceRepository = balanceRepository, }) : _balanceRepository = balanceRepository,
_balanceService = balanceService ?? BalanceService(balanceRepository: balanceRepository, expenseRepository: expenseRepository), _balanceService =
balanceService ??
BalanceService(
balanceRepository: balanceRepository,
expenseRepository: expenseRepository,
),
_errorService = errorService ?? ErrorService(), _errorService = errorService ?? ErrorService(),
super(BalanceInitial()) { super(BalanceInitial()) {
on<LoadGroupBalances>(_onLoadGroupBalance); on<LoadGroupBalances>(_onLoadGroupBalance);
@@ -70,11 +76,11 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
} }
/// Handles [LoadGroupBalances] events. /// Handles [LoadGroupBalances] events.
/// ///
/// Loads and calculates user balances for a specific group along with /// Loads and calculates user balances for a specific group along with
/// optimal settlement recommendations. This provides a complete overview /// optimal settlement recommendations. This provides a complete overview
/// of who owes money to whom and the most efficient payment strategy. /// of who owes money to whom and the most efficient payment strategy.
/// ///
/// Args: /// Args:
/// [event]: The LoadGroupBalances event containing the group ID /// [event]: The LoadGroupBalances event containing the group ID
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -83,18 +89,22 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
Emitter<BalanceState> emit, Emitter<BalanceState> emit,
) async { ) async {
try { try {
emit(BalanceLoading()); // Emit empty state initially to avoid infinite spinner
emit(const GroupBalancesLoaded(balances: [], settlements: []));
// Calculate group user balances // Calculate group user balances
final userBalances = await _balanceRepository.calculateGroupUserBalances(event.groupId); final userBalances = await _balanceRepository.calculateGroupUserBalances(
event.groupId,
);
// Calculate optimal settlements // 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) { } catch (e) {
_errorService.logError('BalanceBloc', 'Error loading balance: $e'); _errorService.logError('BalanceBloc', 'Error loading balance: $e');
emit(BalanceError(e.toString())); emit(BalanceError(e.toString()));
@@ -102,11 +112,11 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
} }
/// Handles [RefreshBalance] events. /// Handles [RefreshBalance] events.
/// ///
/// Refreshes the balance data for a group while trying to maintain the current /// Refreshes the balance data for a group while trying to maintain the current
/// state when possible to provide a smoother user experience. Only shows loading /// state when possible to provide a smoother user experience. Only shows loading
/// state if there's no existing balance data. /// state if there's no existing balance data.
/// ///
/// Args: /// Args:
/// [event]: The RefreshBalance event containing the group ID /// [event]: The RefreshBalance event containing the group ID
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -119,17 +129,20 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
if (state is! GroupBalancesLoaded) { if (state is! GroupBalancesLoaded) {
emit(BalanceLoading()); emit(BalanceLoading());
} }
// Calculate group user balances // Calculate group user balances
final userBalances = await _balanceRepository.calculateGroupUserBalances(event.groupId); final userBalances = await _balanceRepository.calculateGroupUserBalances(
event.groupId,
);
// Calculate optimal settlements // 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) { } catch (e) {
_errorService.logError('BalanceBloc', 'Error refreshing balance: $e'); _errorService.logError('BalanceBloc', 'Error refreshing balance: $e');
emit(BalanceError(e.toString())); emit(BalanceError(e.toString()));
@@ -137,11 +150,11 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
} }
/// Handles [MarkSettlementAsCompleted] events. /// Handles [MarkSettlementAsCompleted] events.
/// ///
/// Records a settlement transaction between two users, marking that /// Records a settlement transaction between two users, marking that
/// a debt has been paid. This updates the balance calculations and /// a debt has been paid. This updates the balance calculations and
/// automatically refreshes the group balance data to reflect the change. /// automatically refreshes the group balance data to reflect the change.
/// ///
/// Args: /// Args:
/// [event]: The MarkSettlementAsCompleted event containing settlement details /// [event]: The MarkSettlementAsCompleted event containing settlement details
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -156,9 +169,9 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
toUserId: event.toUserId, toUserId: event.toUserId,
amount: event.amount, amount: event.amount,
); );
emit(const BalanceOperationSuccess('Settlement marked as completed')); emit(const BalanceOperationSuccess('Settlement marked as completed'));
// Reload balance after settlement // Reload balance after settlement
add(RefreshBalance(event.groupId)); add(RefreshBalance(event.groupId));
} catch (e) { } catch (e) {
@@ -166,4 +179,4 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
emit(BalanceError(e.toString())); emit(BalanceError(e.toString()));
} }
} }
} }

View File

@@ -7,7 +7,7 @@ import 'expense_event.dart';
import 'expense_state.dart'; import 'expense_state.dart';
/// BLoC for managing expense operations and state. /// BLoC for managing expense operations and state.
/// ///
/// This BLoC handles expense-related operations including loading expenses, /// This BLoC handles expense-related operations including loading expenses,
/// creating new expenses, updating existing ones, deleting expenses, and /// creating new expenses, updating existing ones, deleting expenses, and
/// managing expense splits. It coordinates with the expense repository and /// managing expense splits. It coordinates with the expense repository and
@@ -15,18 +15,18 @@ import 'expense_state.dart';
class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> { class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
/// Repository for expense data operations. /// Repository for expense data operations.
final ExpenseRepository _expenseRepository; final ExpenseRepository _expenseRepository;
/// Service for expense business logic and validation. /// Service for expense business logic and validation.
final ExpenseService _expenseService; final ExpenseService _expenseService;
/// Service for error handling and logging. /// Service for error handling and logging.
final ErrorService _errorService; final ErrorService _errorService;
/// Subscription to the expenses stream for real-time updates. /// Subscription to the expenses stream for real-time updates.
StreamSubscription? _expensesSubscription; StreamSubscription? _expensesSubscription;
/// Creates a new [ExpenseBloc] with required dependencies. /// Creates a new [ExpenseBloc] with required dependencies.
/// ///
/// [expenseRepository] is required for data operations. /// [expenseRepository] is required for data operations.
/// [expenseService] and [errorService] have default implementations if not provided. /// [expenseService] and [errorService] have default implementations if not provided.
ExpenseBloc({ ExpenseBloc({
@@ -34,10 +34,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
ExpenseService? expenseService, ExpenseService? expenseService,
ErrorService? errorService, ErrorService? errorService,
}) : _expenseRepository = expenseRepository, }) : _expenseRepository = expenseRepository,
_expenseService = expenseService ?? ExpenseService(expenseRepository: expenseRepository), _expenseService =
expenseService ??
ExpenseService(expenseRepository: expenseRepository),
_errorService = errorService ?? ErrorService(), _errorService = errorService ?? ErrorService(),
super(ExpenseInitial()) { super(ExpenseInitial()) {
on<LoadExpensesByGroup>(_onLoadExpensesByGroup); on<LoadExpensesByGroup>(_onLoadExpensesByGroup);
on<ExpensesUpdated>(_onExpensesUpdated); on<ExpensesUpdated>(_onExpensesUpdated);
on<CreateExpense>(_onCreateExpense); on<CreateExpense>(_onCreateExpense);
@@ -48,7 +49,7 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [LoadExpensesByGroup] events. /// Handles [LoadExpensesByGroup] events.
/// ///
/// Sets up a stream subscription to receive real-time updates for expenses /// Sets up a stream subscription to receive real-time updates for expenses
/// in the specified group. Cancels any existing subscription before creating a new one. /// in the specified group. Cancels any existing subscription before creating a new one.
Future<void> _onLoadExpensesByGroup( Future<void> _onLoadExpensesByGroup(
@@ -56,15 +57,18 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
Emitter<ExpenseState> emit, Emitter<ExpenseState> emit,
) async { ) async {
try { 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(); await _expensesSubscription?.cancel();
_expensesSubscription = _expenseRepository _expensesSubscription = _expenseRepository
.getExpensesStream(event.groupId) .getExpensesStream(event.groupId)
.listen( .listen(
(expenses) => add(ExpensesUpdated(expenses)), (expenses) => add(ExpensesUpdated(expenses)),
onError: (error) => add(ExpensesUpdated([], error: error.toString())), onError: (error) =>
add(ExpensesUpdated([], error: error.toString())),
); );
} catch (e) { } catch (e) {
_errorService.logError('ExpenseBloc', 'Error loading expenses: $e'); _errorService.logError('ExpenseBloc', 'Error loading expenses: $e');
@@ -73,10 +77,10 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [ExpensesUpdated] events. /// Handles [ExpensesUpdated] events.
/// ///
/// Processes real-time updates from the expense stream, either emitting /// Processes real-time updates from the expense stream, either emitting
/// the updated expense list or an error state if the stream encountered an error. /// the updated expense list or an error state if the stream encountered an error.
/// ///
/// Args: /// Args:
/// [event]: The ExpensesUpdated event containing expenses or error information /// [event]: The ExpensesUpdated event containing expenses or error information
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -92,11 +96,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [CreateExpense] events. /// Handles [CreateExpense] events.
/// ///
/// Creates a new expense with validation and optional receipt image upload. /// Creates a new expense with validation and optional receipt image upload.
/// Uses the expense service to handle business logic and validation, /// Uses the expense service to handle business logic and validation,
/// including currency conversion and split calculations. /// including currency conversion and split calculations.
/// ///
/// Args: /// Args:
/// [event]: The CreateExpense event containing expense data and optional receipt /// [event]: The CreateExpense event containing expense data and optional receipt
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -105,7 +109,10 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
Emitter<ExpenseState> emit, Emitter<ExpenseState> emit,
) async { ) async {
try { try {
await _expenseService.createExpenseWithValidation(event.expense, event.receiptImage); await _expenseService.createExpenseWithValidation(
event.expense,
event.receiptImage,
);
emit(const ExpenseOperationSuccess('Expense created successfully')); emit(const ExpenseOperationSuccess('Expense created successfully'));
} catch (e) { } catch (e) {
_errorService.logError('ExpenseBloc', 'Error creating expense: $e'); _errorService.logError('ExpenseBloc', 'Error creating expense: $e');
@@ -114,11 +121,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [UpdateExpense] events. /// Handles [UpdateExpense] events.
/// ///
/// Updates an existing expense with validation and optional new receipt image. /// Updates an existing expense with validation and optional new receipt image.
/// Uses the expense service to handle business logic, validation, and /// Uses the expense service to handle business logic, validation, and
/// recalculation of splits if expense details change. /// recalculation of splits if expense details change.
/// ///
/// Args: /// Args:
/// [event]: The UpdateExpense event containing updated expense data and optional new receipt /// [event]: The UpdateExpense event containing updated expense data and optional new receipt
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -127,7 +134,10 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
Emitter<ExpenseState> emit, Emitter<ExpenseState> emit,
) async { ) async {
try { try {
await _expenseService.updateExpenseWithValidation(event.expense, event.newReceiptImage); await _expenseService.updateExpenseWithValidation(
event.expense,
event.newReceiptImage,
);
emit(const ExpenseOperationSuccess('Expense updated successfully')); emit(const ExpenseOperationSuccess('Expense updated successfully'));
} catch (e) { } catch (e) {
_errorService.logError('ExpenseBloc', 'Error updating expense: $e'); _errorService.logError('ExpenseBloc', 'Error updating expense: $e');
@@ -136,10 +146,10 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [DeleteExpense] events. /// Handles [DeleteExpense] events.
/// ///
/// Permanently deletes an expense from the database. This action /// Permanently deletes an expense from the database. This action
/// cannot be undone and will affect group balance calculations. /// cannot be undone and will affect group balance calculations.
/// ///
/// Args: /// Args:
/// [event]: The DeleteExpense event containing the expense ID to delete /// [event]: The DeleteExpense event containing the expense ID to delete
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -157,11 +167,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [MarkSplitAsPaid] events. /// Handles [MarkSplitAsPaid] events.
/// ///
/// Marks a user's portion of an expense split as paid, updating the /// Marks a user's portion of an expense split as paid, updating the
/// expense's split information and affecting balance calculations. /// expense's split information and affecting balance calculations.
/// This helps track who has settled their portion of shared expenses. /// This helps track who has settled their portion of shared expenses.
/// ///
/// Args: /// Args:
/// [event]: The MarkSplitAsPaid event containing expense ID and user ID /// [event]: The MarkSplitAsPaid event containing expense ID and user ID
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -179,11 +189,11 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Handles [ArchiveExpense] events. /// Handles [ArchiveExpense] events.
/// ///
/// Archives an expense, moving it out of the active expense list /// Archives an expense, moving it out of the active expense list
/// while preserving it for historical records and audit purposes. /// while preserving it for historical records and audit purposes.
/// Archived expenses are not included in current balance calculations. /// Archived expenses are not included in current balance calculations.
/// ///
/// Args: /// Args:
/// [event]: The ArchiveExpense event containing the expense ID to archive /// [event]: The ArchiveExpense event containing the expense ID to archive
/// [emit]: State emitter function /// [emit]: State emitter function
@@ -201,7 +211,7 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
} }
/// Cleans up resources when the bloc is closed. /// Cleans up resources when the bloc is closed.
/// ///
/// Cancels the expense stream subscription to prevent memory leaks /// Cancels the expense stream subscription to prevent memory leaks
/// and ensure proper disposal of resources. /// and ensure proper disposal of resources.
@override @override
@@ -209,4 +219,4 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
_expensesSubscription?.cancel(); _expensesSubscription?.cancel();
return super.close(); return super.close();
} }
} }

View File

@@ -56,6 +56,7 @@
/// - Group /// - Group
/// - ExpenseBloc /// - ExpenseBloc
library; library;
import 'dart:io'; import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
@@ -76,8 +77,10 @@ import '../../models/expense.dart';
class AddExpenseDialog extends StatefulWidget { class AddExpenseDialog extends StatefulWidget {
/// The group to which the expense belongs. /// The group to which the expense belongs.
final Group group; final Group group;
/// The user creating or editing the expense. /// The user creating or editing the expense.
final user_state.UserModel currentUser; final user_state.UserModel currentUser;
/// The expense to edit (null for new expense). /// The expense to edit (null for new expense).
final Expense? expenseToEdit; final Expense? expenseToEdit;
@@ -103,27 +106,40 @@ class AddExpenseDialog extends StatefulWidget {
class _AddExpenseDialogState extends State<AddExpenseDialog> { class _AddExpenseDialogState extends State<AddExpenseDialog> {
/// Form key for validating the expense form. /// Form key for validating the expense form.
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
/// Controller for the expense description field. /// Controller for the expense description field.
final _descriptionController = TextEditingController(); final _descriptionController = TextEditingController();
/// Controller for the expense amount field. /// Controller for the expense amount field.
final _amountController = TextEditingController(); final _amountController = TextEditingController();
/// The selected date for the expense. /// The selected date for the expense.
late DateTime _selectedDate; late DateTime _selectedDate;
/// The selected category for the expense. /// The selected category for the expense.
late ExpenseCategory _selectedCategory; late ExpenseCategory _selectedCategory;
/// The selected currency for the expense. /// The selected currency for the expense.
late ExpenseCurrency _selectedCurrency; late ExpenseCurrency _selectedCurrency;
/// The user ID of the payer. /// The user ID of the payer.
late String _paidById; late String _paidById;
/// Map of userId to split amount for each participant. /// Map of userId to split amount for each participant.
final Map<String, double> _splits = {}; final Map<String, double> _splits = {};
/// The selected receipt image file, if any. /// The selected receipt image file, if any.
File? _receiptImage; File? _receiptImage;
/// Whether the dialog is currently submitting data. /// Whether the dialog is currently submitting data.
bool _isLoading = false; bool _isLoading = false;
/// Whether the expense is split equally among participants. /// Whether the expense is split equally among participants.
bool _splitEqually = true; bool _splitEqually = true;
/// Whether the existing receipt has been removed.
bool _receiptRemoved = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -172,7 +188,7 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
if (pickedFile != null) { if (pickedFile != null) {
final file = File(pickedFile.path); final file = File(pickedFile.path);
final fileSize = await file.length(); final fileSize = await file.length();
if (fileSize > 5 * 1024 * 1024) { if (fileSize > 5 * 1024 * 1024) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -199,11 +215,11 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
final amount = double.tryParse(_amountController.text) ?? 0; final amount = double.tryParse(_amountController.text) ?? 0;
final selectedMembers = _splits.entries.where((e) => e.value >= 0).toList(); final selectedMembers = _splits.entries.where((e) => e.value >= 0).toList();
if (selectedMembers.isEmpty) return; if (selectedMembers.isEmpty) return;
final splitAmount = amount / selectedMembers.length; final splitAmount = amount / selectedMembers.length;
setState(() { setState(() {
for (final entry in selectedMembers) { for (final entry in selectedMembers) {
_splits[entry.key] = splitAmount; _splits[entry.key] = splitAmount;
@@ -221,17 +237,14 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
if (!_formKey.currentState!.validate()) return; if (!_formKey.currentState!.validate()) return;
final amount = double.parse(_amountController.text); final amount = double.parse(_amountController.text);
final selectedSplits = _splits.entries final selectedSplits = _splits.entries.where((e) => e.value > 0).map((e) {
.where((e) => e.value > 0) final member = widget.group.members.firstWhere((m) => m.userId == e.key);
.map((e) { return ExpenseSplit(
final member = widget.group.members.firstWhere((m) => m.userId == e.key); userId: e.key,
return ExpenseSplit( userName: member.firstName,
userId: e.key, amount: e.value,
userName: member.firstName, );
amount: e.value, }).toList();
);
})
.toList();
if (selectedSplits.isEmpty) { if (selectedSplits.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -248,11 +261,15 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
try { try {
// Convertir en EUR // Convertir en EUR
final amountInEur = context.read<ExpenseBloc>().state is ExpensesLoaded final amountInEur = context.read<ExpenseBloc>().state is ExpensesLoaded
? (context.read<ExpenseBloc>().state as ExpensesLoaded) ? ((context.read<ExpenseBloc>().state as ExpensesLoaded)
.exchangeRates[_selectedCurrency]! * amount .exchangeRates[_selectedCurrency.code] ??
1.0) *
amount
: 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( final expense = Expense(
id: widget.expenseToEdit?.id ?? '', id: widget.expenseToEdit?.id ?? '',
@@ -266,29 +283,29 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
paidByName: payer.firstName, paidByName: payer.firstName,
splits: selectedSplits, splits: selectedSplits,
date: _selectedDate, date: _selectedDate,
receiptUrl: widget.expenseToEdit?.receiptUrl, receiptUrl: _receiptRemoved ? null : widget.expenseToEdit?.receiptUrl,
createdAt: widget.expenseToEdit?.createdAt ?? DateTime.now(), createdAt: widget.expenseToEdit?.createdAt ?? DateTime.now(),
); );
if (widget.expenseToEdit == null) { if (widget.expenseToEdit == null) {
context.read<ExpenseBloc>().add(CreateExpense( context.read<ExpenseBloc>().add(
expense: expense, CreateExpense(expense: expense, receiptImage: _receiptImage),
receiptImage: _receiptImage, );
));
} else { } else {
context.read<ExpenseBloc>().add(UpdateExpense( context.read<ExpenseBloc>().add(
expense: expense, UpdateExpense(expense: expense, newReceiptImage: _receiptImage),
newReceiptImage: _receiptImage, );
));
} }
if (mounted) { if (mounted) {
Navigator.of(context).pop(); Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text(widget.expenseToEdit == null content: Text(
? 'Dépense ajoutée' widget.expenseToEdit == null
: 'Dépense modifiée'), ? 'Dépense ajoutée'
: 'Dépense modifiée',
),
backgroundColor: Colors.green, backgroundColor: Colors.green,
), ),
); );
@@ -296,10 +313,7 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
content: Text('Erreur: $e'),
backgroundColor: Colors.red,
),
); );
} }
} finally { } finally {
@@ -314,284 +328,425 @@ class _AddExpenseDialogState extends State<AddExpenseDialog> {
/// Returns a Dialog widget containing the expense form. /// Returns a Dialog widget containing the expense form.
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDark = theme.brightness == Brightness.dark;
return Dialog( return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
backgroundColor: isDark ? theme.scaffoldBackgroundColor : Colors.white,
insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
child: Container( child: Container(
constraints: const BoxConstraints(maxWidth: 600, maxHeight: 700), constraints: const BoxConstraints(maxWidth: 500, maxHeight: 800),
child: Scaffold( child: Column(
appBar: AppBar( children: [
title: Text(widget.expenseToEdit == null // Header
? 'Nouvelle dépense' Padding(
: 'Modifier la dépense'), padding: const EdgeInsets.fromLTRB(24, 24, 16, 16),
automaticallyImplyLeading: false, child: Row(
actions: [ children: [
IconButton( Expanded(
icon: const Icon(Icons.close), child: Text(
onPressed: () => Navigator.of(context).pop(), widget.expenseToEdit == null
? 'Nouvelle dépense'
: 'Modifier la dépense',
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
), ),
], ),
), const Divider(height: 1),
body: Form(
key: _formKey,
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Description
TextFormField(
controller: _descriptionController,
decoration: const InputDecoration(
labelText: 'Description',
hintText: 'Ex: Restaurant, Essence...',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.description),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Veuillez entrer une description';
}
return null;
},
),
const SizedBox(height: 16),
// Montant et devise // Form Content
Row( Expanded(
child: Form(
key: _formKey,
child: ListView(
padding: const EdgeInsets.all(24),
children: [ children: [
Expanded( // Description
flex: 2, TextFormField(
child: TextFormField( controller: _descriptionController,
controller: _amountController, decoration: InputDecoration(
decoration: const InputDecoration( labelText: 'Description',
labelText: 'Montant', hintText: 'Ex: Restaurant, Essence...',
border: OutlineInputBorder(), prefixIcon: const Icon(Icons.description_outlined),
prefixIcon: Icon(Icons.euro), border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
), ),
keyboardType: const TextInputType.numberWithOptions(decimal: true), contentPadding: const EdgeInsets.symmetric(
onChanged: (_) => _calculateSplits(), horizontal: 16,
validator: (value) { vertical: 16,
if (value == null || value.isEmpty) {
return 'Requis';
}
if (double.tryParse(value) == null || double.parse(value) <= 0) {
return 'Montant invalide';
}
return null;
},
),
),
const SizedBox(width: 8),
Expanded(
child: DropdownButtonFormField<ExpenseCurrency>(
initialValue: _selectedCurrency,
decoration: const InputDecoration(
labelText: 'Devise',
border: OutlineInputBorder(),
), ),
items: ExpenseCurrency.values.map((currency) {
return DropdownMenuItem(
value: currency,
child: Text(currency.code),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() => _selectedCurrency = value);
}
},
), ),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Requis';
}
return null;
},
), ),
], const SizedBox(height: 16),
),
const SizedBox(height: 16),
// Catégorie // Montant et Devise
DropdownButtonFormField<ExpenseCategory>( Row(
initialValue: _selectedCategory,
decoration: const InputDecoration(
labelText: 'Catégorie',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.category),
),
items: ExpenseCategory.values.map((category) {
return DropdownMenuItem(
value: category,
child: Row(
children: [
Icon(category.icon, size: 20),
const SizedBox(width: 8),
Text(category.displayName),
],
),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() => _selectedCategory = value);
}
},
),
const SizedBox(height: 16),
// Date
ListTile(
leading: const Icon(Icons.calendar_today),
title: const Text('Date'),
subtitle: Text(DateFormat('dd/MM/yyyy').format(_selectedDate)),
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(4),
),
onTap: () async {
final date = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(2020),
lastDate: DateTime.now().add(const Duration(days: 365)),
);
if (date != null) {
setState(() => _selectedDate = date);
}
},
),
const SizedBox(height: 16),
// Payé par
DropdownButtonFormField<String>(
initialValue: _paidById,
decoration: const InputDecoration(
labelText: 'Payé par',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person),
),
items: widget.group.members.map((member) {
return DropdownMenuItem(
value: member.userId,
child: Text(member.firstName),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() => _paidById = value);
}
},
),
const SizedBox(height: 16),
// Division
Card(
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row( Expanded(
children: [ flex: 2,
const Text( child: TextFormField(
'Division', controller: _amountController,
style: TextStyle( decoration: InputDecoration(
fontSize: 16, labelText: 'Montant',
fontWeight: FontWeight.bold, prefixIcon: const Icon(Icons.euro_symbol),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
), ),
), ),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
onChanged: (_) => _calculateSplits(),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Requis';
}
if (double.tryParse(value) == null ||
double.parse(value) <= 0) {
return 'Invalide';
}
return null;
},
),
),
const SizedBox(width: 12),
Expanded(
child: DropdownButtonFormField<ExpenseCurrency>(
initialValue: _selectedCurrency,
decoration: InputDecoration(
labelText: 'Devise',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 16,
),
),
items: ExpenseCurrency.values.map((currency) {
return DropdownMenuItem(
value: currency,
child: Text(currency.code),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() => _selectedCurrency = value);
}
},
),
),
],
),
const SizedBox(height: 16),
// Catégorie
DropdownButtonFormField<ExpenseCategory>(
initialValue: _selectedCategory,
decoration: InputDecoration(
labelText: 'Catégorie',
prefixIcon: Icon(_selectedCategory.icon),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
),
items: ExpenseCategory.values.map((category) {
return DropdownMenuItem(
value: category,
child: Text(category.displayName),
);
}).toList(),
onChanged: (value) {
if (value != null) {
setState(() => _selectedCategory = value);
}
},
),
const SizedBox(height: 16),
// Date
InkWell(
onTap: () async {
final date = await showDatePicker(
context: context,
initialDate: _selectedDate,
firstDate: DateTime(2020),
lastDate: DateTime.now().add(
const Duration(days: 365),
),
);
if (date != null) setState(() => _selectedDate = date);
},
borderRadius: BorderRadius.circular(8),
child: InputDecorator(
decoration: InputDecoration(
labelText: 'Date',
prefixIcon: const Icon(Icons.calendar_today_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
),
child: Text(
DateFormat('dd/MM/yyyy').format(_selectedDate),
style: theme.textTheme.bodyLarge,
),
),
),
const SizedBox(height: 16),
// Payé par
DropdownButtonFormField<String>(
initialValue: _paidById,
decoration: InputDecoration(
labelText: 'Payé par',
prefixIcon: const Icon(Icons.person_outline),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
),
items: widget.group.members.map((member) {
return DropdownMenuItem(
value: member.userId,
child: Text(member.firstName),
);
}).toList(),
onChanged: (value) {
if (value != null) setState(() => _paidById = value);
},
),
const SizedBox(height: 24),
// Division Section
Container(
decoration: BoxDecoration(
color: isDark ? Colors.grey[800] : Colors.grey[50],
borderRadius: BorderRadius.circular(12),
border: Border.all(color: theme.dividerColor),
),
padding: const EdgeInsets.all(16),
child: Column(
children: [
Row(
children: [
const Text(
'Division',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
Text(
'Égale',
style: TextStyle(
color: isDark
? Colors.grey[400]
: Colors.grey[600],
),
),
const SizedBox(width: 8),
Switch(
value: _splitEqually,
onChanged: (value) {
setState(() {
_splitEqually = value;
if (value) _calculateSplits();
});
},
activeThumbColor: theme.colorScheme.primary,
),
],
),
const Divider(),
...widget.group.members.map((member) {
final isSelected =
_splits.containsKey(member.userId) &&
_splits[member.userId]! >= 0;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Expanded(
child: Text(
member.firstName,
style: const TextStyle(fontSize: 16),
),
),
if (!_splitEqually && isSelected)
SizedBox(
width: 100,
child: TextFormField(
initialValue: _splits[member.userId]
?.toStringAsFixed(2),
decoration: const InputDecoration(
isDense: true,
contentPadding: EdgeInsets.symmetric(
horizontal: 8,
vertical: 8,
),
border: OutlineInputBorder(),
suffixText: '',
),
keyboardType:
const TextInputType.numberWithOptions(
decimal: true,
),
onChanged: (value) {
final amount =
double.tryParse(value) ?? 0;
setState(
() =>
_splits[member.userId] = amount,
);
},
),
),
Checkbox(
value: isSelected,
onChanged: (value) {
setState(() {
if (value == true) {
_splits[member.userId] = 0;
if (_splitEqually) _calculateSplits();
} else {
_splits[member.userId] = -1;
}
});
},
activeColor: theme.colorScheme.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
),
],
),
);
}),
],
),
),
const SizedBox(height: 16),
// Reçu (Optional - keeping simple for now as per design focus)
if (_receiptImage != null ||
(widget.expenseToEdit?.receiptUrl != null &&
!_receiptRemoved))
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
border: Border.all(color: theme.dividerColor),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
const Icon(Icons.receipt_long, color: Colors.green),
const SizedBox(width: 8),
const Text('Reçu joint'),
const Spacer(), const Spacer(),
Text(_splitEqually ? 'Égale' : 'Personnalisée'), IconButton(
Switch( icon: const Icon(Icons.close),
value: _splitEqually, onPressed: () => setState(() {
onChanged: (value) { _receiptImage = null;
setState(() { _receiptRemoved = true;
_splitEqually = value; }),
if (value) _calculateSplits();
});
},
), ),
], ],
), ),
const Divider(), )
...widget.group.members.map((member) { else
final isSelected = _splits.containsKey(member.userId) && OutlinedButton.icon(
_splits[member.userId]! >= 0; onPressed: _pickImage,
icon: const Icon(Icons.camera_alt_outlined),
return CheckboxListTile( label: const Text('Ajouter un reçu'),
title: Text(member.firstName), style: OutlinedButton.styleFrom(
subtitle: _splitEqually || !isSelected padding: const EdgeInsets.symmetric(vertical: 12),
? null shape: RoundedRectangleBorder(
: TextFormField( borderRadius: BorderRadius.circular(8),
initialValue: _splits[member.userId]?.toStringAsFixed(2), ),
decoration: const InputDecoration( ),
labelText: 'Montant',
isDense: true,
),
keyboardType: const TextInputType.numberWithOptions(decimal: true),
onChanged: (value) {
final amount = double.tryParse(value) ?? 0;
setState(() => _splits[member.userId] = amount);
},
),
value: isSelected,
onChanged: (value) {
setState(() {
if (value == true) {
_splits[member.userId] = 0;
if (_splitEqually) _calculateSplits();
} else {
_splits[member.userId] = -1;
}
});
},
);
}),
],
),
),
),
const SizedBox(height: 16),
// Reçu
ListTile(
leading: const Icon(Icons.receipt),
title: Text(_receiptImage != null || widget.expenseToEdit?.receiptUrl != null
? 'Reçu ajouté'
: 'Ajouter un reçu'),
subtitle: _receiptImage != null
? const Text('Nouveau reçu sélectionné')
: null,
trailing: IconButton(
icon: const Icon(Icons.add_photo_alternate),
onPressed: _pickImage,
),
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(4),
),
),
const SizedBox(height: 24),
// Boutons
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
child: const Text('Annuler'),
), ),
),
const SizedBox(width: 16),
Expanded(
child: ElevatedButton(
onPressed: _isLoading ? null : _submit,
child: _isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(widget.expenseToEdit == null ? 'Ajouter' : 'Modifier'),
),
),
], ],
), ),
], ),
), ),
),
// Bottom Button
Padding(
padding: const EdgeInsets.all(24),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: _isLoading ? null : _submit,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
backgroundColor: theme.colorScheme.primary,
foregroundColor: Colors.white,
elevation: 0,
),
child: _isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
),
),
)
: Text(
widget.expenseToEdit == null
? 'Ajouter'
: 'Enregistrer',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
), ),
), ),
); );

View File

@@ -7,11 +7,13 @@ import 'expense_detail_dialog.dart';
class ExpensesTab extends StatelessWidget { class ExpensesTab extends StatelessWidget {
final List<Expense> expenses; final List<Expense> expenses;
final Group group; final Group group;
final String currentUserId;
const ExpensesTab({ const ExpensesTab({
super.key, super.key,
required this.expenses, required this.expenses,
required this.group, required this.group,
required this.currentUserId,
}); });
@override @override
@@ -48,95 +50,157 @@ class ExpensesTab extends StatelessWidget {
} }
Widget _buildExpenseCard(BuildContext context, Expense expense) { Widget _buildExpenseCard(BuildContext context, Expense expense) {
final isDark = Theme.of(context).brightness == Brightness.dark; final theme = Theme.of(context);
final dateFormat = DateFormat('dd/MM/yyyy'); 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), margin: const EdgeInsets.only(bottom: 12),
child: InkWell( decoration: BoxDecoration(
onTap: () => _showExpenseDetail(context, expense), color: isDark ? theme.cardColor : Colors.white,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(16),
child: Padding( boxShadow: [
padding: const EdgeInsets.all(16), BoxShadow(
child: Row( color: Colors.black.withValues(alpha: 0.05),
children: [ blurRadius: 8,
Container( offset: const Offset(0, 2),
width: 48, ),
height: 48, ],
decoration: BoxDecoration( ),
color: isDark ? Colors.blue[900] : Colors.blue[100], child: Material(
borderRadius: BorderRadius.circular(12), color: Colors.transparent,
child: InkWell(
onTap: () => _showExpenseDetail(context, expense),
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Icone circulaire
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: _getCategoryColor(
expense.category,
).withValues(alpha: 0.2),
shape: BoxShape.circle,
),
child: Icon(
expense.category.icon,
color: _getCategoryColor(expense.category),
size: 24,
),
), ),
child: Icon( const SizedBox(width: 16),
expense.category.icon,
color: Colors.blue, // Détails
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
expense.description,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Row(
children: [
Text(
isPayer
? 'Payé par vous'
: 'Payé par ${expense.paidByName}',
style: TextStyle(
fontSize: 13,
color: isDark
? Colors.grey[400]
: Colors.grey[600],
),
),
Text(
'${dateFormat.format(expense.date)}',
style: TextStyle(
fontSize: 13,
color: isDark
? Colors.grey[500]
: Colors.grey[500],
),
),
],
),
],
),
), ),
),
const SizedBox(width: 16), // Montant
Expanded( Column(
child: Column( crossAxisAlignment: CrossAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
expense.description, '$prefix${amountToDisplay.toStringAsFixed(2)} ${expense.currency.symbol}',
style: const TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: amountColor,
), ),
), ),
const SizedBox(height: 4), if (expense.currency != ExpenseCurrency.eur)
Text( Text(
'Payé par ${expense.paidByName}', 'Total ${expense.amountInEur.toStringAsFixed(2)}',
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 11,
color: isDark ? Colors.grey[400] : Colors.grey[600], color: isDark ? Colors.grey[500] : Colors.grey[400],
),
), ),
),
Text(
dateFormat.format(expense.date),
style: TextStyle(
fontSize: 12,
color: isDark ? Colors.grey[500] : Colors.grey[500],
),
),
], ],
), ),
), ],
Column( ),
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'${expense.amount.toStringAsFixed(2)} ${expense.currency.symbol}',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
if (expense.currency != ExpenseCurrency.eur)
Text(
'${expense.amountInEur.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 12,
color: isDark ? Colors.grey[400] : Colors.grey[600],
),
),
],
),
],
), ),
), ),
), ),
); );
} }
Color _getCategoryColor(ExpenseCategory category) {
switch (category) {
case ExpenseCategory.restaurant:
return Colors.orange;
case ExpenseCategory.transport:
return Colors.blue;
case ExpenseCategory.accommodation:
return Colors.purple;
case ExpenseCategory.entertainment:
return Colors.pink;
case ExpenseCategory.shopping:
return Colors.teal;
case ExpenseCategory.other:
return Colors.grey;
}
}
void _showExpenseDetail(BuildContext context, Expense expense) { void _showExpenseDetail(BuildContext context, Expense expense) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => ExpenseDetailDialog( builder: (context) => ExpenseDetailDialog(expense: expense, group: group),
expense: expense,
group: group,
),
); );
} }
} }

View File

@@ -13,7 +13,8 @@ import '../../models/group.dart';
import 'add_expense_dialog.dart'; import 'add_expense_dialog.dart';
import 'balances_tab.dart'; import 'balances_tab.dart';
import 'expenses_tab.dart'; import 'expenses_tab.dart';
import 'settlements_tab.dart'; import '../../models/user_balance.dart';
import '../../models/expense.dart';
class GroupExpensesPage extends StatefulWidget { class GroupExpensesPage extends StatefulWidget {
final Account account; final Account account;
@@ -31,13 +32,14 @@ class GroupExpensesPage extends StatefulWidget {
class _GroupExpensesPageState extends State<GroupExpensesPage> class _GroupExpensesPageState extends State<GroupExpensesPage>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
late TabController _tabController; late TabController _tabController;
ExpenseCategory? _selectedCategory;
String? _selectedPayerId;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_tabController = TabController(length: 3, vsync: this); _tabController = TabController(length: 2, vsync: this);
_loadData(); _loadData();
} }
@@ -50,39 +52,41 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
void _loadData() { void _loadData() {
// Charger les dépenses du groupe // Charger les dépenses du groupe
context.read<ExpenseBloc>().add(LoadExpensesByGroup(widget.group.id)); context.read<ExpenseBloc>().add(LoadExpensesByGroup(widget.group.id));
// Charger les balances du groupe // Charger les balances du groupe
context.read<BalanceBloc>().add(LoadGroupBalances(widget.group.id)); context.read<BalanceBloc>().add(LoadGroupBalances(widget.group.id));
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDarkMode = theme.brightness == Brightness.dark;
return Scaffold( return Scaffold(
backgroundColor: isDarkMode
? theme.scaffoldBackgroundColor
: Colors.grey[50],
appBar: AppBar( appBar: AppBar(
title: Text(widget.account.name), title: const Text(
backgroundColor: Theme.of(context).primaryColor, 'Dépenses du voyage',
foregroundColor: Colors.white, style: TextStyle(fontWeight: FontWeight.bold),
elevation: 0,
bottom: TabBar(
controller: _tabController,
indicatorColor: Colors.white,
labelColor: Colors.white,
unselectedLabelColor: Colors.white70,
tabs: const [
Tab(
icon: Icon(Icons.balance),
text: 'Balances',
),
Tab(
icon: Icon(Icons.receipt_long),
text: 'Dépenses',
),
Tab(
icon: Icon(Icons.payment),
text: 'Règlements',
),
],
), ),
centerTitle: true,
backgroundColor: Colors.transparent,
elevation: 0,
foregroundColor: theme.colorScheme.onSurface,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context),
),
actions: [
IconButton(
icon: const Icon(Icons.filter_list),
onPressed: () {
_showFilterDialog();
},
),
],
), ),
body: MultiBlocListener( body: MultiBlocListener(
listeners: [ listeners: [
@@ -103,56 +107,107 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
backgroundColor: Colors.red, 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: TabBarView( child: Column(
controller: _tabController,
children: [ children: [
// Onglet Balances // Summary Card
BlocBuilder<BalanceBloc, BalanceState>( BlocBuilder<BalanceBloc, BalanceState>(
builder: (context, state) { builder: (context, state) {
if (state is BalanceLoading) { if (state is GroupBalancesLoaded) {
return const Center(child: CircularProgressIndicator()); return _buildSummaryCard(state.balances, isDarkMode);
} 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 _buildEmptyState('Aucune balance disponible'); return const SizedBox.shrink();
}, },
), ),
// Onglet Dépenses // Tabs
BlocBuilder<ExpenseBloc, ExpenseState>( Container(
builder: (context, state) { decoration: BoxDecoration(
if (state is ExpenseLoading) { border: Border(
return const Center(child: CircularProgressIndicator()); bottom: BorderSide(color: theme.dividerColor, width: 1),
} else if (state is ExpensesLoaded) { ),
return ExpensesTab( ),
expenses: state.expenses, child: TabBar(
group: widget.group, controller: _tabController,
); labelColor: theme.colorScheme.primary,
} else if (state is ExpenseError) { unselectedLabelColor: theme.colorScheme.onSurface.withValues(
return _buildErrorState('Erreur lors du chargement des dépenses: ${state.message}'); alpha: 0.6,
} ),
return _buildEmptyState('Aucune dépense trouvée'); indicatorColor: theme.colorScheme.primary,
}, indicatorWeight: 3,
labelStyle: const TextStyle(fontWeight: FontWeight.bold),
tabs: const [
Tab(text: 'Toutes les dépenses'),
Tab(text: 'Mes soldes'),
],
),
), ),
// Onglet Règlements // Tab View
BlocBuilder<BalanceBloc, BalanceState>( Expanded(
builder: (context, state) { child: TabBarView(
if (state is BalanceLoading) { controller: _tabController,
return const Center(child: CircularProgressIndicator()); children: [
} else if (state is GroupBalancesLoaded) { // Onglet Dépenses
return SettlementsTab(settlements: state.settlements); BlocBuilder<ExpenseBloc, ExpenseState>(
} else if (state is BalanceError) { builder: (context, state) {
return _buildErrorState('Erreur lors du chargement des règlements: ${state.message}'); if (state is ExpenseLoading) {
} return const Center(child: CircularProgressIndicator());
return _buildEmptyState('Aucun règlement nécessaire'); } else if (state is ExpensesLoaded) {
}, final userState = context.read<UserBloc>().state;
final currentUserId = userState is user_state.UserLoaded
? userState.user.id
: '';
var filteredExpenses = state.expenses;
if (_selectedCategory != null) {
filteredExpenses = filteredExpenses
.where((e) => e.category == _selectedCategory)
.toList();
}
if (_selectedPayerId != null) {
filteredExpenses = filteredExpenses
.where((e) => e.paidById == _selectedPayerId)
.toList();
}
return ExpensesTab(
expenses: filteredExpenses,
group: widget.group,
currentUserId: currentUserId,
);
} else if (state is ExpenseError) {
return _buildErrorState('Erreur: ${state.message}');
}
return _buildEmptyState('Aucune dépense trouvée');
},
),
// Onglet Balances (Combiné)
BlocBuilder<BalanceBloc, BalanceState>(
builder: (context, state) {
if (state is BalanceLoading) {
return const Center(child: CircularProgressIndicator());
} else if (state is GroupBalancesLoaded) {
return BalancesTab(balances: state.balances);
} else if (state is BalanceError) {
return _buildErrorState('Erreur: ${state.message}');
}
return _buildEmptyState('Aucune balance disponible');
},
),
],
),
), ),
], ],
), ),
@@ -160,8 +215,109 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
onPressed: _showAddExpenseDialog, onPressed: _showAddExpenseDialog,
heroTag: "add_expense_fab", heroTag: "add_expense_fab",
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
elevation: 4,
shape: const CircleBorder(),
tooltip: 'Ajouter une dépense', 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( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( Icon(Icons.error_outline, size: 80, color: Colors.red[300]),
Icons.error_outline,
size: 80,
color: Colors.red[300],
),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Erreur', 'Erreur',
@@ -190,10 +342,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
padding: const EdgeInsets.symmetric(horizontal: 32), padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text( child: Text(
message, message,
style: TextStyle( style: TextStyle(fontSize: 16, color: Colors.grey[600]),
fontSize: 16,
color: Colors.grey[600],
),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), ),
@@ -213,11 +362,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( Icon(Icons.info_outline, size: 80, color: Colors.grey[400]),
Icons.info_outline,
size: 80,
color: Colors.grey[400],
),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'Aucune donnée', 'Aucune donnée',
@@ -230,10 +375,7 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
message, message,
style: TextStyle( style: TextStyle(fontSize: 16, color: Colors.grey[500]),
fontSize: 16,
color: Colors.grey[500],
),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
], ],
@@ -243,14 +385,12 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
void _showAddExpenseDialog() { void _showAddExpenseDialog() {
final userState = context.read<UserBloc>().state; final userState = context.read<UserBloc>().state;
if (userState is user_state.UserLoaded) { if (userState is user_state.UserLoaded) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AddExpenseDialog( builder: (context) =>
group: widget.group, AddExpenseDialog(group: widget.group, currentUser: userState.user),
currentUser: userState.user,
),
); );
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( 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'),
),
],
);
},
);
},
);
}
}

View File

@@ -8,6 +8,8 @@ import '../../models/activity.dart';
import '../../services/activity_cache_service.dart'; import '../../services/activity_cache_service.dart';
import '../loading/laoding_content.dart'; import '../loading/laoding_content.dart';
import '../../blocs/user/user_bloc.dart';
import '../../blocs/user/user_state.dart';
class ActivitiesPage extends StatefulWidget { class ActivitiesPage extends StatefulWidget {
final Trip trip; final Trip trip;
@@ -32,8 +34,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
List<Activity> _tripActivities = []; List<Activity> _tripActivities = [];
List<Activity> _approvedActivities = []; List<Activity> _approvedActivities = [];
bool _isLoadingTripActivities = false; bool _isLoadingTripActivities = false;
int _totalGoogleActivitiesRequested =
0; // Compteur pour les recherches progressives
bool _autoReloadInProgress = bool _autoReloadInProgress =
false; // Protection contre les rechargements en boucle false; // Protection contre les rechargements en boucle
int _lastAutoReloadTriggerCount = int _lastAutoReloadTriggerCount =
@@ -999,9 +1000,11 @@ class _ActivitiesPageState extends State<ActivitiesPage>
} }
void _voteForActivity(String activityId, int vote) { void _voteForActivity(String activityId, int vote) {
// TODO: Récupérer l'ID utilisateur actuel // Récupérer l'ID utilisateur actuel depuis le UserBloc
// Pour l'instant, on utilise l'ID du créateur du voyage pour que le vote compte final userState = context.read<UserBloc>().state;
final userId = widget.trip.createdBy; 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 // 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) // (car l'objet activity passé peut venir d'une liste filtrée ou autre)
@@ -1122,7 +1125,7 @@ class _ActivitiesPageState extends State<ActivitiesPage>
6; // Activités actuelles + ce qui manque + buffer de 6 6; // Activités actuelles + ce qui manque + buffer de 6
// Mettre à jour le compteur et recharger avec le nouveau total // Mettre à jour le compteur et recharger avec le nouveau total
_totalGoogleActivitiesRequested = newTotalToRequest;
_loadMoreGoogleActivitiesWithTotal(newTotalToRequest); _loadMoreGoogleActivitiesWithTotal(newTotalToRequest);
// Libérer le verrou après un délai // Libérer le verrou après un délai
@@ -1135,7 +1138,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
} }
void _searchGoogleActivities() { void _searchGoogleActivities() {
_totalGoogleActivitiesRequested = 6; // Reset du compteur
_autoReloadInProgress = false; // Reset des protections _autoReloadInProgress = false; // Reset des protections
_lastAutoReloadTriggerCount = 0; _lastAutoReloadTriggerCount = 0;
@@ -1166,7 +1168,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
} }
void _resetAndSearchGoogleActivities() { void _resetAndSearchGoogleActivities() {
_totalGoogleActivitiesRequested = 6; // Reset du compteur
_autoReloadInProgress = false; // Reset des protections _autoReloadInProgress = false; // Reset des protections
_lastAutoReloadTriggerCount = 0; _lastAutoReloadTriggerCount = 0;
@@ -1203,8 +1204,6 @@ class _ActivitiesPageState extends State<ActivitiesPage>
final currentCount = currentState.searchResults.length; final currentCount = currentState.searchResults.length;
final newTotal = currentCount + 6; final newTotal = currentCount + 6;
_totalGoogleActivitiesRequested = newTotal;
// Utiliser les coordonnées pré-géolocalisées du voyage si disponibles // Utiliser les coordonnées pré-géolocalisées du voyage si disponibles
if (widget.trip.hasCoordinates) { if (widget.trip.hasCoordinates) {
context.read<ActivityBloc>().add( context.read<ActivityBloc>().add(

View File

@@ -57,7 +57,7 @@ class _AddActivityBottomSheetState extends State<AddActivityBottomSheet> {
height: 4, height: 4,
margin: const EdgeInsets.symmetric(vertical: 12), margin: const EdgeInsets.symmetric(vertical: 12),
decoration: BoxDecoration( decoration: BoxDecoration(
color: theme.colorScheme.onSurface.withOpacity(0.3), color: theme.colorScheme.onSurface.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(2), borderRadius: BorderRadius.circular(2),
), ),
), ),

View File

@@ -12,7 +12,7 @@ import '../../models/message.dart';
import '../../repositories/group_repository.dart'; import '../../repositories/group_repository.dart';
/// Chat group content widget for group messaging functionality. /// Chat group content widget for group messaging functionality.
/// ///
/// This widget provides a complete chat interface for group members to /// This widget provides a complete chat interface for group members to
/// communicate within a travel group. Features include: /// communicate within a travel group. Features include:
/// - Real-time message loading and sending /// - Real-time message loading and sending
@@ -20,7 +20,7 @@ import '../../repositories/group_repository.dart';
/// - Message reactions (like/unlike) /// - Message reactions (like/unlike)
/// - Scroll-to-bottom functionality /// - Scroll-to-bottom functionality
/// - Message status indicators /// - Message status indicators
/// ///
/// The widget integrates with MessageBloc for state management and /// The widget integrates with MessageBloc for state management and
/// handles various message operations through the bloc pattern. /// handles various message operations through the bloc pattern.
class ChatGroupContent extends StatefulWidget { class ChatGroupContent extends StatefulWidget {
@@ -28,13 +28,10 @@ class ChatGroupContent extends StatefulWidget {
final Group group; final Group group;
/// Creates a chat group content widget. /// Creates a chat group content widget.
/// ///
/// Args: /// Args:
/// [group]: The group object containing group details and ID /// [group]: The group object containing group details and ID
const ChatGroupContent({ const ChatGroupContent({super.key, required this.group});
super.key,
required this.group,
});
@override @override
State<ChatGroupContent> createState() => _ChatGroupContentState(); State<ChatGroupContent> createState() => _ChatGroupContentState();
@@ -43,16 +40,16 @@ class ChatGroupContent extends StatefulWidget {
class _ChatGroupContentState extends State<ChatGroupContent> { class _ChatGroupContentState extends State<ChatGroupContent> {
/// Controller for the message input field /// Controller for the message input field
final _messageController = TextEditingController(); final _messageController = TextEditingController();
/// Controller for managing scroll position in the message list /// Controller for managing scroll position in the message list
final _scrollController = ScrollController(); final _scrollController = ScrollController();
/// Currently selected message for editing (null if not editing) /// Currently selected message for editing (null if not editing)
Message? _editingMessage; Message? _editingMessage;
/// Repository pour gérer les groupes /// Repository pour gérer les groupes
final _groupRepository = GroupRepository(); final _groupRepository = GroupRepository();
/// Subscription pour écouter les changements des membres du groupe /// Subscription pour écouter les changements des membres du groupe
late StreamSubscription<List<GroupMember>> _membersSubscription; late StreamSubscription<List<GroupMember>> _membersSubscription;
@@ -61,18 +58,20 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
super.initState(); super.initState();
// Load messages when the widget initializes // Load messages when the widget initializes
context.read<MessageBloc>().add(LoadMessages(widget.group.id)); context.read<MessageBloc>().add(LoadMessages(widget.group.id));
// Écouter les changements des membres du groupe // Écouter les changements des membres du groupe
_membersSubscription = _groupRepository.watchGroupMembers(widget.group.id).listen((updatedMembers) { _membersSubscription = _groupRepository
if (mounted) { .watchGroupMembers(widget.group.id)
setState(() { .listen((updatedMembers) {
widget.group.members.clear(); if (mounted) {
widget.group.members.addAll(updatedMembers); setState(() {
widget.group.members.clear();
widget.group.members.addAll(updatedMembers);
});
}
}); });
}
});
} }
@override @override
void dispose() { void dispose() {
_messageController.dispose(); _messageController.dispose();
@@ -82,11 +81,11 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
} }
/// Sends a new message or updates an existing message. /// Sends a new message or updates an existing message.
/// ///
/// Handles both sending new messages and editing existing ones based /// Handles both sending new messages and editing existing ones based
/// on the current editing state. Validates input and clears the input /// on the current editing state. Validates input and clears the input
/// field after successful submission. /// field after successful submission.
/// ///
/// Args: /// Args:
/// [currentUser]: The user sending or editing the message /// [currentUser]: The user sending or editing the message
void _sendMessage(user_state.UserModel currentUser) { void _sendMessage(user_state.UserModel currentUser) {
@@ -96,33 +95,33 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
if (_editingMessage != null) { if (_editingMessage != null) {
// Edit mode - update existing message // Edit mode - update existing message
context.read<MessageBloc>().add( context.read<MessageBloc>().add(
UpdateMessage( UpdateMessage(
groupId: widget.group.id, groupId: widget.group.id,
messageId: _editingMessage!.id, messageId: _editingMessage!.id,
newText: messageText, newText: messageText,
), ),
); );
_cancelEdit(); _cancelEdit();
} else { } else {
// Send mode - create new message // Send mode - create new message
context.read<MessageBloc>().add( context.read<MessageBloc>().add(
SendMessage( SendMessage(
groupId: widget.group.id, groupId: widget.group.id,
text: messageText, text: messageText,
senderId: currentUser.id, senderId: currentUser.id,
senderName: currentUser.prenom, senderName: currentUser.prenom,
), ),
); );
} }
_messageController.clear(); _messageController.clear();
} }
/// Initiates editing mode for a selected message. /// Initiates editing mode for a selected message.
/// ///
/// Sets the message as the currently editing message and populates /// Sets the message as the currently editing message and populates
/// the input field with the message text for modification. /// the input field with the message text for modification.
/// ///
/// Args: /// Args:
/// [message]: The message to edit /// [message]: The message to edit
void _editMessage(Message message) { void _editMessage(Message message) {
@@ -133,7 +132,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
} }
/// Cancels the current editing operation. /// Cancels the current editing operation.
/// ///
/// Resets the editing state and clears the input field, /// Resets the editing state and clears the input field,
/// returning to normal message sending mode. /// returning to normal message sending mode.
void _cancelEdit() { void _cancelEdit() {
@@ -144,46 +143,43 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
} }
/// Deletes a message from the group chat. /// Deletes a message from the group chat.
/// ///
/// Sends a delete event to the MessageBloc to remove the specified /// Sends a delete event to the MessageBloc to remove the specified
/// message from the group's message history. /// message from the group's message history.
/// ///
/// Args: /// Args:
/// [messageId]: The ID of the message to delete /// [messageId]: The ID of the message to delete
void _deleteMessage(String messageId) { void _deleteMessage(String messageId) {
context.read<MessageBloc>().add( context.read<MessageBloc>().add(
DeleteMessage( DeleteMessage(groupId: widget.group.id, messageId: messageId),
groupId: widget.group.id, );
messageId: messageId,
),
);
} }
void _reactToMessage(String messageId, String userId, String reaction) { void _reactToMessage(String messageId, String userId, String reaction) {
context.read<MessageBloc>().add( context.read<MessageBloc>().add(
ReactToMessage( ReactToMessage(
groupId: widget.group.id, groupId: widget.group.id,
messageId: messageId, messageId: messageId,
userId: userId, userId: userId,
reaction: reaction, reaction: reaction,
), ),
); );
} }
void _removeReaction(String messageId, String userId) { void _removeReaction(String messageId, String userId) {
context.read<MessageBloc>().add( context.read<MessageBloc>().add(
RemoveReaction( RemoveReaction(
groupId: widget.group.id, groupId: widget.group.id,
messageId: messageId, messageId: messageId,
userId: userId, userId: userId,
), ),
); );
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark; final isDark = Theme.of(context).brightness == Brightness.dark;
return BlocBuilder<UserBloc, user_state.UserState>( return BlocBuilder<UserBloc, user_state.UserState>(
builder: (context, userState) { builder: (context, userState) {
if (userState is! user_state.UserLoaded) { if (userState is! user_state.UserLoaded) {
@@ -203,7 +199,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
Text(widget.group.name, style: const TextStyle(fontSize: 18)), Text(widget.group.name, style: const TextStyle(fontSize: 18)),
Text( Text(
'${widget.group.members.length} membre${widget.group.members.length > 1 ? 's' : ''}', '${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,
),
), ),
], ],
), ),
@@ -255,7 +254,8 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
itemBuilder: (context, index) { itemBuilder: (context, index) {
final message = state.messages[index]; final message = state.messages[index];
final isMe = message.senderId == currentUser.id; final isMe = message.senderId == currentUser.id;
final showDate = index == 0 || final showDate =
index == 0 ||
!_isSameDay( !_isSameDay(
state.messages[index - 1].timestamp, state.messages[index - 1].timestamp,
message.timestamp, message.timestamp,
@@ -263,8 +263,14 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
return Column( return Column(
children: [ children: [
if (showDate) _buildDateSeparator(message.timestamp), if (showDate)
_buildMessageBubble(message, isMe, isDark, currentUser.id), _buildDateSeparator(message.timestamp),
_buildMessageBubble(
message,
isMe,
isDark,
currentUser.id,
),
], ],
); );
}, },
@@ -280,14 +286,15 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
if (_editingMessage != null) if (_editingMessage != null)
Container( Container(
color: isDark ? Colors.blue[900] : Colors.blue[100], 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( child: Row(
children: [ children: [
const Icon(Icons.edit, size: 20), const Icon(Icons.edit, size: 20),
const SizedBox(width: 8), const SizedBox(width: 8),
const Expanded( const Expanded(child: Text('Modification du message')),
child: Text('Modification du message'),
),
IconButton( IconButton(
icon: const Icon(Icons.close), icon: const Icon(Icons.close),
onPressed: _cancelEdit, onPressed: _cancelEdit,
@@ -315,11 +322,13 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
child: TextField( child: TextField(
controller: _messageController, controller: _messageController,
decoration: InputDecoration( decoration: InputDecoration(
hintText: _editingMessage != null hintText: _editingMessage != null
? 'Modifier le message...' ? 'Modifier le message...'
: 'Écrire un message...', : 'Écrire un message...',
filled: true, filled: true,
fillColor: isDark ? Colors.grey[850] : Colors.grey[100], fillColor: isDark
? Colors.grey[850]
: Colors.grey[100],
border: OutlineInputBorder( border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24), borderRadius: BorderRadius.circular(24),
borderSide: BorderSide.none, borderSide: BorderSide.none,
@@ -336,9 +345,13 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
const SizedBox(width: 8), const SizedBox(width: 8),
IconButton( IconButton(
onPressed: () => _sendMessage(currentUser), onPressed: () => _sendMessage(currentUser),
icon: Icon(_editingMessage != null ? Icons.check : Icons.send), icon: Icon(
_editingMessage != null ? Icons.check : Icons.send,
),
style: IconButton.styleFrom( style: IconButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(
context,
).colorScheme.primary,
foregroundColor: Colors.white, foregroundColor: Colors.white,
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
), ),
@@ -361,27 +374,17 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( Icon(Icons.chat_bubble_outline, size: 80, color: Colors.grey[400]),
Icons.chat_bubble_outline,
size: 80,
color: Colors.grey[400],
),
const SizedBox(height: 16), const SizedBox(height: 16),
const Text( const Text(
'Aucun message', 'Aucun message',
style: TextStyle( style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
fontSize: 20,
fontWeight: FontWeight.bold,
),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Commencez la conversation !', 'Commencez la conversation !',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(fontSize: 14, color: Colors.grey[600]),
fontSize: 14,
color: Colors.grey[600],
),
), ),
], ],
), ),
@@ -389,10 +392,15 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
); );
} }
Widget _buildMessageBubble(Message message, bool isMe, bool isDark, String currentUserId) { Widget _buildMessageBubble(
Message message,
bool isMe,
bool isDark,
String currentUserId,
) {
final Color bubbleColor; final Color bubbleColor;
final Color textColor; final Color textColor;
if (isMe) { if (isMe) {
bubbleColor = isDark ? const Color(0xFF1E3A5F) : const Color(0xFF90CAF9); bubbleColor = isDark ? const Color(0xFF1E3A5F) : const Color(0xFF90CAF9);
textColor = isDark ? Colors.white : Colors.black87; textColor = isDark ? Colors.white : Colors.black87;
@@ -402,42 +410,48 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
} }
// Trouver le membre qui a envoyé le message pour récupérer son pseudo actuel // Trouver le membre qui a envoyé le message pour récupérer son pseudo actuel
final senderMember = widget.group.members.firstWhere( final senderMember =
(m) => m.userId == message.senderId, widget.group.members.firstWhere(
orElse: () => null as dynamic, (m) => m.userId == message.senderId,
) as dynamic; orElse: () => null as dynamic,
)
as dynamic;
// Utiliser le pseudo actuel du membre, ou le senderName en fallback // Utiliser le pseudo actuel du membre, ou le senderName en fallback
final displayName = senderMember != null ? senderMember.pseudo : message.senderName; final displayName = senderMember != null
? senderMember.pseudo
: message.senderName;
return Align( return Align(
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft, alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
child: GestureDetector( child: GestureDetector(
onLongPress: () => _showMessageOptions(context, message, isMe, currentUserId), onLongPress: () =>
_showMessageOptions(context, message, isMe, currentUserId),
child: Padding( child: Padding(
padding: EdgeInsets.symmetric( padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
horizontal: 8,
vertical: 4,
),
child: Row( child: Row(
mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start, mainAxisAlignment: isMe
? MainAxisAlignment.end
: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
// Avatar du sender (seulement pour les autres messages) // Avatar du sender (seulement pour les autres messages)
if (!isMe) ...[ if (!isMe) ...[
CircleAvatar( CircleAvatar(
radius: 16, radius: 16,
backgroundImage: (senderMember != null && backgroundImage:
senderMember.profilePictureUrl != null && (senderMember != null &&
senderMember.profilePictureUrl!.isNotEmpty) senderMember.profilePictureUrl != null &&
senderMember.profilePictureUrl!.isNotEmpty)
? NetworkImage(senderMember.profilePictureUrl!) ? NetworkImage(senderMember.profilePictureUrl!)
: null, : null,
child: (senderMember == null || child:
senderMember.profilePictureUrl == null || (senderMember == null ||
senderMember.profilePictureUrl!.isEmpty) senderMember.profilePictureUrl == null ||
senderMember.profilePictureUrl!.isEmpty)
? Text( ? Text(
displayName.isNotEmpty displayName.isNotEmpty
? displayName[0].toUpperCase() ? displayName[0].toUpperCase()
: '?', : '?',
style: const TextStyle(fontSize: 12), style: const TextStyle(fontSize: 12),
) )
@@ -445,10 +459,13 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
], ],
Container( Container(
margin: const EdgeInsets.symmetric(vertical: 4), margin: const EdgeInsets.symmetric(vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 10,
),
constraints: BoxConstraints( constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.65, maxWidth: MediaQuery.of(context).size.width * 0.65,
), ),
@@ -462,7 +479,9 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
), ),
), ),
child: Column( child: Column(
crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, crossAxisAlignment: isMe
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [ children: [
if (!isMe) ...[ if (!isMe) ...[
Text( Text(
@@ -476,11 +495,17 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
const SizedBox(height: 4), const SizedBox(height: 4),
], ],
Text( Text(
message.isDeleted ? 'a supprimé un message' : message.text, message.isDeleted
? 'a supprimé un message'
: message.text,
style: TextStyle( style: TextStyle(
fontSize: 15, fontSize: 15,
color: message.isDeleted ? textColor.withValues(alpha: 0.5) : textColor, color: message.isDeleted
fontStyle: message.isDeleted ? FontStyle.italic : FontStyle.normal, ? textColor.withValues(alpha: 0.5)
: textColor,
fontStyle: message.isDeleted
? FontStyle.italic
: FontStyle.normal,
), ),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
@@ -528,7 +553,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
List<Widget> _buildReactionChips(Message message, String currentUserId) { List<Widget> _buildReactionChips(Message message, String currentUserId) {
final reactionCounts = <String, List<String>>{}; final reactionCounts = <String, List<String>>{};
// Grouper les réactions par emoji // Grouper les réactions par emoji
message.reactions.forEach((userId, emoji) { message.reactions.forEach((userId, emoji) {
reactionCounts.putIfAbsent(emoji, () => []).add(userId); reactionCounts.putIfAbsent(emoji, () => []).add(userId);
@@ -550,7 +575,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration( decoration: BoxDecoration(
color: hasReacted color: hasReacted
? Colors.blue.withValues(alpha: 0.3) ? Colors.blue.withValues(alpha: 0.3)
: Colors.grey.withValues(alpha: 0.3), : Colors.grey.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
@@ -565,7 +590,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
const SizedBox(width: 2), const SizedBox(width: 2),
Text( Text(
'${userIds.length}', '${userIds.length}',
style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold), style: const TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
),
), ),
], ],
), ),
@@ -574,7 +602,12 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
}).toList(); }).toList();
} }
void _showMessageOptions(BuildContext context, Message message, bool isMe, String currentUserId) { void _showMessageOptions(
BuildContext context,
Message message,
bool isMe,
String currentUserId,
) {
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
builder: (context) => SafeArea( builder: (context) => SafeArea(
@@ -609,7 +642,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
), ),
ListTile( ListTile(
leading: const Icon(Icons.delete, color: Colors.red), 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: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
_showDeleteConfirmation(context, message.id); _showDeleteConfirmation(context, message.id);
@@ -712,20 +748,23 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
final member = widget.group.members[index]; final member = widget.group.members[index];
final initials = member.pseudo.isNotEmpty final initials = member.pseudo.isNotEmpty
? member.pseudo[0].toUpperCase() ? member.pseudo[0].toUpperCase()
: (member.firstName.isNotEmpty : (member.firstName.isNotEmpty
? member.firstName[0].toUpperCase() ? member.firstName[0].toUpperCase()
: '?'); : '?');
// Construire le nom complet // Construire le nom complet
final fullName = '${member.firstName} ${member.lastName}'.trim(); final fullName = '${member.firstName} ${member.lastName}'.trim();
return ListTile( return ListTile(
leading: CircleAvatar( leading: CircleAvatar(
backgroundImage: (member.profilePictureUrl != null && backgroundImage:
member.profilePictureUrl!.isNotEmpty) (member.profilePictureUrl != null &&
member.profilePictureUrl!.isNotEmpty)
? NetworkImage(member.profilePictureUrl!) ? NetworkImage(member.profilePictureUrl!)
: null, : null,
child: (member.profilePictureUrl == null || member.profilePictureUrl!.isEmpty) child:
(member.profilePictureUrl == null ||
member.profilePictureUrl!.isEmpty)
? Text(initials) ? Text(initials)
: null, : null,
), ),
@@ -743,8 +782,11 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
), ),
], ],
), ),
subtitle: member.role == 'admin' subtitle: member.role == 'admin'
? const Text('Administrateur', style: TextStyle(fontSize: 12)) ? const Text(
'Administrateur',
style: TextStyle(fontSize: 12),
)
: null, : null,
trailing: IconButton( trailing: IconButton(
icon: const Icon(Icons.edit, size: 18), icon: const Icon(Icons.edit, size: 18),
@@ -774,7 +816,8 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
backgroundColor: theme.dialogBackgroundColor, backgroundColor:
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
title: Text( title: Text(
'Changer le pseudo', 'Changer le pseudo',
style: theme.textTheme.titleLarge?.copyWith( style: theme.textTheme.titleLarge?.copyWith(
@@ -785,9 +828,7 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
controller: pseudoController, controller: pseudoController,
decoration: InputDecoration( decoration: InputDecoration(
hintText: 'Nouveau pseudo', hintText: 'Nouveau pseudo',
border: OutlineInputBorder( border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
borderRadius: BorderRadius.circular(8),
),
contentPadding: const EdgeInsets.symmetric( contentPadding: const EdgeInsets.symmetric(
horizontal: 16, horizontal: 16,
vertical: 12, vertical: 12,
@@ -825,11 +866,11 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
try { try {
final updatedMember = member.copyWith(pseudo: newPseudo); final updatedMember = member.copyWith(pseudo: newPseudo);
await _groupRepository.addMember(widget.group.id, updatedMember); await _groupRepository.addMember(widget.group.id, updatedMember);
if (mounted) { if (mounted) {
// Le stream listener va automatiquement mettre à jour les membres // Le stream listener va automatiquement mettre à jour les membres
// Pas besoin de fermer le dialog ou de faire un refresh manuel // Pas besoin de fermer le dialog ou de faire un refresh manuel
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Pseudo modifié en "$newPseudo"'), content: Text('Pseudo modifié en "$newPseudo"'),
@@ -848,4 +889,4 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
} }
} }
} }
} }

View File

@@ -144,12 +144,9 @@ class _GroupContentState extends State<GroupContent> {
final color = colors[group.name.hashCode.abs() % colors.length]; final color = colors[group.name.hashCode.abs() % colors.length];
// Membres de manière simple // Membres de manière simple
String memberInfo = '${group.members.length} membre(s)'; String memberInfo = '${group.memberIds.length} membre(s)';
if (group.members.isNotEmpty) { if (group.members.isNotEmpty) {
final names = group.members final names = group.members.take(2).map((m) => m.firstName).join(', ');
.take(2)
.map((m) => m.firstName)
.join(', ');
memberInfo += '\n$names'; memberInfo += '\n$names';
} }

View File

@@ -290,10 +290,13 @@ class _CalendarPageState extends State<CalendarPage> {
), ),
// Zone de drop pour le calendrier // Zone de drop pour le calendrier
DragTarget<Activity>( DragTarget<Activity>(
onWillAccept: (data) => true, onWillAcceptWithDetails: (details) => true,
onAccept: (activity) { onAcceptWithDetails: (details) {
if (_selectedDay != null) { if (_selectedDay != null) {
_selectTimeAndSchedule(activity, _selectedDay!); _selectTimeAndSchedule(
details.data,
_selectedDay!,
);
} }
}, },
builder: (context, candidateData, rejectedData) { builder: (context, candidateData, rejectedData) {

View File

@@ -22,9 +22,10 @@ import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../../services/place_image_service.dart'; import '../../services/place_image_service.dart';
import '../../services/trip_geocoding_service.dart'; import '../../services/trip_geocoding_service.dart';
import '../../services/logger_service.dart';
/// Create trip content widget for trip creation and editing functionality. /// Create trip content widget for trip creation and editing functionality.
/// ///
/// This widget provides a comprehensive form interface for creating new trips /// This widget provides a comprehensive form interface for creating new trips
/// or editing existing ones. Key features include: /// or editing existing ones. Key features include:
/// - Trip creation with validation /// - Trip creation with validation
@@ -34,22 +35,19 @@ import '../../services/trip_geocoding_service.dart';
/// - Group creation and member management /// - Group creation and member management
/// - Account setup for expense tracking /// - Account setup for expense tracking
/// - Integration with mapping services for location selection /// - Integration with mapping services for location selection
/// ///
/// The widget handles both creation and editing modes based on the /// The widget handles both creation and editing modes based on the
/// provided tripToEdit parameter. /// provided tripToEdit parameter.
class CreateTripContent extends StatefulWidget { class CreateTripContent extends StatefulWidget {
/// Optional trip to edit. If null, creates a new trip /// Optional trip to edit. If null, creates a new trip
final Trip? tripToEdit; final Trip? tripToEdit;
/// Creates a create trip content widget. /// Creates a create trip content widget.
/// ///
/// Args: /// Args:
/// [tripToEdit]: Optional trip to edit. If provided, the form will /// [tripToEdit]: Optional trip to edit. If provided, the form will
/// be populated with existing trip data for editing /// be populated with existing trip data for editing
const CreateTripContent({ const CreateTripContent({super.key, this.tripToEdit});
super.key,
this.tripToEdit,
});
@override @override
State<CreateTripContent> createState() => _CreateTripContentState(); State<CreateTripContent> createState() => _CreateTripContentState();
@@ -58,17 +56,17 @@ class CreateTripContent extends StatefulWidget {
class _CreateTripContentState extends State<CreateTripContent> { class _CreateTripContentState extends State<CreateTripContent> {
/// Service for handling and displaying errors /// Service for handling and displaying errors
final _errorService = ErrorService(); final _errorService = ErrorService();
/// Form validation key /// Form validation key
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
/// Text controllers for form fields /// Text controllers for form fields
final _titleController = TextEditingController(); final _titleController = TextEditingController();
final _descriptionController = TextEditingController(); final _descriptionController = TextEditingController();
final _locationController = TextEditingController(); final _locationController = TextEditingController();
final _budgetController = TextEditingController(); final _budgetController = TextEditingController();
final _participantController = TextEditingController(); final _participantController = TextEditingController();
/// Services for user and group operations /// Services for user and group operations
final _userService = UserService(); final _userService = UserService();
final _groupRepository = GroupRepository(); final _groupRepository = GroupRepository();
@@ -79,7 +77,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
/// Trip date variables /// Trip date variables
DateTime? _startDate; DateTime? _startDate;
DateTime? _endDate; DateTime? _endDate;
/// Loading and state management variables /// Loading and state management variables
bool _isLoading = false; bool _isLoading = false;
String? _createdTripId; String? _createdTripId;
@@ -127,7 +125,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
void _onLocationChanged() { void _onLocationChanged() {
final query = _locationController.text.trim(); final query = _locationController.text.trim();
if (query.length < 2) { if (query.length < 2) {
_hideSuggestions(); _hideSuggestions();
return; return;
@@ -151,14 +149,14 @@ class _CreateTripContentState extends State<CreateTripContent> {
'?input=${Uri.encodeComponent(query)}' '?input=${Uri.encodeComponent(query)}'
'&types=(cities)' '&types=(cities)'
'&language=fr' '&language=fr'
'&key=$_apiKey' '&key=$_apiKey',
); );
final response = await http.get(url); final response = await http.get(url);
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK') { if (data['status'] == 'OK') {
final predictions = data['predictions'] as List; final predictions = data['predictions'] as List;
setState(() { setState(() {
@@ -170,7 +168,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
}).toList(); }).toList();
_isLoadingSuggestions = false; _isLoadingSuggestions = false;
}); });
if (_placeSuggestions.isNotEmpty) { if (_placeSuggestions.isNotEmpty) {
_showSuggestions(); _showSuggestions();
} else { } else {
@@ -202,12 +200,14 @@ class _CreateTripContentState extends State<CreateTripContent> {
// Nouvelle méthode pour afficher les suggestions // Nouvelle méthode pour afficher les suggestions
void _showSuggestions() { void _showSuggestions() {
_hideSuggestions(); // Masquer d'abord les suggestions existantes _hideSuggestions(); // Masquer d'abord les suggestions existantes
if (_placeSuggestions.isEmpty) return; if (_placeSuggestions.isEmpty) return;
_suggestionsOverlay = OverlayEntry( _suggestionsOverlay = OverlayEntry(
builder: (context) => Positioned( 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( child: CompositedTransformFollower(
link: _layerLink, link: _layerLink,
showWhenUnlinked: false, showWhenUnlinked: false,
@@ -258,26 +258,32 @@ class _CreateTripContentState extends State<CreateTripContent> {
setState(() { setState(() {
_placeSuggestions = []; _placeSuggestions = [];
}); });
// Charger l'image du lieu sélectionné // Charger l'image du lieu sélectionné
_loadPlaceImage(suggestion.description); _loadPlaceImage(suggestion.description);
} }
/// Charge l'image du lieu depuis Google Places API /// Charge l'image du lieu depuis Google Places API
Future<void> _loadPlaceImage(String location) async { Future<void> _loadPlaceImage(String location) async {
print('CreateTripContent: Chargement de l\'image pour: $location'); LoggerService.info(
'CreateTripContent: Chargement de l\'image pour: $location',
);
try { try {
final imageUrl = await _placeImageService.getPlaceImageUrl(location); final imageUrl = await _placeImageService.getPlaceImageUrl(location);
print('CreateTripContent: Image URL reçue: $imageUrl'); LoggerService.info('CreateTripContent: Image URL reçue: $imageUrl');
if (mounted) { if (mounted) {
setState(() { setState(() {
_selectedImageUrl = imageUrl; _selectedImageUrl = imageUrl;
}); });
print('CreateTripContent: État mis à jour avec imageUrl: $_selectedImageUrl'); LoggerService.info(
'CreateTripContent: État mis à jour avec imageUrl: $_selectedImageUrl',
);
} }
} catch (e) { } 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) { if (mounted) {
_errorService.logError( _errorService.logError(
'create_trip_content.dart', 'create_trip_content.dart',
@@ -337,7 +343,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
}) { }) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDarkMode = theme.brightness == Brightness.dark; final isDarkMode = theme.brightness == Brightness.dark;
return TextFormField( return TextFormField(
controller: controller, controller: controller,
validator: validator, validator: validator,
@@ -349,42 +355,36 @@ class _CreateTripContentState extends State<CreateTripContent> {
decoration: InputDecoration( decoration: InputDecoration(
hintText: label, hintText: label,
hintStyle: theme.textTheme.bodyLarge?.copyWith( hintStyle: theme.textTheme.bodyLarge?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.5), color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
), ),
prefixIcon: Icon( prefixIcon: Icon(
icon, icon,
color: theme.colorScheme.onSurface.withOpacity(0.5), color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
), ),
suffixIcon: suffixIcon, suffixIcon: suffixIcon,
border: OutlineInputBorder( border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
borderSide: BorderSide( borderSide: BorderSide(
color: isDarkMode color: isDarkMode
? Colors.white.withOpacity(0.2) ? Colors.white.withValues(alpha: 0.2)
: Colors.black.withOpacity(0.2), : Colors.black.withValues(alpha: 0.2),
), ),
), ),
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
borderSide: BorderSide( borderSide: BorderSide(
color: isDarkMode color: isDarkMode
? Colors.white.withOpacity(0.2) ? Colors.white.withValues(alpha: 0.2)
: Colors.black.withOpacity(0.2), : Colors.black.withValues(alpha: 0.2),
), ),
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
borderSide: BorderSide( borderSide: BorderSide(color: Colors.teal, width: 2),
color: Colors.teal,
width: 2,
),
), ),
errorBorder: OutlineInputBorder( errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
borderSide: const BorderSide( borderSide: const BorderSide(color: Colors.red, width: 2),
color: Colors.red,
width: 2,
),
), ),
filled: true, filled: true,
fillColor: theme.cardColor, fillColor: theme.cardColor,
@@ -403,7 +403,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
}) { }) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDarkMode = theme.brightness == Brightness.dark; final isDarkMode = theme.brightness == Brightness.dark;
return InkWell( return InkWell(
onTap: onTap, onTap: onTap,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
@@ -413,27 +413,27 @@ class _CreateTripContentState extends State<CreateTripContent> {
color: theme.cardColor, color: theme.cardColor,
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
border: Border.all( border: Border.all(
color: isDarkMode color: isDarkMode
? Colors.white.withOpacity(0.2) ? Colors.white.withValues(alpha: 0.2)
: Colors.black.withOpacity(0.2), : Colors.black.withValues(alpha: 0.2),
), ),
), ),
child: Row( child: Row(
children: [ children: [
Icon( Icon(
Icons.calendar_today, Icons.calendar_today,
color: theme.colorScheme.onSurface.withOpacity(0.5), color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
size: 20, size: 20,
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
Text( Text(
date != null date != null
? '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}' ? '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}'
: 'mm/dd/yyyy', : 'mm/dd/yyyy',
style: theme.textTheme.bodyLarge?.copyWith( style: theme.textTheme.bodyLarge?.copyWith(
color: date != null color: date != null
? theme.colorScheme.onSurface ? theme.colorScheme.onSurface
: theme.colorScheme.onSurface.withOpacity(0.5), : theme.colorScheme.onSurface.withValues(alpha: 0.5),
), ),
), ),
], ],
@@ -442,11 +442,11 @@ class _CreateTripContentState extends State<CreateTripContent> {
); );
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isDarkMode = theme.brightness == Brightness.dark; final isDarkMode = theme.brightness == Brightness.dark;
return BlocListener<TripBloc, TripState>( return BlocListener<TripBloc, TripState>(
listener: (context, tripState) { listener: (context, tripState) {
if (tripState is TripCreated) { if (tripState is TripCreated) {
@@ -454,7 +454,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
_createGroupAndAccountForTrip(_createdTripId!); _createGroupAndAccountForTrip(_createdTripId!);
} else if (tripState is TripOperationSuccess) { } else if (tripState is TripOperationSuccess) {
if (mounted) { if (mounted) {
_errorService.showSnackbar(message: tripState.message, isError: false); _errorService.showSnackbar(
message: tripState.message,
isError: false,
);
setState(() { setState(() {
_isLoading = false; _isLoading = false;
}); });
@@ -465,7 +468,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
} }
} else if (tripState is TripError) { } else if (tripState is TripError) {
if (mounted) { if (mounted) {
_errorService.showSnackbar(message: tripState.message, isError: true); _errorService.showSnackbar(
message: tripState.message,
isError: true,
);
setState(() { setState(() {
_isLoading = false; _isLoading = false;
}); });
@@ -478,7 +484,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
return Scaffold( return Scaffold(
backgroundColor: theme.scaffoldBackgroundColor, backgroundColor: theme.scaffoldBackgroundColor,
appBar: AppBar( 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, backgroundColor: theme.appBarTheme.backgroundColor,
foregroundColor: theme.appBarTheme.foregroundColor, foregroundColor: theme.appBarTheme.foregroundColor,
), ),
@@ -506,7 +514,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
elevation: 0, elevation: 0,
leading: IconButton( leading: IconButton(
icon: Icon(Icons.arrow_back, color: theme.colorScheme.onSurface), icon: Icon(
Icons.arrow_back,
color: theme.colorScheme.onSurface,
),
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
), ),
), ),
@@ -519,7 +530,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20),
boxShadow: [ boxShadow: [
BoxShadow( BoxShadow(
color: Colors.black.withOpacity(isDarkMode ? 0.3 : 0.1), color: Colors.black.withValues(
alpha: isDarkMode ? 0.3 : 0.1,
),
blurRadius: 10, blurRadius: 10,
offset: const Offset(0, 5), offset: const Offset(0, 5),
), ),
@@ -544,7 +557,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
Text( Text(
'Donne un nom à ton voyage', 'Donne un nom à ton voyage',
style: theme.textTheme.bodyMedium?.copyWith( style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.7), color: theme.colorScheme.onSurface.withValues(
alpha: 0.7,
),
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
@@ -588,7 +603,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
? const SizedBox( ? const SizedBox(
width: 20, width: 20,
height: 20, height: 20,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(
strokeWidth: 2,
),
) )
: null, : null,
), ),
@@ -667,7 +684,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
controller: _budgetController, controller: _budgetController,
label: 'Ex : 500', label: 'Ex : 500',
icon: Icons.euro, icon: Icons.euro,
keyboardType: TextInputType.numberWithOptions(decimal: true), keyboardType: TextInputType.numberWithOptions(
decimal: true,
),
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
@@ -701,7 +720,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
), ),
child: IconButton( child: IconButton(
onPressed: _addParticipant, onPressed: _addParticipant,
icon: const Icon(Icons.add, color: Colors.white), icon: const Icon(
Icons.add,
color: Colors.white,
),
), ),
), ),
], ],
@@ -720,7 +742,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
vertical: 8, vertical: 8,
), ),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.teal.withOpacity(0.1), color: Colors.teal.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20),
), ),
child: Row( child: Row(
@@ -728,10 +750,11 @@ class _CreateTripContentState extends State<CreateTripContent> {
children: [ children: [
Text( Text(
email, email,
style: theme.textTheme.bodySmall?.copyWith( style: theme.textTheme.bodySmall
color: Colors.teal, ?.copyWith(
fontWeight: FontWeight.w500, color: Colors.teal,
), fontWeight: FontWeight.w500,
),
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
GestureDetector( GestureDetector(
@@ -758,7 +781,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
width: double.infinity, width: double.infinity,
height: 56, height: 56,
child: ElevatedButton( child: ElevatedButton(
onPressed: _isLoading ? null : () => _saveTrip(userState.user), onPressed: _isLoading
? null
: () => _saveTrip(userState.user),
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal, backgroundColor: Colors.teal,
foregroundColor: Colors.white, foregroundColor: Colors.white,
@@ -773,15 +798,20 @@ class _CreateTripContentState extends State<CreateTripContent> {
height: 20, height: 20,
child: CircularProgressIndicator( child: CircularProgressIndicator(
strokeWidth: 2, strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white), valueColor: AlwaysStoppedAnimation<Color>(
Colors.white,
),
), ),
) )
: Text( : Text(
isEditing ? 'Modifier le voyage' : 'Créer le voyage', isEditing
style: theme.textTheme.titleMedium?.copyWith( ? 'Modifier le voyage'
color: Colors.white, : 'Créer le voyage',
fontWeight: FontWeight.w600, 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}$'); final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
if (!emailRegex.hasMatch(email)) { if (!emailRegex.hasMatch(email)) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Email invalide'))); ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Email invalide')));
} }
return; return;
} }
if (_participants.contains(email)) { if (_participants.contains(email)) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context).showSnackBar(
.showSnackBar(SnackBar(content: Text('Ce participant est déjà ajouté'))); SnackBar(content: Text('Ce participant est déjà ajouté')),
);
} }
return; return;
} }
@@ -879,7 +912,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
) async { ) async {
final groupBloc = context.read<GroupBloc>(); final groupBloc = context.read<GroupBloc>();
final accountBloc = context.read<AccountBloc>(); final accountBloc = context.read<AccountBloc>();
try { try {
final group = await _groupRepository.getGroupByTripId(tripId); final group = await _groupRepository.getGroupByTripId(tripId);
@@ -900,7 +933,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
final currentMemberIds = currentMembers.map((m) => m.userId).toSet(); final currentMemberIds = currentMembers.map((m) => m.userId).toSet();
final newMemberIds = newMembers.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 final membersToRemove = currentMembers
.where((m) => !newMemberIds.contains(m.userId) && m.role != 'admin') .where((m) => !newMemberIds.contains(m.userId) && m.role != 'admin')
@@ -961,14 +996,16 @@ class _CreateTripContentState extends State<CreateTripContent> {
role: 'admin', role: 'admin',
profilePictureUrl: currentUser.profilePictureUrl, profilePictureUrl: currentUser.profilePictureUrl,
), ),
...participantsData.map((p) => GroupMember( ...participantsData.map(
userId: p['id'] as String, (p) => GroupMember(
firstName: p['firstName'] as String, userId: p['id'] as String,
lastName: p['lastName'] as String? ?? '', firstName: p['firstName'] as String,
pseudo: p['firstName'] as String, lastName: p['lastName'] as String? ?? '',
role: 'member', pseudo: p['firstName'] as String,
profilePictureUrl: p['profilePictureUrl'] as String?, role: 'member',
)), profilePictureUrl: p['profilePictureUrl'] as String?,
),
),
]; ];
return groupMembers; return groupMembers;
} }
@@ -976,9 +1013,8 @@ class _CreateTripContentState extends State<CreateTripContent> {
Future<void> _createGroupAndAccountForTrip(String tripId) async { Future<void> _createGroupAndAccountForTrip(String tripId) async {
final groupBloc = context.read<GroupBloc>(); final groupBloc = context.read<GroupBloc>();
final accountBloc = context.read<AccountBloc>(); final accountBloc = context.read<AccountBloc>();
try { try {
final userState = context.read<UserBloc>().state; final userState = context.read<UserBloc>().state;
if (userState is! user_state.UserLoaded) { if (userState is! user_state.UserLoaded) {
throw Exception('Utilisateur non connecté'); throw Exception('Utilisateur non connecté');
@@ -998,21 +1034,19 @@ class _CreateTripContentState extends State<CreateTripContent> {
throw Exception('Erreur lors de la création des membres du groupe'); throw Exception('Erreur lors de la création des membres du groupe');
} }
groupBloc.add(CreateGroupWithMembers( groupBloc.add(
group: group, CreateGroupWithMembers(group: group, members: groupMembers),
members: groupMembers, );
));
final account = Account( final account = Account(
id: '', id: '',
tripId: tripId, tripId: tripId,
name: _titleController.text.trim(), name: _titleController.text.trim(),
); );
accountBloc.add(CreateAccountWithMembers( accountBloc.add(
account: account, CreateAccountWithMembers(account: account, members: groupMembers),
members: groupMembers, );
));
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
@@ -1025,7 +1059,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
}); });
Navigator.pop(context); Navigator.pop(context);
} }
} catch (e) { } catch (e) {
_errorService.logError( _errorService.logError(
'create_trip_content.dart', 'create_trip_content.dart',
@@ -1034,10 +1067,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
content: Text('Erreur: $e'),
backgroundColor: Colors.red,
),
); );
setState(() { setState(() {
_isLoading = false; _isLoading = false;
@@ -1046,8 +1076,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
} }
} }
Future<void> _saveTrip(user_state.UserModel currentUser) async { Future<void> _saveTrip(user_state.UserModel currentUser) async {
if (!_formKey.currentState!.validate()) { if (!_formKey.currentState!.validate()) {
return; return;
@@ -1070,7 +1098,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
try { try {
final participantsData = await _getParticipantsData(_participants); 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)) { if (!participantIds.contains(currentUser.id)) {
participantIds.insert(0, currentUser.id); participantIds.insert(0, currentUser.id);
@@ -1101,7 +1131,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( 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, backgroundColor: Colors.orange,
duration: Duration(seconds: 2), duration: Duration(seconds: 2),
), ),
@@ -1114,16 +1146,21 @@ class _CreateTripContentState extends State<CreateTripContent> {
tripBloc.add(TripUpdateRequested(trip: tripWithCoordinates)); tripBloc.add(TripUpdateRequested(trip: tripWithCoordinates));
// Mettre à jour le groupe ET les comptes avec les nouveaux participants // Mettre à jour le groupe ET les comptes avec les nouveaux participants
if (widget.tripToEdit != null && widget.tripToEdit!.id != null && widget.tripToEdit!.id!.isNotEmpty) { if (widget.tripToEdit != null &&
print('🔄 [CreateTrip] Mise à jour du groupe et du compte pour le voyage ID: ${widget.tripToEdit!.id}'); widget.tripToEdit!.id != null &&
print('👥 Participants: ${participantsData.map((p) => p['id']).toList()}'); 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( await _updateGroupAndAccountMembers(
widget.tripToEdit!.id!, widget.tripToEdit!.id!,
currentUser, currentUser,
participantsData, participantsData,
); );
} }
} else { } else {
// Mode création - Le groupe sera créé dans le listener TripCreated // Mode création - Le groupe sera créé dans le listener TripCreated
tripBloc.add(TripCreateRequested(trip: tripWithCoordinates)); tripBloc.add(TripCreateRequested(trip: tripWithCoordinates));
@@ -1131,10 +1168,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(content: Text('Erreur: $e'), backgroundColor: Colors.red),
content: Text('Erreur: $e'),
backgroundColor: Colors.red,
),
); );
setState(() { setState(() {
@@ -1144,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 = []; List<Map<String, dynamic>> participantsData = [];
for (String email in emails) { for (String email in emails) {
@@ -1188,8 +1224,5 @@ class PlaceSuggestion {
final String placeId; final String placeId;
final String description; final String description;
PlaceSuggestion({ PlaceSuggestion({required this.placeId, required this.description});
required this.placeId, }
required this.description,
});
}

View File

@@ -100,7 +100,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return AlertDialog( return AlertDialog(
backgroundColor: theme.dialogBackgroundColor, backgroundColor:
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
title: Text( title: Text(
'Ouvrir la carte', 'Ouvrir la carte',
style: theme.textTheme.titleLarge?.copyWith( style: theme.textTheme.titleLarge?.copyWith(
@@ -612,7 +613,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => AlertDialog(
backgroundColor: theme.dialogBackgroundColor, backgroundColor:
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
title: Text( title: Text(
'Confirmer la suppression', 'Confirmer la suppression',
style: theme.textTheme.titleLarge?.copyWith( style: theme.textTheme.titleLarge?.copyWith(
@@ -814,7 +816,8 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return AlertDialog( return AlertDialog(
backgroundColor: theme.dialogBackgroundColor, backgroundColor:
theme.dialogTheme.backgroundColor ?? theme.colorScheme.surface,
title: Text( title: Text(
'Ajouter un participant', 'Ajouter un participant',
style: theme.textTheme.titleLarge?.copyWith( style: theme.textTheme.titleLarge?.copyWith(

View File

@@ -57,7 +57,7 @@ class _LoadingContentState extends State<LoadingContent>
widget.onComplete!(); widget.onComplete!();
} }
} catch (e) { } 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');
} }
} }
} }

View File

@@ -21,19 +21,20 @@ class _MapContentState extends State<MapContent> {
bool _isLoadingLocation = false; bool _isLoadingLocation = false;
bool _isSearching = false; bool _isSearching = false;
Position? _currentPosition; Position? _currentPosition;
final Set<Marker> _markers = {}; final Set<Marker> _markers = {};
final Set<Circle> _circles = {}; final Set<Circle> _circles = {};
List<PlaceSuggestion> _suggestions = []; List<PlaceSuggestion> _suggestions = [];
static final String _apiKey = dotenv.env['GOOGLE_MAPS_API_KEY'] ?? ''; static final String _apiKey = dotenv.env['GOOGLE_MAPS_API_KEY'] ?? '';
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// Si une recherche initiale est fournie, la pré-remplir et lancer la recherche // 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!; _searchController.text = widget.initialSearchQuery!;
// Lancer la recherche automatiquement après un court délai pour laisser l'interface se charger // Lancer la recherche automatiquement après un court délai pour laisser l'interface se charger
Future.delayed(const Duration(milliseconds: 500), () { Future.delayed(const Duration(milliseconds: 500), () {
@@ -65,17 +66,19 @@ class _MapContentState extends State<MapContent> {
'https://maps.googleapis.com/maps/api/place/autocomplete/json' 'https://maps.googleapis.com/maps/api/place/autocomplete/json'
'?input=${Uri.encodeComponent(query)}' '?input=${Uri.encodeComponent(query)}'
'&key=$_apiKey' '&key=$_apiKey'
'&language=fr' '&language=fr',
); );
final response = await http.get(url); final response = await http.get(url);
if (!mounted) return;
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK') { if (data['status'] == 'OK') {
final predictions = data['predictions'] as List; final predictions = data['predictions'] as List;
if (predictions.isNotEmpty) { if (predictions.isNotEmpty) {
// Prendre automatiquement la première suggestion // Prendre automatiquement la première suggestion
final firstPrediction = predictions.first; final firstPrediction = predictions.first;
@@ -83,7 +86,7 @@ class _MapContentState extends State<MapContent> {
placeId: firstPrediction['place_id'], placeId: firstPrediction['place_id'],
description: firstPrediction['description'], description: firstPrediction['description'],
); );
// Effectuer la sélection automatique // Effectuer la sélection automatique
await _selectPlaceForInitialSearch(suggestion); await _selectPlaceForInitialSearch(suggestion);
} else { } else {
@@ -117,9 +120,11 @@ class _MapContentState extends State<MapContent> {
final response = await http.get(url); final response = await http.get(url);
if (!mounted) return;
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK') { if (data['status'] == 'OK') {
final location = data['result']['geometry']['location']; final location = data['result']['geometry']['location'];
final lat = location['lat']; final lat = location['lat'];
@@ -132,7 +137,7 @@ class _MapContentState extends State<MapContent> {
setState(() { setState(() {
// Garder le marqueur de position utilisateur s'il existe // Garder le marqueur de position utilisateur s'il existe
_markers.removeWhere((m) => m.markerId.value != 'user_location'); _markers.removeWhere((m) => m.markerId.value != 'user_location');
// Ajouter le nouveau marqueur de lieu // Ajouter le nouveau marqueur de lieu
_markers.add( _markers.add(
Marker( Marker(
@@ -230,9 +235,7 @@ class _MapContentState extends State<MapContent> {
const size = 120.0; const size = 120.0;
// Dessiner l'icône person_pin_circle en bleu // Dessiner l'icône person_pin_circle en bleu
final iconPainter = TextPainter( final iconPainter = TextPainter(textDirection: TextDirection.ltr);
textDirection: TextDirection.ltr,
);
iconPainter.text = TextSpan( iconPainter.text = TextSpan(
text: String.fromCharCode(Icons.person_pin_circle.codePoint), text: String.fromCharCode(Icons.person_pin_circle.codePoint),
style: TextStyle( style: TextStyle(
@@ -242,26 +245,20 @@ class _MapContentState extends State<MapContent> {
), ),
); );
iconPainter.layout(); iconPainter.layout();
iconPainter.paint( iconPainter.paint(canvas, Offset((size - iconPainter.width) / 2, 0));
canvas,
Offset(
(size - iconPainter.width) / 2,
0,
),
);
final picture = pictureRecorder.endRecording(); final picture = pictureRecorder.endRecording();
final image = await picture.toImage(size.toInt(), size.toInt()); final image = await picture.toImage(size.toInt(), size.toInt());
final bytes = await image.toByteData(format: ui.ImageByteFormat.png); 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 // Ajouter le marqueur avec l'icône personnalisée
Future<void> _addUserLocationMarker(LatLng position) async { Future<void> _addUserLocationMarker(LatLng position) async {
_markers.clear(); _markers.clear();
_circles.clear(); _circles.clear();
// Ajouter un cercle de précision // Ajouter un cercle de précision
_circles.add( _circles.add(
Circle( Circle(
@@ -284,10 +281,14 @@ class _MapContentState extends State<MapContent> {
markerId: const MarkerId('user_location'), markerId: const MarkerId('user_location'),
position: position, position: position,
icon: icon, 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( infoWindow: InfoWindow(
title: 'Ma position', 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,23 +312,27 @@ class _MapContentState extends State<MapContent> {
'https://maps.googleapis.com/maps/api/place/autocomplete/json' 'https://maps.googleapis.com/maps/api/place/autocomplete/json'
'?input=${Uri.encodeComponent(query)}' '?input=${Uri.encodeComponent(query)}'
'&key=$_apiKey' '&key=$_apiKey'
'&language=fr' '&language=fr',
); );
final response = await http.get(url); final response = await http.get(url);
if (!mounted) return;
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK') { if (data['status'] == 'OK') {
final predictions = data['predictions'] as List; final predictions = data['predictions'] as List;
setState(() { setState(() {
_suggestions = predictions _suggestions = predictions
.map((p) => PlaceSuggestion( .map(
placeId: p['place_id'], (p) => PlaceSuggestion(
description: p['description'], placeId: p['place_id'],
)) description: p['description'],
),
)
.toList(); .toList();
_isSearching = false; _isSearching = false;
}); });
@@ -363,9 +368,11 @@ class _MapContentState extends State<MapContent> {
final response = await http.get(url); final response = await http.get(url);
if (!mounted) return;
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK') { if (data['status'] == 'OK') {
final location = data['result']['geometry']['location']; final location = data['result']['geometry']['location'];
final lat = location['lat']; final lat = location['lat'];
@@ -378,7 +385,7 @@ class _MapContentState extends State<MapContent> {
setState(() { setState(() {
// Garder le marqueur de position utilisateur // Garder le marqueur de position utilisateur
_markers.removeWhere((m) => m.markerId.value != 'user_location'); _markers.removeWhere((m) => m.markerId.value != 'user_location');
// Ajouter le nouveau marqueur de lieu // Ajouter le nouveau marqueur de lieu
_markers.add( _markers.add(
Marker( Marker(
@@ -394,7 +401,9 @@ class _MapContentState extends State<MapContent> {
CameraUpdate.newLatLngZoom(newPosition, 15), CameraUpdate.newLatLngZoom(newPosition, 15),
); );
FocusScope.of(context).unfocus(); if (mounted) {
FocusScope.of(context).unfocus();
}
} }
} }
} catch (e) { } catch (e) {
@@ -545,7 +554,10 @@ class _MapContentState extends State<MapContent> {
: Icon(Icons.search, color: Colors.grey[700]), : Icon(Icons.search, color: Colors.grey[700]),
suffixIcon: _searchController.text.isNotEmpty suffixIcon: _searchController.text.isNotEmpty
? IconButton( ? IconButton(
icon: Icon(Icons.clear, color: Colors.grey[700]), icon: Icon(
Icons.clear,
color: Colors.grey[700],
),
onPressed: () { onPressed: () {
_searchController.clear(); _searchController.clear();
setState(() { setState(() {
@@ -567,7 +579,8 @@ class _MapContentState extends State<MapContent> {
), ),
onChanged: (value) { onChanged: (value) {
// Ne pas rechercher si c'est juste le remplissage initial // 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; return;
} }
_searchPlaces(value); _searchPlaces(value);
@@ -601,10 +614,8 @@ class _MapContentState extends State<MapContent> {
shrinkWrap: true, shrinkWrap: true,
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
itemCount: _suggestions.length, itemCount: _suggestions.length,
separatorBuilder: (context, index) => Divider( separatorBuilder: (context, index) =>
height: 1, Divider(height: 1, color: Colors.grey[300]),
color: Colors.grey[300],
),
itemBuilder: (context, index) { itemBuilder: (context, index) {
final suggestion = _suggestions[index]; final suggestion = _suggestions[index];
return InkWell( return InkWell(
@@ -664,8 +675,5 @@ class PlaceSuggestion {
final String placeId; final String placeId;
final String description; final String description;
PlaceSuggestion({ PlaceSuggestion({required this.placeId, required this.description});
required this.placeId, }
required this.description,
});
}

View File

@@ -9,6 +9,7 @@ import '../../../blocs/user/user_bloc.dart';
import '../../../blocs/user/user_state.dart' as user_state; import '../../../blocs/user/user_state.dart' as user_state;
import '../../../blocs/user/user_event.dart' as user_event; import '../../../blocs/user/user_event.dart' as user_event;
import '../../../services/auth_service.dart'; import '../../../services/auth_service.dart';
import '../../../services/logger_service.dart';
class ProfileContent extends StatelessWidget { class ProfileContent extends StatelessWidget {
ProfileContent({super.key}); ProfileContent({super.key});
@@ -19,7 +20,8 @@ class ProfileContent extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return UserStateWrapper( return UserStateWrapper(
builder: (context, user) { builder: (context, user) {
final isEmailAuth = user.authMethod == 'email' || user.authMethod == null; final isEmailAuth =
user.authMethod == 'email' || user.authMethod == null;
return SingleChildScrollView( return SingleChildScrollView(
child: Column( child: Column(
@@ -40,10 +42,12 @@ class ProfileContent extends StatelessWidget {
color: Colors.black.withValues(alpha: 0.1), color: Colors.black.withValues(alpha: 0.1),
blurRadius: 8, blurRadius: 8,
offset: Offset(0, 2), offset: Offset(0, 2),
) ),
], ],
), ),
child: user.profilePictureUrl != null && user.profilePictureUrl!.isNotEmpty child:
user.profilePictureUrl != null &&
user.profilePictureUrl!.isNotEmpty
? CircleAvatar( ? CircleAvatar(
radius: 50, radius: 50,
backgroundImage: NetworkImage( backgroundImage: NetworkImage(
@@ -57,7 +61,9 @@ class ProfileContent extends StatelessWidget {
) )
: CircleAvatar( : CircleAvatar(
radius: 50, radius: 50,
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(
context,
).colorScheme.primary,
child: Text( child: Text(
user.prenom.isNotEmpty user.prenom.isNotEmpty
? user.prenom[0].toUpperCase() ? user.prenom[0].toUpperCase()
@@ -88,10 +94,7 @@ class ProfileContent extends StatelessWidget {
// Email // Email
Text( Text(
user.email, user.email,
style: TextStyle( style: TextStyle(fontSize: 14, color: Colors.grey[600]),
fontSize: 14,
color: Colors.grey[600],
),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
@@ -99,7 +102,10 @@ class ProfileContent extends StatelessWidget {
// Badge de méthode de connexion // Badge de méthode de connexion
Container( Container(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6), padding: EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration( decoration: BoxDecoration(
color: _getAuthMethodColor(user.authMethod, context), color: _getAuthMethodColor(user.authMethod, context),
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
@@ -120,7 +126,10 @@ class ProfileContent extends StatelessWidget {
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 12,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: _getAuthMethodTextColor(user.authMethod, context), color: _getAuthMethodTextColor(
user.authMethod,
context,
),
), ),
), ),
], ],
@@ -314,17 +323,13 @@ class ProfileContent extends StatelessWidget {
style: TextStyle( style: TextStyle(
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: isDestructive color: isDestructive
? Colors.red ? Colors.red
: (isDarkMode ? Colors.white : Colors.black87), : (isDarkMode ? Colors.white : Colors.black87),
), ),
), ),
), ),
Icon( Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
Icons.arrow_forward_ios,
size: 16,
color: Colors.grey[400],
),
], ],
), ),
), ),
@@ -355,7 +360,7 @@ class ProfileContent extends StatelessWidget {
Color _getAuthMethodColor(String? authMethod, BuildContext context) { Color _getAuthMethodColor(String? authMethod, BuildContext context) {
final isDarkMode = Theme.of(context).brightness == Brightness.dark; final isDarkMode = Theme.of(context).brightness == Brightness.dark;
switch (authMethod) { switch (authMethod) {
case 'apple': case 'apple':
return isDarkMode ? Colors.white : Colors.black87; return isDarkMode ? Colors.white : Colors.black87;
@@ -368,7 +373,7 @@ class ProfileContent extends StatelessWidget {
Color _getAuthMethodTextColor(String? authMethod, BuildContext context) { Color _getAuthMethodTextColor(String? authMethod, BuildContext context) {
final isDarkMode = Theme.of(context).brightness == Brightness.dark; final isDarkMode = Theme.of(context).brightness == Brightness.dark;
switch (authMethod) { switch (authMethod) {
case 'apple': case 'apple':
return isDarkMode ? Colors.black87 : Colors.white; return isDarkMode ? Colors.black87 : Colors.white;
@@ -401,7 +406,9 @@ class ProfileContent extends StatelessWidget {
children: [ children: [
CircleAvatar( CircleAvatar(
radius: 50, radius: 50,
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(
context,
).colorScheme.primary,
child: Text( child: Text(
prenomController.text.isNotEmpty prenomController.text.isNotEmpty
? prenomController.text[0].toUpperCase() ? prenomController.text[0].toUpperCase()
@@ -422,7 +429,11 @@ class ProfileContent extends StatelessWidget {
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
), ),
child: IconButton( child: IconButton(
icon: Icon(Icons.camera_alt, color: Colors.white, size: 20), icon: Icon(
Icons.camera_alt,
color: Colors.white,
size: 20,
),
onPressed: () { onPressed: () {
_showPhotoPickerDialog(dialogContext); _showPhotoPickerDialog(dialogContext);
}, },
@@ -511,60 +522,66 @@ class ProfileContent extends StatelessWidget {
void _showPhotoPickerDialog(BuildContext context) { void _showPhotoPickerDialog(BuildContext context) {
// Récupérer les références AVANT que le modal ne se ferme // Récupérer les références AVANT que le modal ne se ferme
final userBloc = context.read<UserBloc>(); final userBloc = context.read<UserBloc>();
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
builder: (BuildContext sheetContext) { builder: (BuildContext sheetContext) {
return Container( return Wrap(
child: Wrap( children: [
children: [ ListTile(
ListTile( leading: Icon(Icons.photo_library),
leading: Icon(Icons.photo_library), title: Text('Galerie'),
title: Text('Galerie'), onTap: () {
onTap: () { Navigator.pop(sheetContext);
Navigator.pop(sheetContext); _pickImageFromGallery(context, userBloc);
_pickImageFromGallery(context, userBloc); },
}, ),
), ListTile(
ListTile( leading: Icon(Icons.camera_alt),
leading: Icon(Icons.camera_alt), title: Text('Caméra'),
title: Text('Caméra'), onTap: () {
onTap: () { Navigator.pop(sheetContext);
Navigator.pop(sheetContext); _pickImageFromCamera(context, userBloc);
_pickImageFromCamera(context, userBloc); },
}, ),
), ListTile(
ListTile( leading: Icon(Icons.close),
leading: Icon(Icons.close), title: Text('Annuler'),
title: Text('Annuler'), onTap: () => Navigator.pop(sheetContext),
onTap: () => Navigator.pop(sheetContext), ),
), ],
],
),
); );
}, },
); );
} }
Future<void> _pickImageFromGallery(BuildContext context, UserBloc userBloc) async { Future<void> _pickImageFromGallery(
BuildContext context,
UserBloc userBloc,
) async {
try { try {
final ImagePicker picker = ImagePicker(); final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.gallery); final XFile? image = await picker.pickImage(source: ImageSource.gallery);
if (image != null) { if (image != null && context.mounted) {
await _uploadProfilePicture(context, image.path, userBloc); await _uploadProfilePicture(context, image.path, userBloc);
} }
} catch (e) { } 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 { try {
final ImagePicker picker = ImagePicker(); final ImagePicker picker = ImagePicker();
final XFile? image = await picker.pickImage(source: ImageSource.camera); final XFile? image = await picker.pickImage(source: ImageSource.camera);
if (image != null) { if (image != null && context.mounted) {
await _uploadProfilePicture(context, image.path, userBloc); await _uploadProfilePicture(context, image.path, userBloc);
} }
} catch (e) { } catch (e) {
@@ -572,17 +589,23 @@ class ProfileContent extends StatelessWidget {
} }
} }
Future<void> _uploadProfilePicture(BuildContext context, String imagePath, UserBloc userBloc) async { Future<void> _uploadProfilePicture(
BuildContext context,
String imagePath,
UserBloc userBloc,
) async {
try { try {
final File imageFile = File(imagePath); final File imageFile = File(imagePath);
// Vérifier que le fichier existe // Vérifier que le fichier existe
if (!await imageFile.exists()) { if (!await imageFile.exists()) {
_errorService.showError(message: 'Le fichier image n\'existe pas'); _errorService.showError(message: 'Le fichier image n\'existe pas');
return; return;
} }
print('DEBUG: Taille du fichier: ${imageFile.lengthSync()} bytes'); LoggerService.info(
'DEBUG: Taille du fichier: ${imageFile.lengthSync()} bytes',
);
final userState = userBloc.state; final userState = userBloc.state;
if (userState is! user_state.UserLoaded) { if (userState is! user_state.UserLoaded) {
@@ -591,30 +614,35 @@ class ProfileContent extends StatelessWidget {
} }
final user = userState.user; final user = userState.user;
// Créer un nom unique pour la photo // 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 final Reference storageRef = FirebaseStorage.instance
.ref() .ref()
.child('profile_pictures') .child('profile_pictures')
.child(fileName); .child(fileName);
print('DEBUG: Chemin Storage: ${storageRef.fullPath}'); LoggerService.info('DEBUG: Chemin Storage: ${storageRef.fullPath}');
print('DEBUG: Upload en cours pour $fileName'); LoggerService.info('DEBUG: Upload en cours pour $fileName');
// Uploader l'image avec gestion d'erreur détaillée // Uploader l'image avec gestion d'erreur détaillée
try { try {
final uploadTask = storageRef.putFile(imageFile); final uploadTask = storageRef.putFile(imageFile);
// Écouter la progression // Écouter la progression
uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) { uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
print('DEBUG: Progression: ${snapshot.bytesTransferred}/${snapshot.totalBytes}'); LoggerService.info(
'DEBUG: Progression: ${snapshot.bytesTransferred}/${snapshot.totalBytes}',
);
}); });
final snapshot = await uploadTask; final snapshot = await uploadTask;
print('DEBUG: Upload terminé. État: ${snapshot.state}'); LoggerService.info('DEBUG: Upload terminé. État: ${snapshot.state}');
} on FirebaseException catch (e) { } 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) { if (context.mounted) {
_errorService.showError( _errorService.showError(
message: 'Erreur Firebase: ${e.code}\n${e.message}', message: 'Erreur Firebase: ${e.code}\n${e.message}',
@@ -623,26 +651,22 @@ class ProfileContent extends StatelessWidget {
return; 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 // Récupérer l'URL
final String downloadUrl = await storageRef.getDownloadURL(); 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 // 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'); LoggerService.info('DEBUG: Envoi de UserUpdated event au BLoC');
userBloc.add( userBloc.add(user_event.UserUpdated({'profilePictureUrl': downloadUrl}));
user_event.UserUpdated({
'profilePictureUrl': downloadUrl,
}),
);
// Attendre un peu que Firestore se mette à jour // Attendre un peu que Firestore se mette à jour
await Future.delayed(Duration(milliseconds: 500)); await Future.delayed(Duration(milliseconds: 500));
if (context.mounted) { if (context.mounted) {
print('DEBUG: Affichage du succès'); LoggerService.info('DEBUG: Affichage du succès');
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Photo de profil mise à jour !'), content: Text('Photo de profil mise à jour !'),
@@ -651,8 +675,8 @@ class ProfileContent extends StatelessWidget {
); );
} }
} catch (e, stackTrace) { } catch (e, stackTrace) {
print('DEBUG: Erreur lors de l\'upload: $e'); LoggerService.error('DEBUG: Erreur lors de l\'upload: $e');
print('DEBUG: Stack trace: $stackTrace'); LoggerService.error('DEBUG: Stack trace: $stackTrace');
_errorService.logError( _errorService.logError(
'ProfileContent - _uploadProfilePicture', 'ProfileContent - _uploadProfilePicture',
'Erreur lors de l\'upload de la photo: $e\n$stackTrace', 'Erreur lors de l\'upload de la photo: $e\n$stackTrace',
@@ -738,13 +762,15 @@ class ProfileContent extends StatelessWidget {
email: user.email, email: user.email,
); );
Navigator.of(dialogContext).pop(); if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( Navigator.of(dialogContext).pop();
SnackBar( ScaffoldMessenger.of(context).showSnackBar(
content: Text('Mot de passe changé !'), SnackBar(
backgroundColor: Colors.green, content: Text('Mot de passe changé !'),
), backgroundColor: Colors.green,
); ),
);
}
} catch (e) { } catch (e) {
_errorService.showError( _errorService.showError(
message: 'Erreur: Mot de passe actuel incorrect', message: 'Erreur: Mot de passe actuel incorrect',
@@ -801,13 +827,15 @@ class ProfileContent extends StatelessWidget {
email: user.email, email: user.email,
); );
Navigator.of(dialogContext).pop(); if (context.mounted) {
context.read<UserBloc>().add(user_event.UserLoggedOut()); Navigator.of(dialogContext).pop();
Navigator.pushNamedAndRemoveUntil( context.read<UserBloc>().add(user_event.UserLoggedOut());
context, Navigator.pushNamedAndRemoveUntil(
'/login', context,
(route) => false, '/login',
); (route) => false,
);
}
} catch (e) { } catch (e) {
_errorService.showError( _errorService.showError(
message: 'Erreur: Mot de passe incorrect', message: 'Erreur: Mot de passe incorrect',

View File

@@ -46,7 +46,7 @@ class Activity {
/// Calcule le score total des votes /// Calcule le score total des votes
int get totalVotes { 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 /// Calcule le nombre de votes positifs

View File

@@ -4,107 +4,114 @@ import 'package:flutter/material.dart';
import 'expense_split.dart'; import 'expense_split.dart';
/// Enumeration of supported currencies for expenses. /// Enumeration of supported currencies for expenses.
/// ///
/// Each currency includes both a display symbol and standard currency code. /// Each currency includes both a display symbol and standard currency code.
enum ExpenseCurrency { enum ExpenseCurrency {
/// Euro currency /// Euro currency
eur('', 'EUR'), eur('', 'EUR'),
/// US Dollar currency
/// US Dollar currency
usd('\$', 'USD'), usd('\$', 'USD'),
/// British Pound currency /// British Pound currency
gbp('£', 'GBP'); gbp('£', 'GBP');
const ExpenseCurrency(this.symbol, this.code); const ExpenseCurrency(this.symbol, this.code);
/// Currency symbol for display (e.g., €, $, £) /// Currency symbol for display (e.g., €, $, £)
final String symbol; final String symbol;
/// Standard currency code (e.g., EUR, USD, GBP) /// Standard currency code (e.g., EUR, USD, GBP)
final String code; final String code;
} }
/// Enumeration of expense categories with display names and icons. /// Enumeration of expense categories with display names and icons.
/// ///
/// Provides predefined categories for organizing travel expenses. /// Provides predefined categories for organizing travel expenses.
enum ExpenseCategory { enum ExpenseCategory {
/// Restaurant and food expenses /// Restaurant and food expenses
restaurant('Restaurant', Icons.restaurant), restaurant('Restaurant', Icons.restaurant),
/// Transportation expenses /// Transportation expenses
transport('Transport', Icons.directions_car), transport('Transport', Icons.directions_car),
/// Accommodation and lodging expenses /// Accommodation and lodging expenses
accommodation('Accommodation', Icons.hotel), accommodation('Accommodation', Icons.hotel),
/// Entertainment and activity expenses /// Entertainment and activity expenses
entertainment('Entertainment', Icons.local_activity), entertainment('Entertainment', Icons.local_activity),
/// Shopping expenses /// Shopping expenses
shopping('Shopping', Icons.shopping_bag), shopping('Shopping', Icons.shopping_bag),
/// Other miscellaneous expenses /// Other miscellaneous expenses
other('Other', Icons.category); other('Other', Icons.category);
const ExpenseCategory(this.displayName, this.icon); const ExpenseCategory(this.displayName, this.icon);
/// Human-readable display name for the category /// Human-readable display name for the category
final String displayName; final String displayName;
/// Icon representing the category /// Icon representing the category
final IconData icon; final IconData icon;
} }
/// Model representing a travel expense. /// Model representing a travel expense.
/// ///
/// This class encapsulates all information about an expense including /// This class encapsulates all information about an expense including
/// amount, currency, category, who paid, how it's split among participants, /// amount, currency, category, who paid, how it's split among participants,
/// and receipt information. It extends [Equatable] for value comparison. /// and receipt information. It extends [Equatable] for value comparison.
class Expense extends Equatable { class Expense extends Equatable {
/// Unique identifier for the expense /// Unique identifier for the expense
final String id; final String id;
/// ID of the group this expense belongs to /// ID of the group this expense belongs to
final String groupId; final String groupId;
/// Description of the expense /// Description of the expense
final String description; final String description;
/// Amount of the expense in the original currency /// Amount of the expense in the original currency
final double amount; final double amount;
/// Currency of the expense /// Currency of the expense
final ExpenseCurrency currency; final ExpenseCurrency currency;
/// Amount converted to EUR for standardized calculations /// Amount converted to EUR for standardized calculations
final double amountInEur; final double amountInEur;
/// Category of the expense /// Category of the expense
final ExpenseCategory category; final ExpenseCategory category;
/// ID of the user who paid for this expense /// ID of the user who paid for this expense
final String paidById; final String paidById;
/// Name of the user who paid for this expense /// Name of the user who paid for this expense
final String paidByName; final String paidByName;
/// Date when the expense occurred /// Date when the expense occurred
final DateTime date; final DateTime date;
/// Timestamp when the expense was created /// Timestamp when the expense was created
final DateTime createdAt; final DateTime createdAt;
/// Timestamp when the expense was last edited (null if never edited) /// Timestamp when the expense was last edited (null if never edited)
final DateTime? editedAt; final DateTime? editedAt;
/// Whether this expense has been edited after creation /// Whether this expense has been edited after creation
final bool isEdited; final bool isEdited;
/// Whether this expense has been archived /// Whether this expense has been archived
final bool isArchived; final bool isArchived;
/// URL to the receipt image (optional) /// URL to the receipt image (optional)
final String? receiptUrl; final String? receiptUrl;
/// List of expense splits showing how the cost is divided /// List of expense splits showing how the cost is divided
final List<ExpenseSplit> splits; final List<ExpenseSplit> splits;
/// Creates a new [Expense] instance. /// Creates a new [Expense] instance.
/// ///
/// All parameters except [editedAt] and [receiptUrl] are required. /// All parameters except [editedAt] and [receiptUrl] are required.
const Expense({ const Expense({
required this.id, required this.id,
@@ -144,13 +151,17 @@ class Expense extends Equatable {
paidByName: map['paidByName'] ?? '', paidByName: map['paidByName'] ?? '',
date: _parseDateTime(map['date']), date: _parseDateTime(map['date']),
createdAt: _parseDateTime(map['createdAt']), createdAt: _parseDateTime(map['createdAt']),
editedAt: map['editedAt'] != null ? _parseDateTime(map['editedAt']) : null, editedAt: map['editedAt'] != null
? _parseDateTime(map['editedAt'])
: null,
isEdited: map['isEdited'] ?? false, isEdited: map['isEdited'] ?? false,
isArchived: map['isArchived'] ?? false, isArchived: map['isArchived'] ?? false,
receiptUrl: map['receiptUrl'], receiptUrl: map['receiptUrl'],
splits: (map['splits'] as List?) splits:
?.map((s) => ExpenseSplit.fromMap(s)) (map['splits'] as List?)
.toList() ?? [], ?.map((s) => ExpenseSplit.fromMap(s))
.toList() ??
[],
); );
} }
@@ -243,25 +254,36 @@ class Expense extends Equatable {
// Marquer comme archivé // Marquer comme archivé
Expense copyWithArchived() { Expense copyWithArchived() {
return copyWith( return copyWith(isArchived: true);
isArchived: true,
);
} }
// Ajouter/mettre à jour l'URL du reçu // Ajouter/mettre à jour l'URL du reçu
Expense copyWithReceipt(String receiptUrl) { Expense copyWithReceipt(String receiptUrl) {
return copyWith( return copyWith(receiptUrl: receiptUrl);
receiptUrl: receiptUrl,
);
} }
// Mettre à jour les splits // Mettre à jour les splits
Expense copyWithSplits(List<ExpenseSplit> newSplits) { Expense copyWithSplits(List<ExpenseSplit> newSplits) {
return copyWith( return copyWith(splits: newSplits);
splits: newSplits,
);
} }
@override @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,
];
}

View File

@@ -22,12 +22,22 @@ class GroupBalance extends Equatable {
factory GroupBalance.fromMap(Map<String, dynamic> map) { factory GroupBalance.fromMap(Map<String, dynamic> map) {
return GroupBalance( return GroupBalance(
groupId: map['groupId'] ?? '', groupId: map['groupId'] ?? '',
userBalances: (map['userBalances'] as List?) userBalances:
?.map((userBalance) => UserBalance.fromMap(userBalance as Map<String, dynamic>)) (map['userBalances'] as List?)
.toList() ?? [], ?.map(
settlements: (map['settlements'] as List?) (userBalance) =>
?.map((settlement) => Settlement.fromMap(settlement as Map<String, dynamic>)) UserBalance.fromMap(userBalance as Map<String, dynamic>),
.toList() ?? [], )
.toList() ??
[],
settlements:
(map['settlements'] as List?)
?.map(
(settlement) =>
Settlement.fromMap(settlement as Map<String, dynamic>),
)
.toList() ??
[],
totalExpenses: (map['totalExpenses'] as num?)?.toDouble() ?? 0.0, totalExpenses: (map['totalExpenses'] as num?)?.toDouble() ?? 0.0,
calculatedAt: _parseDateTime(map['calculatedAt']), calculatedAt: _parseDateTime(map['calculatedAt']),
); );
@@ -37,8 +47,12 @@ class GroupBalance extends Equatable {
Map<String, dynamic> toMap() { Map<String, dynamic> toMap() {
return { return {
'groupId': groupId, 'groupId': groupId,
'userBalances': userBalances.map((userBalance) => userBalance.toMap()).toList(), 'userBalances': userBalances
'settlements': settlements.map((settlement) => settlement.toMap()).toList(), .map((userBalance) => userBalance.toMap())
.toList(),
'settlements': settlements
.map((settlement) => settlement.toMap())
.toList(),
'totalExpenses': totalExpenses, 'totalExpenses': totalExpenses,
'calculatedAt': Timestamp.fromDate(calculatedAt), 'calculatedAt': Timestamp.fromDate(calculatedAt),
}; };
@@ -71,16 +85,20 @@ class GroupBalance extends Equatable {
} }
// Méthodes utilitaires pour la logique métier // 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; 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 =>
List<UserBalance> get debtors => userBalances.where((b) => b.shouldPay).toList(); userBalances.where((b) => b.shouldReceive).toList();
List<UserBalance> get debtors =>
userBalances.where((b) => b.shouldPay).toList();
int get participantCount => userBalances.length; int get participantCount => userBalances.length;
@override @override
@@ -90,4 +108,4 @@ class GroupBalance extends Equatable {
String toString() { String toString() {
return 'GroupBalance(groupId: $groupId, totalExpenses: $totalExpenses, participantCount: $participantCount, calculatedAt: $calculatedAt)'; return 'GroupBalance(groupId: $groupId, totalExpenses: $totalExpenses, participantCount: $participantCount, calculatedAt: $calculatedAt)';
} }
} }

View File

@@ -16,7 +16,10 @@ class ActivityRepository {
/// Ajoute une nouvelle activité /// Ajoute une nouvelle activité
Future<String?> addActivity(Activity activity) async { Future<String?> addActivity(Activity activity) async {
try { try {
print('ActivityRepository: Ajout d\'une activité: ${activity.name}'); _errorService.logInfo(
'ActivityRepository',
'Ajout d\'une activité: ${activity.name}',
);
final docRef = await _firestore final docRef = await _firestore
.collection(_collection) .collection(_collection)
@@ -25,10 +28,16 @@ class ActivityRepository {
// Mettre à jour l'activité avec l'ID généré // Mettre à jour l'activité avec l'ID généré
await docRef.update({'id': docRef.id}); 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; return docRef.id;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur lors de l\'ajout: $e'); _errorService.logError(
'ActivityRepository',
'Erreur lors de l\'ajout: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur ajout activité: $e', 'Erreur ajout activité: $e',
@@ -40,8 +49,9 @@ class ActivityRepository {
/// Récupère toutes les activités d'un voyage /// Récupère toutes les activités d'un voyage
Future<List<Activity>> getActivitiesByTrip(String tripId) async { Future<List<Activity>> getActivitiesByTrip(String tripId) async {
try { try {
print( _errorService.logInfo(
'ActivityRepository: Récupération des activités pour le voyage: $tripId', 'ActivityRepository',
'Récupération des activités pour le voyage: $tripId',
); );
// Modifié pour éviter l'erreur d'index composite // Modifié pour éviter l'erreur d'index composite
@@ -58,10 +68,16 @@ class ActivityRepository {
// Tri en mémoire par date de mise à jour (plus récent en premier) // Tri en mémoire par date de mise à jour (plus récent en premier)
activities.sort((a, b) => b.updatedAt.compareTo(a.updatedAt)); 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; return activities;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur lors de la récupération: $e'); _errorService.logError(
'ActivityRepository',
'Erreur lors de la récupération: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur récupération activités: $e', 'Erreur récupération activités: $e',
@@ -89,7 +105,10 @@ class ActivityRepository {
return null; return null;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur récupération activité: $e'); _errorService.logError(
'ActivityRepository',
'Erreur récupération activité: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur récupération activité: $e', 'Erreur récupération activité: $e',
@@ -101,17 +120,26 @@ class ActivityRepository {
/// Met à jour une activité /// Met à jour une activité
Future<bool> updateActivity(Activity activity) async { Future<bool> updateActivity(Activity activity) async {
try { try {
print('ActivityRepository: Mise à jour de l\'activité: ${activity.id}'); _errorService.logInfo(
'ActivityRepository',
'Mise à jour de l\'activité: ${activity.id}',
);
await _firestore await _firestore
.collection(_collection) .collection(_collection)
.doc(activity.id) .doc(activity.id)
.update(activity.copyWith(updatedAt: DateTime.now()).toMap()); .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; return true;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur lors de la mise à jour: $e'); _errorService.logError(
'ActivityRepository',
'Erreur lors de la mise à jour: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur mise à jour activité: $e', 'Erreur mise à jour activité: $e',
@@ -123,14 +151,23 @@ class ActivityRepository {
/// Supprime une activité /// Supprime une activité
Future<bool> deleteActivity(String activityId) async { Future<bool> deleteActivity(String activityId) async {
try { try {
print('ActivityRepository: Suppression de l\'activité: $activityId'); _errorService.logInfo(
'ActivityRepository',
'Suppression de l\'activité: $activityId',
);
await _firestore.collection(_collection).doc(activityId).delete(); 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; return true;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur lors de la suppression: $e'); _errorService.logError(
'ActivityRepository',
'Erreur lors de la suppression: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur suppression activité: $e', 'Erreur suppression activité: $e',
@@ -148,7 +185,7 @@ class ActivityRepository {
try { try {
// Validation des paramètres // Validation des paramètres
if (activityId.isEmpty) { if (activityId.isEmpty) {
print('ActivityRepository: ID d\'activité vide'); _errorService.logError('ActivityRepository', 'ID d\'activité vide');
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'ID d\'activité vide pour le vote', 'ID d\'activité vide pour le vote',
@@ -157,7 +194,7 @@ class ActivityRepository {
} }
if (userId.isEmpty) { if (userId.isEmpty) {
print('ActivityRepository: ID d\'utilisateur vide'); _errorService.logError('ActivityRepository', 'ID d\'utilisateur vide');
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'ID d\'utilisateur vide pour le vote', 'ID d\'utilisateur vide pour le vote',
@@ -165,7 +202,10 @@ class ActivityRepository {
return false; 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 // vote: 1 pour positif, -1 pour négatif, 0 pour supprimer le vote
final activityRef = _firestore.collection(_collection).doc(activityId); final activityRef = _firestore.collection(_collection).doc(activityId);
@@ -194,10 +234,13 @@ class ActivityRepository {
}); });
}); });
print('ActivityRepository: Vote enregistré avec succès'); _errorService.logSuccess(
'ActivityRepository',
'Vote enregistré avec succès',
);
return true; return true;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur lors du vote: $e'); _errorService.logError('ActivityRepository', 'Erreur lors du vote: $e');
_errorService.logError('activity_repository', 'Erreur vote: $e'); _errorService.logError('activity_repository', 'Erreur vote: $e');
return false; return false;
} }
@@ -221,7 +264,10 @@ class ActivityRepository {
return activities; return activities;
}); });
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur stream activités: $e'); _errorService.logError(
'ActivityRepository',
'Erreur stream activités: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur stream activités: $e', 'Erreur stream activités: $e',
@@ -233,8 +279,9 @@ class ActivityRepository {
/// Ajoute plusieurs activités en lot /// Ajoute plusieurs activités en lot
Future<List<String>> addActivitiesBatch(List<Activity> activities) async { Future<List<String>> addActivitiesBatch(List<Activity> activities) async {
try { try {
print( _errorService.logInfo(
'ActivityRepository: Ajout en lot de ${activities.length} activités', 'ActivityRepository',
'Ajout en lot de ${activities.length} activités',
); );
final batch = _firestore.batch(); final batch = _firestore.batch();
@@ -249,10 +296,13 @@ class ActivityRepository {
await batch.commit(); 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; return addedIds;
} catch (e) { } 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'); _errorService.logError('activity_repository', 'Erreur ajout en lot: $e');
return []; return [];
} }
@@ -264,8 +314,9 @@ class ActivityRepository {
String category, String category,
) async { ) async {
try { try {
print( _errorService.logInfo(
'ActivityRepository: Recherche par catégorie: $category pour le voyage: $tripId', 'ActivityRepository',
'Recherche par catégorie: $category pour le voyage: $tripId',
); );
// Récupérer toutes les activités du voyage puis filtrer en mémoire // Récupérer toutes les activités du voyage puis filtrer en mémoire
@@ -284,7 +335,10 @@ class ActivityRepository {
return activities; return activities;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur recherche par catégorie: $e'); _errorService.logError(
'ActivityRepository',
'Erreur recherche par catégorie: $e',
);
_errorService.logError( _errorService.logError(
'activity_repository', 'activity_repository',
'Erreur recherche par catégorie: $e', 'Erreur recherche par catégorie: $e',
@@ -315,7 +369,10 @@ class ActivityRepository {
return activities.take(limit).toList(); return activities.take(limit).toList();
} catch (e) { } 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'); _errorService.logError('activity_repository', 'Erreur top rated: $e');
return []; return [];
} }
@@ -337,7 +394,10 @@ class ActivityRepository {
return null; return null;
} catch (e) { } catch (e) {
print('ActivityRepository: Erreur recherche activité existante: $e'); _errorService.logError(
'ActivityRepository',
'Erreur recherche activité existante: $e',
);
return null; return null;
} }
} }

View File

@@ -117,10 +117,16 @@ class GroupRepository {
if (memberIds.isNotEmpty) { if (memberIds.isNotEmpty) {
await _groupsCollection.doc(groupId).update({'memberIds': memberIds}); await _groupsCollection.doc(groupId).update({'memberIds': memberIds});
print('Migration réussie pour le groupe $groupId'); _errorService.logSuccess(
'GroupRepository',
'Migration réussie pour le groupe $groupId',
);
} }
} catch (e) { } catch (e) {
print('Erreur de migration pour le groupe $groupId: $e'); _errorService.logError(
'GroupRepository',
'Erreur de migration pour le groupe $groupId: $e',
);
} }
} }

View File

@@ -3,6 +3,7 @@ import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/activity.dart'; import '../models/activity.dart';
import '../services/error_service.dart'; import '../services/error_service.dart';
import '../services/logger_service.dart';
/// Service pour rechercher des activités touristiques via Google Places API /// Service pour rechercher des activités touristiques via Google Places API
class ActivityPlacesService { class ActivityPlacesService {
@@ -24,7 +25,7 @@ class ActivityPlacesService {
int offset = 0, int offset = 0,
}) async { }) async {
try { try {
print( LoggerService.info(
'ActivityPlacesService: Recherche d\'activités pour: $destination (max: $maxResults, offset: $offset)', 'ActivityPlacesService: Recherche d\'activités pour: $destination (max: $maxResults, offset: $offset)',
); );
@@ -69,7 +70,7 @@ class ActivityPlacesService {
final uniqueActivities = _removeDuplicates(allActivities); final uniqueActivities = _removeDuplicates(allActivities);
uniqueActivities.sort((a, b) => (b.rating ?? 0).compareTo(a.rating ?? 0)); uniqueActivities.sort((a, b) => (b.rating ?? 0).compareTo(a.rating ?? 0));
print( LoggerService.info(
'ActivityPlacesService: ${uniqueActivities.length} activités trouvées au total', 'ActivityPlacesService: ${uniqueActivities.length} activités trouvées au total',
); );
@@ -81,20 +82,22 @@ class ActivityPlacesService {
); );
if (startIndex >= uniqueActivities.length) { if (startIndex >= uniqueActivities.length) {
print( LoggerService.info(
'ActivityPlacesService: Offset $startIndex dépasse le nombre total (${uniqueActivities.length})', 'ActivityPlacesService: Offset $startIndex dépasse le nombre total (${uniqueActivities.length})',
); );
return []; return [];
} }
final paginatedResults = uniqueActivities.sublist(startIndex, endIndex); final paginatedResults = uniqueActivities.sublist(startIndex, endIndex);
print( LoggerService.info(
'ActivityPlacesService: Retour de ${paginatedResults.length} activités (offset: $offset, max: $maxResults)', 'ActivityPlacesService: Retour de ${paginatedResults.length} activités (offset: $offset, max: $maxResults)',
); );
return paginatedResults; return paginatedResults;
} catch (e) { } 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); _errorService.logError('activity_places_service', e);
return []; return [];
} }
@@ -105,7 +108,9 @@ class ActivityPlacesService {
try { try {
// Vérifier que la clé API est configurée // Vérifier que la clé API est configurée
if (_apiKey.isEmpty) { 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'); throw Exception('Clé API Google Maps non configurée');
} }
@@ -113,16 +118,20 @@ class ActivityPlacesService {
final url = final url =
'https://maps.googleapis.com/maps/api/geocode/json?address=$encodedDestination&key=$_apiKey'; 'https://maps.googleapis.com/maps/api/geocode/json?address=$encodedDestination&key=$_apiKey';
print('ActivityPlacesService: Géocodage de "$destination"'); LoggerService.info('ActivityPlacesService: Géocodage de "$destination"');
print('ActivityPlacesService: URL = $url'); LoggerService.info('ActivityPlacesService: URL = $url');
final response = await http.get(Uri.parse(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) { if (response.statusCode == 200) {
final data = json.decode(response.body); 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) { if (data['status'] == 'OK' && data['results'].isNotEmpty) {
final location = data['results'][0]['geometry']['location']; final location = data['results'][0]['geometry']['location'];
@@ -130,10 +139,12 @@ class ActivityPlacesService {
'lat': location['lat'].toDouble(), 'lat': location['lat'].toDouble(),
'lng': location['lng'].toDouble(), 'lng': location['lng'].toDouble(),
}; };
print('ActivityPlacesService: Coordonnées trouvées = $coordinates'); LoggerService.info(
'ActivityPlacesService: Coordonnées trouvées = $coordinates',
);
return coordinates; return coordinates;
} else { } else {
print( LoggerService.error(
'ActivityPlacesService: Erreur API = ${data['error_message'] ?? data['status']}', 'ActivityPlacesService: Erreur API = ${data['error_message'] ?? data['status']}',
); );
if (data['status'] == 'REQUEST_DENIED') { if (data['status'] == 'REQUEST_DENIED') {
@@ -154,7 +165,7 @@ class ActivityPlacesService {
throw Exception('Erreur HTTP ${response.statusCode}'); throw Exception('Erreur HTTP ${response.statusCode}');
} }
} catch (e) { } 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 rethrow; // Rethrow pour permettre la gestion d'erreur en amont
} }
} }
@@ -194,7 +205,9 @@ class ActivityPlacesService {
activities.add(activity); activities.add(activity);
} }
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur conversion place: $e'); LoggerService.error(
'ActivityPlacesService: Erreur conversion place: $e',
);
} }
} }
@@ -204,7 +217,9 @@ class ActivityPlacesService {
return []; return [];
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur recherche par catégorie: $e'); LoggerService.error(
'ActivityPlacesService: Erreur recherche par catégorie: $e',
);
return []; return [];
} }
} }
@@ -260,7 +275,7 @@ class ActivityPlacesService {
updatedAt: DateTime.now(), updatedAt: DateTime.now(),
); );
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur conversion place: $e'); LoggerService.error('ActivityPlacesService: Erreur conversion place: $e');
return null; return null;
} }
} }
@@ -285,7 +300,9 @@ class ActivityPlacesService {
return null; return null;
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur récupération détails: $e'); LoggerService.error(
'ActivityPlacesService: Erreur récupération détails: $e',
);
return null; return null;
} }
} }
@@ -326,7 +343,7 @@ class ActivityPlacesService {
int radius = 5000, int radius = 5000,
}) async { }) async {
try { try {
print( LoggerService.info(
'ActivityPlacesService: Recherche textuelle: $query à $destination', 'ActivityPlacesService: Recherche textuelle: $query à $destination',
); );
@@ -364,7 +381,9 @@ class ActivityPlacesService {
activities.add(activity); activities.add(activity);
} }
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur conversion place: $e'); LoggerService.error(
'ActivityPlacesService: Erreur conversion place: $e',
);
} }
} }
@@ -374,7 +393,9 @@ class ActivityPlacesService {
return []; return [];
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur recherche textuelle: $e'); LoggerService.error(
'ActivityPlacesService: Erreur recherche textuelle: $e',
);
return []; return [];
} }
} }
@@ -423,11 +444,11 @@ class ActivityPlacesService {
if (latitude != null && longitude != null) { if (latitude != null && longitude != null) {
lat = latitude; lat = latitude;
lng = longitude; lng = longitude;
print( LoggerService.info(
'ActivityPlacesService: Utilisation des coordonnées pré-géolocalisées: $lat, $lng', 'ActivityPlacesService: Utilisation des coordonnées pré-géolocalisées: $lat, $lng',
); );
} else if (destination != null) { } else if (destination != null) {
print( LoggerService.info(
'ActivityPlacesService: Géolocalisation de la destination: $destination', 'ActivityPlacesService: Géolocalisation de la destination: $destination',
); );
final coordinates = await _geocodeDestination(destination); final coordinates = await _geocodeDestination(destination);
@@ -437,7 +458,7 @@ class ActivityPlacesService {
throw Exception('Destination ou coordonnées requises'); throw Exception('Destination ou coordonnées requises');
} }
print( LoggerService.info(
'ActivityPlacesService: Recherche paginée aux coordonnées: $lat, $lng (page: ${nextPageToken ?? "première"})', 'ActivityPlacesService: Recherche paginée aux coordonnées: $lat, $lng (page: ${nextPageToken ?? "première"})',
); );
@@ -464,7 +485,9 @@ class ActivityPlacesService {
); );
} }
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur recherche paginée: $e'); LoggerService.error(
'ActivityPlacesService: Erreur recherche paginée: $e',
);
_errorService.logError('activity_places_service', e); _errorService.logError('activity_places_service', e);
return { return {
'activities': <Activity>[], 'activities': <Activity>[],
@@ -519,7 +542,9 @@ class ActivityPlacesService {
activities.add(activity); activities.add(activity);
} }
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur conversion place: $e'); LoggerService.error(
'ActivityPlacesService: Erreur conversion place: $e',
);
} }
} }
@@ -537,7 +562,9 @@ class ActivityPlacesService {
'hasMoreData': false, 'hasMoreData': false,
}; };
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur recherche catégorie paginée: $e'); LoggerService.error(
'ActivityPlacesService: Erreur recherche catégorie paginée: $e',
);
return { return {
'activities': <Activity>[], 'activities': <Activity>[],
'nextPageToken': null, 'nextPageToken': null,
@@ -595,7 +622,9 @@ class ActivityPlacesService {
activities.add(activity); activities.add(activity);
} }
} catch (e) { } catch (e) {
print('ActivityPlacesService: Erreur conversion place: $e'); LoggerService.error(
'ActivityPlacesService: Erreur conversion place: $e',
);
} }
} }
@@ -613,7 +642,7 @@ class ActivityPlacesService {
'hasMoreData': false, 'hasMoreData': false,
}; };
} catch (e) { } catch (e) {
print( LoggerService.error(
'ActivityPlacesService: Erreur recherche toutes catégories paginée: $e', 'ActivityPlacesService: Erreur recherche toutes catégories paginée: $e',
); );
return { return {

View File

@@ -32,6 +32,7 @@
/// - [Settlement] for individual payment recommendations /// - [Settlement] for individual payment recommendations
/// - [UserBalance] for per-user balance information /// - [UserBalance] for per-user balance information
library; library;
import '../models/group_balance.dart'; import '../models/group_balance.dart';
import '../models/expense.dart'; import '../models/expense.dart';
import '../models/group_statistics.dart'; import '../models/group_statistics.dart';
@@ -59,7 +60,10 @@ class BalanceService {
try { try {
return await _balanceRepository.calculateGroupBalance(groupId); return await _balanceRepository.calculateGroupBalance(groupId);
} catch (e) { } catch (e) {
_errorService.logError('BalanceService', 'Erreur calcul balance groupe: $e'); _errorService.logError(
'BalanceService',
'Erreur calcul balance groupe: $e',
);
rethrow; rethrow;
} }
} }
@@ -80,7 +84,9 @@ class BalanceService {
/// Stream de la balance en temps réel /// Stream de la balance en temps réel
Stream<GroupBalance> getGroupBalanceStream(String groupId) { Stream<GroupBalance> getGroupBalanceStream(String groupId) {
return _expenseRepository.getExpensesStream(groupId).asyncMap((expenses) async { return _expenseRepository.getExpensesStream(groupId).asyncMap((
expenses,
) async {
try { try {
final userBalances = calculateUserBalances(expenses); final userBalances = calculateUserBalances(expenses);
final settlements = optimizeSettlements(userBalances); final settlements = optimizeSettlements(userBalances);
@@ -145,7 +151,7 @@ class BalanceService {
/// Optimiser les règlements (algorithme avancé) /// Optimiser les règlements (algorithme avancé)
List<Settlement> optimizeSettlements(List<UserBalance> balances) { List<Settlement> optimizeSettlements(List<UserBalance> balances) {
final settlements = <Settlement>[]; final settlements = <Settlement>[];
// Filtrer les utilisateurs avec une balance significative (> 0.01€) // Filtrer les utilisateurs avec une balance significative (> 0.01€)
final creditors = balances final creditors = balances
.where((b) => b.shouldReceive && b.balance > 0.01) .where((b) => b.shouldReceive && b.balance > 0.01)
@@ -164,10 +170,10 @@ class BalanceService {
// Utiliser des copies mutables pour les calculs // Utiliser des copies mutables pour les calculs
final creditorsRemaining = Map<String, double>.fromEntries( 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( 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é // Algorithme glouton optimisé
@@ -185,16 +191,19 @@ class BalanceService {
); );
if (settlementAmount > 0.01) { if (settlementAmount > 0.01) {
settlements.add(Settlement( settlements.add(
fromUserId: debtor.userId, Settlement(
fromUserName: debtor.userName, fromUserId: debtor.userId,
toUserId: creditor.userId, fromUserName: debtor.userName,
toUserName: creditor.userName, toUserId: creditor.userId,
amount: settlementAmount, toUserName: creditor.userName,
)); amount: settlementAmount,
),
);
// Mettre à jour les montants restants // Mettre à jour les montants restants
creditorsRemaining[creditor.userId] = creditRemaining - settlementAmount; creditorsRemaining[creditor.userId] =
creditRemaining - settlementAmount;
debtorsRemaining[debtor.userId] = debtRemaining - settlementAmount; debtorsRemaining[debtor.userId] = debtRemaining - settlementAmount;
} }
} }
@@ -204,7 +213,10 @@ class BalanceService {
} }
/// Calculer le montant optimal pour un règlement /// 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); final amount = [creditAmount, debtAmount].reduce((a, b) => a < b ? a : b);
// Arrondir à 2 décimales // Arrondir à 2 décimales
return (amount * 100).round() / 100; return (amount * 100).round() / 100;
@@ -213,36 +225,50 @@ class BalanceService {
/// Valider les règlements calculés /// Valider les règlements calculés
List<Settlement> _validateSettlements(List<Settlement> settlements) { List<Settlement> _validateSettlements(List<Settlement> settlements) {
// Supprimer les règlements trop petits // Supprimer les règlements trop petits
final validSettlements = settlements final validSettlements = settlements.where((s) => s.amount > 0.01).toList();
.where((s) => s.amount > 0.01)
.toList();
// Log pour debug en cas de problème // Log pour debug en cas de problème
final totalSettlements = validSettlements.fold(0.0, (sum, s) => sum + s.amount); final totalSettlements = validSettlements.fold(
_errorService.logInfo('BalanceService', 0.0,
'Règlements calculés: ${validSettlements.length}, Total: ${totalSettlements.toStringAsFixed(2)}'); (sum, s) => sum + s.amount,
);
_errorService.logInfo(
'BalanceService',
'Règlements calculés: ${validSettlements.length}, Total: ${totalSettlements.toStringAsFixed(2)}',
);
return validSettlements; return validSettlements;
} }
/// Calculer la dette entre deux utilisateurs spécifiques /// 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 // Cette méthode pourrait être utile pour des fonctionnalités avancées
// comme "Combien me doit X ?" ou "Combien je dois à Y ?" // 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 /// Analyser les tendances de dépenses par catégorie
Map<String, double> analyzeCategorySpending(List<Expense> expenses) { Map<String, double> analyzeCategorySpending(List<Expense> expenses) {
final categoryTotals = <String, double>{}; final categoryTotals = <String, double>{};
for (final expense in expenses) { for (final expense in expenses) {
if (expense.isArchived) continue; if (expense.isArchived) continue;
final categoryName = expense.category.displayName; final categoryName = expense.category.displayName;
categoryTotals[categoryName] = (categoryTotals[categoryName] ?? 0) + expense.amountInEur; categoryTotals[categoryName] =
(categoryTotals[categoryName] ?? 0) + expense.amountInEur;
} }
return categoryTotals; return categoryTotals;
} }
@@ -253,9 +279,12 @@ class BalanceService {
} }
final nonArchivedExpenses = expenses.where((e) => !e.isArchived).toList(); 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 averageAmount = totalAmount / nonArchivedExpenses.length;
final categorySpending = analyzeCategorySpending(nonArchivedExpenses); final categorySpending = analyzeCategorySpending(nonArchivedExpenses);
final topCategory = categorySpending.entries final topCategory = categorySpending.entries
.reduce((a, b) => a.value > b.value ? a : b) .reduce((a, b) => a.value > b.value ? a : b)
@@ -279,11 +308,14 @@ class BalanceService {
try { try {
// Ici vous pourriez enregistrer le règlement en base // Ici vous pourriez enregistrer le règlement en base
// ou créer une transaction de règlement // ou créer une transaction de règlement
// Pour l'instant, on pourrait juste recalculer // Pour l'instant, on pourrait juste recalculer
await Future.delayed(const Duration(milliseconds: 100)); 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) { } catch (e) {
_errorService.logError('BalanceService', 'Erreur mark settlement: $e'); _errorService.logError('BalanceService', 'Erreur mark settlement: $e');
rethrow; rethrow;
@@ -312,4 +344,4 @@ class _UserBalanceCalculator {
balance: _totalPaid - _totalOwed, balance: _totalPaid - _totalOwed,
); );
} }
} }

View File

@@ -1,32 +1,33 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../components/error/error_content.dart'; import '../components/error/error_content.dart';
import 'logger_service.dart';
/// Service for handling application errors and user notifications. /// Service for handling application errors and user notifications.
/// ///
/// This singleton service provides centralized error handling capabilities /// This singleton service provides centralized error handling capabilities
/// including displaying error dialogs, snackbars, and logging errors for /// including displaying error dialogs, snackbars, and logging errors for
/// debugging purposes. It uses a global navigator key to show notifications /// debugging purposes. It uses a global navigator key to show notifications
/// from anywhere in the application. /// from anywhere in the application.
class ErrorService { class ErrorService {
static final ErrorService _instance = ErrorService._internal(); static final ErrorService _instance = ErrorService._internal();
/// Factory constructor that returns the singleton instance. /// Factory constructor that returns the singleton instance.
factory ErrorService() => _instance; factory ErrorService() => _instance;
/// Private constructor for singleton pattern. /// Private constructor for singleton pattern.
ErrorService._internal(); ErrorService._internal();
/// Global navigator key for accessing context from anywhere in the app. /// Global navigator key for accessing context from anywhere in the app.
/// ///
/// This key should be assigned to the MaterialApp's navigatorKey property /// This key should be assigned to the MaterialApp's navigatorKey property
/// to enable error notifications from any part of the application. /// to enable error notifications from any part of the application.
static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
/// Displays an error message in a dialog. /// Displays an error message in a dialog.
/// ///
/// Shows a modal dialog with the error message and optional retry functionality. /// Shows a modal dialog with the error message and optional retry functionality.
/// The dialog appearance can be customized with different icons and colors. /// The dialog appearance can be customized with different icons and colors.
/// ///
/// [message] - The error message to display /// [message] - The error message to display
/// [title] - The dialog title (defaults to 'Error') /// [title] - The dialog title (defaults to 'Error')
/// [onRetry] - Optional callback for retry functionality /// [onRetry] - Optional callback for retry functionality
@@ -53,10 +54,10 @@ class ErrorService {
} }
/// Displays an error or success message in a snackbar. /// Displays an error or success message in a snackbar.
/// ///
/// Shows a floating snackbar at the bottom of the screen with the message. /// Shows a floating snackbar at the bottom of the screen with the message.
/// The appearance changes based on whether it's an error or success message. /// The appearance changes based on whether it's an error or success message.
/// ///
/// [message] - The message to display /// [message] - The message to display
/// [onRetry] - Optional callback for retry functionality /// [onRetry] - Optional callback for retry functionality
/// [isError] - Whether this is an error (true) or success (false) message /// [isError] - Whether this is an error (true) or success (false) message
@@ -89,36 +90,35 @@ class ErrorService {
} }
/// Logs error messages to the console during development. /// Logs error messages to the console during development.
/// ///
/// Formats and displays error information including source, error message, /// Formats and displays error information including source, error message,
/// and optional stack trace in a visually distinct format. /// and optional stack trace in a visually distinct format.
/// ///
/// [source] - The source or location where the error occurred /// [source] - The source or location where the error occurred
/// [error] - The error object or message /// [error] - The error object or message
/// [stackTrace] - Optional stack trace for debugging /// [stackTrace] - Optional stack trace for debugging
void logError(String source, dynamic error, [StackTrace? stackTrace]) { void logError(String source, dynamic error, [StackTrace? stackTrace]) {
print('═══════════════════════════════════'); LoggerService.error(
print('❌ ERROR in $source'); '❌ ERROR in $source\nMessage: $error',
print('Message: $error'); name: source,
if (stackTrace != null) { error: error,
print('StackTrace: $stackTrace'); stackTrace: stackTrace,
} );
print('═══════════════════════════════════');
} }
/// Logs informational messages to the console during development. /// Logs informational messages to the console during development.
/// ///
/// [source] - The source or location of the information /// [source] - The source or location of the information
/// [message] - The informational message /// [message] - The informational message
void logInfo(String source, String message) { void logInfo(String source, String message) {
print(' [$source] $message'); LoggerService.info(' $message', name: source);
} }
/// Logs success messages to the console during development. /// Logs success messages to the console during development.
/// ///
/// [source] - The source or location of the success /// [source] - The source or location of the success
/// [message] - The success message /// [message] - The success message
void logSuccess(String source, String message) { void logSuccess(String source, String message) {
print('[$source] $message'); LoggerService.info('$message', name: source);
} }
} }

View 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);
}
}

View File

@@ -11,7 +11,6 @@ class PlaceImageService {
/// Récupère l'URL de l'image d'un lieu depuis Google Places API /// Récupère l'URL de l'image d'un lieu depuis Google Places API
Future<String?> getPlaceImageUrl(String location) async { Future<String?> getPlaceImageUrl(String location) async {
try { try {
// ÉTAPE 1: Vérifier d'abord si une image existe déjà dans le Storage // ÉTAPE 1: Vérifier d'abord si une image existe déjà dans le Storage
final existingUrl = await _checkExistingImage(location); final existingUrl = await _checkExistingImage(location);
@@ -19,26 +18,25 @@ class PlaceImageService {
return existingUrl; return existingUrl;
} }
if (_apiKey.isEmpty) { if (_apiKey.isEmpty) {
_errorService.logError('PlaceImageService', 'Google Maps API key manquante'); _errorService.logError(
'PlaceImageService',
'Google Maps API key manquante',
);
return null; return null;
} }
// ÉTAPE 2: Recherche via Google Places API seulement si aucune image n'existe // ÉTAPE 2: Recherche via Google Places API seulement si aucune image n'existe
final searchTerms = _generateSearchTerms(location); final searchTerms = _generateSearchTerms(location);
for (final searchTerm in searchTerms) { for (final searchTerm in searchTerms) {
// 1. Rechercher le lieu // 1. Rechercher le lieu
final placeId = await _getPlaceIdForTerm(searchTerm); final placeId = await _getPlaceIdForTerm(searchTerm);
if (placeId == null) continue; if (placeId == null) continue;
// 2. Récupérer les détails du lieu avec les photos // 2. Récupérer les détails du lieu avec les photos
final photoReference = await _getPhotoReference(placeId); final photoReference = await _getPhotoReference(placeId);
if (photoReference == null) continue; if (photoReference == null) continue;
// 3. Télécharger et sauvegarder l'image (seulement si pas d'image existante) // 3. Télécharger et sauvegarder l'image (seulement si pas d'image existante)
final imageUrl = await _downloadAndSaveImage(photoReference, location); final imageUrl = await _downloadAndSaveImage(photoReference, location);
@@ -46,11 +44,13 @@ class PlaceImageService {
return imageUrl; return imageUrl;
} }
} }
return null;
return null;
} catch (e) { } 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; return null;
} }
} }
@@ -58,11 +58,11 @@ class PlaceImageService {
/// Génère différents termes de recherche pour optimiser les résultats /// Génère différents termes de recherche pour optimiser les résultats
List<String> _generateSearchTerms(String location) { List<String> _generateSearchTerms(String location) {
final terms = <String>[]; final terms = <String>[];
// Ajouter des termes spécifiques pour les villes connues // Ajouter des termes spécifiques pour les villes connues
final citySpecificTerms = _getCitySpecificTerms(location.toLowerCase()); final citySpecificTerms = _getCitySpecificTerms(location.toLowerCase());
terms.addAll(citySpecificTerms); terms.addAll(citySpecificTerms);
// Termes génériques avec attractions // Termes génériques avec attractions
terms.addAll([ terms.addAll([
'$location attractions touristiques monuments', '$location attractions touristiques monuments',
@@ -74,14 +74,14 @@ class PlaceImageService {
'$location skyline', '$location skyline',
location, // Terme original en dernier location, // Terme original en dernier
]); ]);
return terms; return terms;
} }
/// Retourne des termes spécifiques pour des villes connues /// Retourne des termes spécifiques pour des villes connues
List<String> _getCitySpecificTerms(String location) { List<String> _getCitySpecificTerms(String location) {
final specific = <String>[]; final specific = <String>[];
if (location.contains('paris')) { if (location.contains('paris')) {
specific.addAll([ specific.addAll([
'Tour Eiffel Paris', 'Tour Eiffel Paris',
@@ -120,20 +120,23 @@ class PlaceImageService {
'Tokyo Skytree', 'Tokyo Skytree',
]); ]);
} }
return specific; return specific;
} }
/// Recherche un place ID pour un terme spécifique /// Recherche un place ID pour un terme spécifique
Future<String?> _getPlaceIdForTerm(String searchTerm) async { Future<String?> _getPlaceIdForTerm(String searchTerm) async {
// Essayer d'abord avec les attractions touristiques // 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; if (placeId != null) return placeId;
// Puis avec les points d'intérêt // Puis avec les points d'intérêt
placeId = await _searchPlaceWithType(searchTerm, 'point_of_interest'); placeId = await _searchPlaceWithType(searchTerm, 'point_of_interest');
if (placeId != null) return placeId; if (placeId != null) return placeId;
// Enfin recherche générale // Enfin recherche générale
return await _searchPlaceGeneral(searchTerm); return await _searchPlaceGeneral(searchTerm);
} }
@@ -146,14 +149,14 @@ class PlaceImageService {
'?query=${Uri.encodeComponent('$location attractions monuments')}' '?query=${Uri.encodeComponent('$location attractions monuments')}'
'&type=$type' '&type=$type'
'&fields=place_id,name,types,rating' '&fields=place_id,name,types,rating'
'&key=$_apiKey' '&key=$_apiKey',
); );
final response = await http.get(url); final response = await http.get(url);
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK' && data['results'].isNotEmpty) { if (data['status'] == 'OK' && data['results'].isNotEmpty) {
// Prioriser les résultats avec des ratings élevés // Prioriser les résultats avec des ratings élevés
final results = data['results'] as List; final results = data['results'] as List;
@@ -162,7 +165,7 @@ class PlaceImageService {
final bRating = b['rating'] ?? 0.0; final bRating = b['rating'] ?? 0.0;
return bRating.compareTo(aRating); return bRating.compareTo(aRating);
}); });
return results.first['place_id']; return results.first['place_id'];
} }
} }
@@ -180,14 +183,14 @@ class PlaceImageService {
'?input=${Uri.encodeComponent(location)}' '?input=${Uri.encodeComponent(location)}'
'&inputtype=textquery' '&inputtype=textquery'
'&fields=place_id' '&fields=place_id'
'&key=$_apiKey' '&key=$_apiKey',
); );
final response = await http.get(url); final response = await http.get(url);
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK' && data['candidates'].isNotEmpty) { if (data['status'] == 'OK' && data['candidates'].isNotEmpty) {
return data['candidates'][0]['place_id']; return data['candidates'][0]['place_id'];
} }
@@ -205,24 +208,23 @@ class PlaceImageService {
'https://maps.googleapis.com/maps/api/place/details/json' 'https://maps.googleapis.com/maps/api/place/details/json'
'?place_id=$placeId' '?place_id=$placeId'
'&fields=photos' '&fields=photos'
'&key=$_apiKey' '&key=$_apiKey',
); );
final response = await http.get(url); final response = await http.get(url);
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = json.decode(response.body); final data = json.decode(response.body);
if (data['status'] == 'OK' && if (data['status'] == 'OK' &&
data['result'] != null && data['result'] != null &&
data['result']['photos'] != null && data['result']['photos'] != null &&
data['result']['photos'].isNotEmpty) { data['result']['photos'].isNotEmpty) {
final photos = data['result']['photos'] as List; final photos = data['result']['photos'] as List;
// Trier les photos pour obtenir les meilleures // Trier les photos pour obtenir les meilleures
final sortedPhotos = _sortPhotosByQuality(photos); final sortedPhotos = _sortPhotosByQuality(photos);
if (sortedPhotos.isNotEmpty) { if (sortedPhotos.isNotEmpty) {
return sortedPhotos.first['photo_reference']; return sortedPhotos.first['photo_reference'];
} }
@@ -230,7 +232,10 @@ class PlaceImageService {
} }
return null; return null;
} catch (e) { } 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; return null;
} }
} }
@@ -238,64 +243,68 @@ class PlaceImageService {
/// Trie les photos par qualité (largeur/hauteur et popularité) /// Trie les photos par qualité (largeur/hauteur et popularité)
List<Map<String, dynamic>> _sortPhotosByQuality(List photos) { List<Map<String, dynamic>> _sortPhotosByQuality(List photos) {
final photoList = photos.cast<Map<String, dynamic>>(); final photoList = photos.cast<Map<String, dynamic>>();
photoList.sort((a, b) { photoList.sort((a, b) {
// Priorité 1: Photos horizontales (largeur > hauteur) // Priorité 1: Photos horizontales (largeur > hauteur)
final aWidth = a['width'] ?? 0; final aWidth = a['width'] ?? 0;
final aHeight = a['height'] ?? 0; final aHeight = a['height'] ?? 0;
final bWidth = b['width'] ?? 0; final bWidth = b['width'] ?? 0;
final bHeight = b['height'] ?? 0; final bHeight = b['height'] ?? 0;
final aIsHorizontal = aWidth > aHeight; final aIsHorizontal = aWidth > aHeight;
final bIsHorizontal = bWidth > bHeight; final bIsHorizontal = bWidth > bHeight;
if (aIsHorizontal && !bIsHorizontal) return -1; if (aIsHorizontal && !bIsHorizontal) return -1;
if (!aIsHorizontal && bIsHorizontal) return 1; if (!aIsHorizontal && bIsHorizontal) return 1;
// Priorité 2: Résolution plus élevée // Priorité 2: Résolution plus élevée
final aResolution = aWidth * aHeight; final aResolution = aWidth * aHeight;
final bResolution = bWidth * bHeight; final bResolution = bWidth * bHeight;
if (aResolution != bResolution) { if (aResolution != bResolution) {
return bResolution.compareTo(aResolution); return bResolution.compareTo(aResolution);
} }
// Priorité 3: Ratio d'aspect optimal pour paysage (1.5-2.0) // Priorité 3: Ratio d'aspect optimal pour paysage (1.5-2.0)
final aRatio = aWidth > 0 ? aWidth / aHeight : 0; final aRatio = aWidth > 0 ? aWidth / aHeight : 0;
final bRatio = bWidth > 0 ? bWidth / bHeight : 0; final bRatio = bWidth > 0 ? bWidth / bHeight : 0;
final idealRatio = 1.7; // Ratio 16:9 environ final idealRatio = 1.7; // Ratio 16:9 environ
final aDiff = (aRatio - idealRatio).abs(); final aDiff = (aRatio - idealRatio).abs();
final bDiff = (bRatio - idealRatio).abs(); final bDiff = (bRatio - idealRatio).abs();
return aDiff.compareTo(bDiff); return aDiff.compareTo(bDiff);
}); });
return photoList; return photoList;
} }
/// Télécharge l'image et la sauvegarde dans Firebase Storage /// 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 { try {
// URL pour télécharger l'image en haute qualité et format horizontal // 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 =
'?maxwidth=1200' // Augmenté pour une meilleure qualité 'https://maps.googleapis.com/maps/api/place/photo'
'&maxheight=800' // Ratio horizontal ~1.5:1 '?maxwidth=1200' // Augmenté pour une meilleure qualité
'&maxheight=800' // Ratio horizontal ~1.5:1
'&photo_reference=$photoReference' '&photo_reference=$photoReference'
'&key=$_apiKey'; '&key=$_apiKey';
// Télécharger l'image // Télécharger l'image
final response = await http.get(Uri.parse(imageUrl)); final response = await http.get(Uri.parse(imageUrl));
if (response.statusCode == 200) { if (response.statusCode == 200) {
// Créer un nom de fichier unique basé sur la localisation normalisée // Créer un nom de fichier unique basé sur la localisation normalisée
final normalizedLocation = _normalizeLocationName(location); final normalizedLocation = _normalizeLocationName(location);
final fileName = '${normalizedLocation}_${DateTime.now().millisecondsSinceEpoch}.jpg'; final fileName =
'${normalizedLocation}_${DateTime.now().millisecondsSinceEpoch}.jpg';
// Référence vers Firebase Storage // Référence vers Firebase Storage
final storageRef = _storage.ref().child('trip_images/$fileName'); final storageRef = _storage.ref().child('trip_images/$fileName');
// Upload de l'image avec métadonnées // Upload de l'image avec métadonnées
final uploadTask = await storageRef.putData( final uploadTask = await storageRef.putData(
response.bodyBytes, response.bodyBytes,
@@ -309,15 +318,17 @@ class PlaceImageService {
}, },
), ),
); );
// Récupérer l'URL de téléchargement // Récupérer l'URL de téléchargement
final downloadUrl = await uploadTask.ref.getDownloadURL(); final downloadUrl = await uploadTask.ref.getDownloadURL();
return downloadUrl; return downloadUrl;
} else { } else {}
}
return null; return null;
} catch (e) { } 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; return null;
} }
} }
@@ -326,45 +337,52 @@ class PlaceImageService {
Future<String?> _checkExistingImage(String location) async { Future<String?> _checkExistingImage(String location) async {
try { try {
final normalizedLocation = _normalizeLocationName(location); final normalizedLocation = _normalizeLocationName(location);
final listResult = await _storage.ref('trip_images').listAll(); final listResult = await _storage.ref('trip_images').listAll();
for (final item in listResult.items) { for (final item in listResult.items) {
try { try {
final metadata = await item.getMetadata(); final metadata = await item.getMetadata();
final storedNormalizedLocation = metadata.customMetadata?['normalizedLocation']; final storedNormalizedLocation =
metadata.customMetadata?['normalizedLocation'];
final storedLocation = metadata.customMetadata?['location']; final storedLocation = metadata.customMetadata?['location'];
// Méthode 1: Vérifier avec la location normalisée (nouvelles images) // 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(); final url = await item.getDownloadURL();
return url; return url;
} }
// Méthode 2: Vérifier avec la location originale normalisée (anciennes images) // Méthode 2: Vérifier avec la location originale normalisée (anciennes images)
if (storedLocation != null) { if (storedLocation != null) {
final storedLocationNormalized = _normalizeLocationName(storedLocation); final storedLocationNormalized = _normalizeLocationName(
storedLocation,
);
if (storedLocationNormalized == normalizedLocation) { if (storedLocationNormalized == normalizedLocation) {
final url = await item.getDownloadURL(); final url = await item.getDownloadURL();
return url; return url;
} }
} }
} catch (e) { } catch (e) {
// Méthode 3: Essayer de deviner depuis le nom du fichier (fallback) // Méthode 3: Essayer de deviner depuis le nom du fichier (fallback)
final fileName = item.name; final fileName = item.name;
if (fileName.toLowerCase().contains(normalizedLocation.toLowerCase())) { if (fileName.toLowerCase().contains(
normalizedLocation.toLowerCase(),
)) {
try { try {
final url = await item.getDownloadURL(); final url = await item.getDownloadURL();
return url; return url;
} catch (urlError) { } 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',
);
} }
} }
} }
} }
return null; return null;
} catch (e) { } catch (e) {
return null; return null;
@@ -384,23 +402,26 @@ class PlaceImageService {
Future<void> cleanupUnusedImages(List<String> usedImageUrls) async { Future<void> cleanupUnusedImages(List<String> usedImageUrls) async {
try { try {
final listResult = await _storage.ref('trip_images').listAll(); final listResult = await _storage.ref('trip_images').listAll();
int deletedCount = 0;
for (final item in listResult.items) { for (final item in listResult.items) {
try { try {
final url = await item.getDownloadURL(); final url = await item.getDownloadURL();
if (!usedImageUrls.contains(url)) { if (!usedImageUrls.contains(url)) {
await item.delete(); await item.delete();
deletedCount++;
} }
} catch (e) { } catch (e) {
_errorService.logError('PlaceImageService', 'Erreur lors du nettoyage: $e'); _errorService.logError(
'PlaceImageService',
'Erreur lors du nettoyage: $e',
);
} }
} }
} catch (e) { } catch (e) {
_errorService.logError('PlaceImageService', 'Erreur lors du nettoyage: $e'); _errorService.logError(
'PlaceImageService',
'Erreur lors du nettoyage: $e',
);
} }
} }
@@ -408,18 +429,19 @@ class PlaceImageService {
Future<void> cleanupDuplicateImages() async { Future<void> cleanupDuplicateImages() async {
try { try {
final listResult = await _storage.ref('trip_images').listAll(); final listResult = await _storage.ref('trip_images').listAll();
// Grouper les images par location normalisée // Grouper les images par location normalisée
final Map<String, List<Reference>> locationGroups = {}; final Map<String, List<Reference>> locationGroups = {};
for (final item in listResult.items) { for (final item in listResult.items) {
String locationKey = 'unknown'; String locationKey = 'unknown';
try { try {
final metadata = await item.getMetadata(); final metadata = await item.getMetadata();
final storedNormalizedLocation = metadata.customMetadata?['normalizedLocation']; final storedNormalizedLocation =
metadata.customMetadata?['normalizedLocation'];
final storedLocation = metadata.customMetadata?['location']; final storedLocation = metadata.customMetadata?['location'];
if (storedNormalizedLocation != null) { if (storedNormalizedLocation != null) {
locationKey = storedNormalizedLocation; locationKey = storedNormalizedLocation;
} else if (storedLocation != null) { } else if (storedLocation != null) {
@@ -440,43 +462,44 @@ class PlaceImageService {
locationKey = parts.take(parts.length - 1).join('_'); locationKey = parts.take(parts.length - 1).join('_');
} }
} }
if (!locationGroups.containsKey(locationKey)) { if (!locationGroups.containsKey(locationKey)) {
locationGroups[locationKey] = []; locationGroups[locationKey] = [];
} }
locationGroups[locationKey]!.add(item); locationGroups[locationKey]!.add(item);
} }
// Supprimer les doublons (garder le plus récent) // Supprimer les doublons (garder le plus récent)
int deletedCount = 0;
for (final entry in locationGroups.entries) { for (final entry in locationGroups.entries) {
final location = entry.key;
final images = entry.value; final images = entry.value;
if (images.length > 1) { if (images.length > 1) {
// Trier par timestamp (garder le plus récent) // Trier par timestamp (garder le plus récent)
images.sort((a, b) { images.sort((a, b) {
final aTimestamp = _extractTimestampFromName(a.name); final aTimestamp = _extractTimestampFromName(a.name);
final bTimestamp = _extractTimestampFromName(b.name); final bTimestamp = _extractTimestampFromName(b.name);
return bTimestamp.compareTo(aTimestamp); // Plus récent en premier return bTimestamp.compareTo(aTimestamp); // Plus récent en premier
}); });
// Supprimer tous sauf le premier (plus récent) // Supprimer tous sauf le premier (plus récent)
for (int i = 1; i < images.length; i++) { for (int i = 1; i < images.length; i++) {
try { try {
await images[i].delete(); await images[i].delete();
deletedCount++;
} catch (e) { } 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) { } 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; return null;
} catch (e) { } 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; return null;
} }
} }
@@ -510,7 +536,10 @@ class PlaceImageService {
final ref = _storage.refFromURL(imageUrl); final ref = _storage.refFromURL(imageUrl);
await ref.delete(); await ref.delete();
} catch (e) { } 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',
);
} }
} }
} }

View File

@@ -14,17 +14,18 @@
/// Example usage: /// Example usage:
/// ```dart /// ```dart
/// final storageService = StorageService(); /// final storageService = StorageService();
/// ///
/// // Upload a receipt image /// // Upload a receipt image
/// final receiptUrl = await storageService.uploadReceiptImage(groupId, imageFile); /// final receiptUrl = await storageService.uploadReceiptImage(groupId, imageFile);
/// ///
/// // Upload a profile image /// // Upload a profile image
/// final profileUrl = await storageService.uploadProfileImage(userId, imageFile); /// final profileUrl = await storageService.uploadProfileImage(userId, imageFile);
/// ///
/// // Delete a file /// // Delete a file
/// await storageService.deleteFile(fileUrl); /// await storageService.deleteFile(fileUrl);
/// ``` /// ```
library; library;
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:firebase_storage/firebase_storage.dart'; import 'package:firebase_storage/firebase_storage.dart';
@@ -36,34 +37,32 @@ import 'error_service.dart';
class StorageService { class StorageService {
/// Firebase Storage instance for file operations /// Firebase Storage instance for file operations
final FirebaseStorage _storage; final FirebaseStorage _storage;
/// Service for error handling and logging /// Service for error handling and logging
final ErrorService _errorService; final ErrorService _errorService;
/// Constructor for StorageService. /// Constructor for StorageService.
/// ///
/// Args: /// Args:
/// [storage]: Optional Firebase Storage instance (auto-created if null) /// [storage]: Optional Firebase Storage instance (auto-created if null)
/// [errorService]: Optional error service instance (auto-created if null) /// [errorService]: Optional error service instance (auto-created if null)
StorageService({ StorageService({FirebaseStorage? storage, ErrorService? errorService})
FirebaseStorage? storage, : _storage = storage ?? FirebaseStorage.instance,
ErrorService? errorService, _errorService = errorService ?? ErrorService();
}) : _storage = storage ?? FirebaseStorage.instance,
_errorService = errorService ?? ErrorService();
/// Uploads a receipt image for an expense with automatic compression. /// Uploads a receipt image for an expense with automatic compression.
/// ///
/// Validates the image file, compresses it to JPEG format with 85% quality, /// Validates the image file, compresses it to JPEG format with 85% quality,
/// generates a unique filename, and uploads it with appropriate metadata. /// generates a unique filename, and uploads it with appropriate metadata.
/// Monitors upload progress and logs it for debugging purposes. /// Monitors upload progress and logs it for debugging purposes.
/// ///
/// Args: /// Args:
/// [groupId]: ID of the group this receipt belongs to /// [groupId]: ID of the group this receipt belongs to
/// [imageFile]: The image file to upload /// [imageFile]: The image file to upload
/// ///
/// Returns: /// Returns:
/// A Future<String> containing the download URL of the uploaded image /// A `Future<String>` containing the download URL of the uploaded image
/// ///
/// Throws: /// Throws:
/// Exception if file validation fails or upload encounters an error /// Exception if file validation fails or upload encounters an error
Future<String> uploadReceiptImage(String groupId, File imageFile) async { Future<String> uploadReceiptImage(String groupId, File imageFile) async {
@@ -95,8 +94,12 @@ class StorageService {
// Progress monitoring (optional) // Progress monitoring (optional)
uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) { uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
final progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; final progress =
_errorService.logInfo('StorageService', 'Upload progress: ${progress.toStringAsFixed(1)}%'); (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
_errorService.logInfo(
'StorageService',
'Upload progress: ${progress.toStringAsFixed(1)}%',
);
}); });
// Wait for completion // Wait for completion
@@ -105,9 +108,11 @@ class StorageService {
// Get download URL // Get download URL
final downloadUrl = await snapshot.ref.getDownloadURL(); final downloadUrl = await snapshot.ref.getDownloadURL();
_errorService.logSuccess('StorageService', 'Image uploaded successfully: $fileName'); _errorService.logSuccess(
'StorageService',
'Image uploaded successfully: $fileName',
);
return downloadUrl; return downloadUrl;
} catch (e) { } catch (e) {
_errorService.logError('StorageService', 'Error uploading image: $e'); _errorService.logError('StorageService', 'Error uploading image: $e');
rethrow; rethrow;
@@ -115,10 +120,10 @@ class StorageService {
} }
/// Deletes a receipt image from storage. /// Deletes a receipt image from storage.
/// ///
/// Extracts the storage reference from the provided URL and deletes the file. /// Extracts the storage reference from the provided URL and deletes the file.
/// Does not throw errors to avoid blocking expense deletion operations. /// Does not throw errors to avoid blocking expense deletion operations.
/// ///
/// Args: /// Args:
/// [imageUrl]: The download URL of the image to delete /// [imageUrl]: The download URL of the image to delete
Future<void> deleteReceiptImage(String imageUrl) async { Future<void> deleteReceiptImage(String imageUrl) async {
@@ -137,17 +142,17 @@ class StorageService {
} }
/// Compresses an image to optimize storage space and upload speed. /// Compresses an image to optimize storage space and upload speed.
/// ///
/// Reads the image file, decodes it, resizes it if too large (max 1024x1024), /// Reads the image file, decodes it, resizes it if too large (max 1024x1024),
/// and encodes it as JPEG with 85% quality for optimal balance between /// and encodes it as JPEG with 85% quality for optimal balance between
/// file size and image quality. /// file size and image quality.
/// ///
/// Args: /// Args:
/// [imageFile]: The image file to compress /// [imageFile]: The image file to compress
/// ///
/// Returns: /// Returns:
/// A Future<Uint8List> containing the compressed image bytes /// A `Future<Uint8List>` containing the compressed image bytes
/// ///
/// Throws: /// Throws:
/// Exception if the image cannot be decoded or processed /// Exception if the image cannot be decoded or processed
Future<Uint8List> _compressImage(File imageFile) async { Future<Uint8List> _compressImage(File imageFile) async {
@@ -175,9 +180,11 @@ class StorageService {
// Encode as JPEG with compression // Encode as JPEG with compression
final compressedBytes = img.encodeJpg(image, quality: 85); final compressedBytes = img.encodeJpg(image, quality: 85);
_errorService.logInfo('StorageService', _errorService.logInfo(
'Image compressed: ${bytes.length}${compressedBytes.length} bytes'); 'StorageService',
'Image compressed: ${bytes.length}${compressedBytes.length} bytes',
);
return Uint8List.fromList(compressedBytes); return Uint8List.fromList(compressedBytes);
} catch (e) { } catch (e) {
@@ -188,13 +195,13 @@ class StorageService {
} }
/// Validates an image file before upload. /// Validates an image file before upload.
/// ///
/// Checks file existence, size constraints (max 10MB), and file extension /// Checks file existence, size constraints (max 10MB), and file extension
/// to ensure only valid image files are processed for upload. /// to ensure only valid image files are processed for upload.
/// ///
/// Args: /// Args:
/// [imageFile]: The image file to validate /// [imageFile]: The image file to validate
/// ///
/// Throws: /// Throws:
/// Exception if validation fails (file doesn't exist, too large, or invalid extension) /// Exception if validation fails (file doesn't exist, too large, or invalid extension)
void _validateImageFile(File imageFile) { void _validateImageFile(File imageFile) {
@@ -219,13 +226,13 @@ class StorageService {
} }
/// Generates a unique filename for a receipt image. /// Generates a unique filename for a receipt image.
/// ///
/// Creates a filename using timestamp, microseconds, and group ID to ensure /// Creates a filename using timestamp, microseconds, and group ID to ensure
/// uniqueness and prevent naming conflicts when multiple receipts are uploaded. /// uniqueness and prevent naming conflicts when multiple receipts are uploaded.
/// ///
/// Args: /// Args:
/// [groupId]: ID of the group this receipt belongs to /// [groupId]: ID of the group this receipt belongs to
/// ///
/// Returns: /// Returns:
/// A unique filename string for the receipt image /// A unique filename string for the receipt image
String _generateReceiptFileName(String groupId) { String _generateReceiptFileName(String groupId) {
@@ -235,21 +242,23 @@ class StorageService {
} }
/// Uploads multiple images simultaneously (for future features). /// Uploads multiple images simultaneously (for future features).
/// ///
/// Processes multiple image files in parallel for batch upload scenarios. /// Processes multiple image files in parallel for batch upload scenarios.
/// Each image is validated, compressed, and uploaded with unique filenames. /// Each image is validated, compressed, and uploaded with unique filenames.
/// ///
/// Args: /// Args:
/// [groupId]: ID of the group these images belong to /// [groupId]: ID of the group these images belong to
/// [imageFiles]: List of image files to upload /// [imageFiles]: List of image files to upload
/// ///
/// Returns: /// 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( Future<List<String>> uploadMultipleImages(
String groupId, String groupId,
List<File> imageFiles, List<File> imageFiles,
) async { ) async {
final uploadTasks = imageFiles.map((file) => uploadReceiptImage(groupId, file)); final uploadTasks = imageFiles.map(
(file) => uploadReceiptImage(groupId, file),
);
return await Future.wait(uploadTasks); return await Future.wait(uploadTasks);
} }
@@ -259,7 +268,10 @@ class StorageService {
final ref = _storage.refFromURL(imageUrl); final ref = _storage.refFromURL(imageUrl);
return await ref.getMetadata(); return await ref.getMetadata();
} catch (e) { } catch (e) {
_errorService.logError('StorageService', 'Erreur récupération metadata: $e'); _errorService.logError(
'StorageService',
'Erreur récupération metadata: $e',
);
return null; return null;
} }
} }
@@ -274,14 +286,17 @@ class StorageService {
// Vérifier l'âge du fichier // Vérifier l'âge du fichier
final metadata = await ref.getMetadata(); final metadata = await ref.getMetadata();
final uploadDate = metadata.timeCreated; final uploadDate = metadata.timeCreated;
if (uploadDate != null) { if (uploadDate != null) {
final daysSinceUpload = DateTime.now().difference(uploadDate).inDays; final daysSinceUpload = DateTime.now().difference(uploadDate).inDays;
// Supprimer les fichiers de plus de 30 jours sans dépense associée // Supprimer les fichiers de plus de 30 jours sans dépense associée
if (daysSinceUpload > 30) { if (daysSinceUpload > 30) {
await ref.delete(); await ref.delete();
_errorService.logInfo('StorageService', 'Image orpheline supprimée: ${ref.name}'); _errorService.logInfo(
'StorageService',
'Image orpheline supprimée: ${ref.name}',
);
} }
} }
} }
@@ -295,17 +310,20 @@ class StorageService {
try { try {
final groupRef = _storage.ref().child('receipts/$groupId'); final groupRef = _storage.ref().child('receipts/$groupId');
final listResult = await groupRef.listAll(); final listResult = await groupRef.listAll();
int totalSize = 0; int totalSize = 0;
for (final ref in listResult.items) { for (final ref in listResult.items) {
final metadata = await ref.getMetadata(); final metadata = await ref.getMetadata();
totalSize += metadata.size ?? 0; totalSize += metadata.size ?? 0;
} }
return totalSize; return totalSize;
} catch (e) { } catch (e) {
_errorService.logError('StorageService', 'Erreur calcul taille storage: $e'); _errorService.logError(
'StorageService',
'Erreur calcul taille storage: $e',
);
return 0; return 0;
} }
} }
} }

View File

@@ -3,10 +3,12 @@ import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/trip.dart'; import '../models/trip.dart';
import 'error_service.dart'; import 'error_service.dart';
import 'logger_service.dart';
/// Service pour géocoder les destinations des voyages /// Service pour géocoder les destinations des voyages
class TripGeocodingService { class TripGeocodingService {
static final TripGeocodingService _instance = TripGeocodingService._internal(); static final TripGeocodingService _instance =
TripGeocodingService._internal();
factory TripGeocodingService() => _instance; factory TripGeocodingService() => _instance;
TripGeocodingService._internal(); TripGeocodingService._internal();
@@ -16,35 +18,41 @@ class TripGeocodingService {
/// Géocode la destination d'un voyage et retourne un Trip mis à jour /// Géocode la destination d'un voyage et retourne un Trip mis à jour
Future<Trip> geocodeTrip(Trip trip) async { Future<Trip> geocodeTrip(Trip trip) async {
try { 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 // Vérifier si on a déjà des coordonnées récentes
if (trip.hasRecentCoordinates) { 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; return trip;
} }
if (_apiKey.isEmpty) { 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'); throw Exception('Clé API Google Maps non configurée');
} }
final coordinates = await _geocodeDestination(trip.location); final coordinates = await _geocodeDestination(trip.location);
if (coordinates != null) { 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( return trip.copyWith(
latitude: coordinates['lat'], latitude: coordinates['lat'],
longitude: coordinates['lng'], longitude: coordinates['lng'],
lastGeocodingUpdate: DateTime.now(), lastGeocodingUpdate: DateTime.now(),
); );
} else { } else {
print('⚠️ [TripGeocoding] Impossible de géocoder "${trip.location}"'); LoggerService.warning(
'⚠️ [TripGeocoding] Impossible de géocoder "${trip.location}"',
);
return trip; return trip;
} }
} catch (e) { } 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); _errorService.logError('trip_geocoding_service', e);
return trip; // Retourner le voyage original en cas d'erreur 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 /// Géocode une destination et retourne les coordonnées
Future<Map<String, double>?> _geocodeDestination(String destination) async { Future<Map<String, double>?> _geocodeDestination(String destination) async {
try { 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)}' '?address=${Uri.encodeComponent(destination)}'
'&key=$_apiKey'; '&key=$_apiKey';
print('🌐 [TripGeocoding] URL = $url'); LoggerService.info('🌐 [TripGeocoding] URL = $url');
final response = await http.get(Uri.parse(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) { if (response.statusCode == 200) {
final data = json.decode(response.body); 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) { if (data['status'] == 'OK' && data['results'].isNotEmpty) {
final location = data['results'][0]['geometry']['location']; final location = data['results'][0]['geometry']['location'];
@@ -72,18 +85,24 @@ class TripGeocodingService {
'lat': (location['lat'] as num).toDouble(), 'lat': (location['lat'] as num).toDouble(),
'lng': (location['lng'] 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; return coordinates;
} else { } else {
print('⚠️ [TripGeocoding] Erreur API = ${data['error_message'] ?? data['status']}'); LoggerService.warning(
'⚠️ [TripGeocoding] Erreur API = ${data['error_message'] ?? data['status']}',
);
return null; return null;
} }
} else { } else {
print('❌ [TripGeocoding] Erreur HTTP ${response.statusCode}'); LoggerService.error(
'❌ [TripGeocoding] Erreur HTTP ${response.statusCode}',
);
return null; return null;
} }
} catch (e) { } 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); _errorService.logError('trip_geocoding_service', e);
return null; return null;
} }
@@ -96,23 +115,25 @@ class TripGeocodingService {
/// Géocode plusieurs voyages en batch /// Géocode plusieurs voyages en batch
Future<List<Trip>> geocodeTrips(List<Trip> trips) async { 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 = []; final List<Trip> geocodedTrips = [];
for (final trip in trips) { for (final trip in trips) {
if (needsGeocoding(trip)) { if (needsGeocoding(trip)) {
final geocodedTrip = await geocodeTrip(trip); final geocodedTrip = await geocodeTrip(trip);
geocodedTrips.add(geocodedTrip); geocodedTrips.add(geocodedTrip);
// Petit délai pour éviter de saturer l'API Google // Petit délai pour éviter de saturer l'API Google
await Future.delayed(const Duration(milliseconds: 200)); await Future.delayed(const Duration(milliseconds: 200));
} else { } else {
geocodedTrips.add(trip); geocodedTrips.add(trip);
} }
} }
print('✅ [TripGeocoding] Géocodage terminé'); LoggerService.info('✅ [TripGeocoding] Géocodage terminé');
return geocodedTrips; return geocodedTrips;
} }
} }

View File

@@ -617,7 +617,7 @@ packages:
source: hosted source: hosted
version: "4.1.2" version: "4.1.2"
image: image:
dependency: transitive dependency: "direct main"
description: description:
name: image name: image
sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928"
@@ -825,7 +825,7 @@ packages:
source: hosted source: hosted
version: "3.2.1" version: "3.2.1"
path: path:
dependency: transitive dependency: "direct main"
description: description:
name: path name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"

View File

@@ -59,6 +59,8 @@ dependencies:
sign_in_with_apple: ^7.0.1 sign_in_with_apple: ^7.0.1
sign_in_button: ^4.0.1 sign_in_button: ^4.0.1
cached_network_image: ^3.3.1 cached_network_image: ^3.3.1
path: ^1.9.1
image: ^4.5.4
dev_dependencies: dev_dependencies:
flutter_launcher_icons: ^0.13.1 flutter_launcher_icons: ^0.13.1

View File

@@ -20,7 +20,7 @@ void main() async {
if (stats['tripsWithImages'] > 0) { if (stats['tripsWithImages'] > 0) {
await tripImageService.cleanupUnusedImages(userId); await tripImageService.cleanupUnusedImages(userId);
final newStats = await tripImageService.getImageStatistics(userId); await tripImageService.getImageStatistics(userId);
} else {} } else {}
} catch (e) { } catch (e) {
exit(1); exit(1);

View File

@@ -1,3 +1,4 @@
// ignore_for_file: avoid_print
import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart'; import 'package:firebase_storage/firebase_storage.dart';
import 'package:travel_mate/firebase_options.dart'; import 'package:travel_mate/firebase_options.dart';
@@ -32,7 +33,7 @@ void main() async {
final location = customMeta['location'] ?? 'Inconnue'; final location = customMeta['location'] ?? 'Inconnue';
final normalizedLocation = final normalizedLocation =
customMeta['normalizedLocation'] ?? 'Non définie'; customMeta['normalizedLocation'] ?? 'Non définie';
final source = customMeta['source'] ?? 'Inconnue';
final uploadedAt = customMeta['uploadedAt'] ?? 'Inconnue'; final uploadedAt = customMeta['uploadedAt'] ?? 'Inconnue';
// Récupérer l'URL de téléchargement // Récupérer l'URL de téléchargement
@@ -76,18 +77,17 @@ void main() async {
int totalDuplicates = 0; int totalDuplicates = 0;
for (final entry in locationGroups.entries) { for (final entry in locationGroups.entries) {
final location = entry.key;
final images = entry.value; final images = entry.value;
if (images.length > 1) { if (images.length > 1) {
totalDuplicates += images.length - 1; totalDuplicates += images.length - 1;
for (int i = 0; i < images.length; i++) { for (int i = 0; i < images.length; i++) {}
final image = images[i];
}
} else {} } else {}
} }
if (totalDuplicates > 0) {} if (totalDuplicates > 0) {}
} catch (e) {} } catch (e) {
print('Erreur globale: $e');
}
} }

View File

@@ -1,3 +1,4 @@
// ignore_for_file: avoid_print
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
void main() { void main() {
@@ -13,7 +14,7 @@ void main() {
print('✓ Téléchargement d\'une nouvelle image depuis Google Places'); print('✓ Téléchargement d\'une nouvelle image depuis Google Places');
existingImage = 'https://storage.googleapis.com/image1.jpg'; existingImage = 'https://storage.googleapis.com/image1.jpg';
print('✓ Image sauvée: $existingImage'); print('✓ Image sauvée: $existingImage');
expect(existingImage, isNotNull); expect(existingImage, isNotNull);
// Scénario 2: Rechargement (image existante) // Scénario 2: Rechargement (image existante)
@@ -34,7 +35,7 @@ void main() {
print('✓ Nouvelle destination, aucune image existante'); print('✓ Nouvelle destination, aucune image existante');
print('✓ Téléchargement autorisé pour cette nouvelle destination'); print('✓ Téléchargement autorisé pour cette nouvelle destination');
differentLocationImage = 'https://storage.googleapis.com/image2.jpg'; differentLocationImage = 'https://storage.googleapis.com/image2.jpg';
expect(differentLocationImage, isNotNull); expect(differentLocationImage, isNotNull);
expect(differentLocationImage, isNot(equals(existingImage))); expect(differentLocationImage, isNot(equals(existingImage)));

View File

@@ -1,3 +1,4 @@
// ignore_for_file: avoid_print
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
void main() { void main() {

View File

@@ -1,10 +1,11 @@
// ignore_for_file: avoid_print
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:travel_mate/services/place_image_service.dart'; import 'package:travel_mate/services/place_image_service.dart';
void main() { void main() {
group('PlaceImageService Tests', () { group('PlaceImageService Tests', () {
late PlaceImageService placeImageService; late PlaceImageService placeImageService;
setUp(() { setUp(() {
placeImageService = PlaceImageService(); placeImageService = PlaceImageService();
}); });
@@ -12,9 +13,9 @@ void main() {
test('should generate search terms correctly for Paris', () { test('should generate search terms correctly for Paris', () {
// Cette fonction n'est pas publique, mais nous pouvons tester indirectement // Cette fonction n'est pas publique, mais nous pouvons tester indirectement
// en vérifiant que différentes villes génèrent des termes appropriés // en vérifiant que différentes villes génèrent des termes appropriés
final cities = ['Paris', 'London', 'Rome', 'New York', 'Tokyo']; final cities = ['Paris', 'London', 'Rome', 'New York', 'Tokyo'];
for (String city in cities) { for (String city in cities) {
print('Testing search terms generation for: $city'); print('Testing search terms generation for: $city');
// Le test indirect sera fait lors de l'appel réel à l'API // Le test indirect sera fait lors de l'appel réel à l'API
@@ -23,14 +24,8 @@ void main() {
}); });
test('should prioritize tourist attractions in search terms', () { test('should prioritize tourist attractions in search terms', () {
const testCases = [ const testCases = ['Paris', 'London', 'Rome', 'New York', 'Tokyo'];
'Paris',
'London',
'Rome',
'New York',
'Tokyo'
];
for (String city in testCases) { for (String city in testCases) {
print('City: $city should have tourist attraction terms'); print('City: $city should have tourist attraction terms');
expect(city.length, greaterThan(0)); expect(city.length, greaterThan(0));
@@ -41,7 +36,7 @@ void main() {
test('should handle API key missing gracefully', () async { test('should handle API key missing gracefully', () async {
// Test avec une clé API vide // Test avec une clé API vide
final result = await placeImageService.getPlaceImageUrl('Paris'); final result = await placeImageService.getPlaceImageUrl('Paris');
// Devrait retourner null si pas de clé API // Devrait retourner null si pas de clé API
expect(result, isNull); expect(result, isNull);
}); });
@@ -57,12 +52,12 @@ void main() {
'Louvre Paris', 'Louvre Paris',
'Champs-Élysées Paris', 'Champs-Élysées Paris',
]; ];
for (String term in parisTerms) { for (String term in parisTerms) {
expect(term.contains('Paris'), true); expect(term.contains('Paris'), true);
print('Generated term: $term'); print('Generated term: $term');
} }
// Test des termes spécifiques pour Londres // Test des termes spécifiques pour Londres
const londonTerms = [ const londonTerms = [
'Big Ben London', 'Big Ben London',
@@ -71,7 +66,7 @@ void main() {
'Buckingham Palace London', 'Buckingham Palace London',
'Tower of London', 'Tower of London',
]; ];
for (String term in londonTerms) { for (String term in londonTerms) {
expect(term.contains('London') || term.contains('Eye'), true); expect(term.contains('London') || term.contains('Eye'), true);
print('Generated term: $term'); print('Generated term: $term');
@@ -88,7 +83,7 @@ void main() {
'centre ville', 'centre ville',
'skyline', 'skyline',
]; ];
for (String term in genericTerms) { for (String term in genericTerms) {
expect(term.isNotEmpty, true); expect(term.isNotEmpty, true);
print('Generic term: $term'); print('Generic term: $term');
@@ -105,32 +100,34 @@ void main() {
{'width': 300, 'height': 300}, // Carré {'width': 300, 'height': 300}, // Carré
{'width': 1200, 'height': 800}, // Horizontal haute résolution {'width': 1200, 'height': 800}, // Horizontal haute résolution
]; ];
// Le tri devrait favoriser les photos horizontales // Le tri devrait favoriser les photos horizontales
photos.sort((a, b) { photos.sort((a, b) {
final aRatio = a['width']! / a['height']!; final aRatio = a['width']! / a['height']!;
final bRatio = b['width']! / b['height']!; final bRatio = b['width']! / b['height']!;
// Favoriser les ratios > 1 (horizontal) // Favoriser les ratios > 1 (horizontal)
if (aRatio > 1 && bRatio <= 1) return -1; if (aRatio > 1 && bRatio <= 1) return -1;
if (bRatio > 1 && aRatio <= 1) return 1; if (bRatio > 1 && aRatio <= 1) return 1;
// Si les deux sont horizontaux, favoriser la plus haute résolution // Si les deux sont horizontaux, favoriser la plus haute résolution
final aResolution = a['width']! * a['height']!; final aResolution = a['width']! * a['height']!;
final bResolution = b['width']! * b['height']!; final bResolution = b['width']! * b['height']!;
return bResolution.compareTo(aResolution); return bResolution.compareTo(aResolution);
}); });
// La première photo devrait être celle avec la plus haute résolution horizontale // La première photo devrait être celle avec la plus haute résolution horizontale
expect(photos.first['width'], 1200); expect(photos.first['width'], 1200);
expect(photos.first['height'], 800); expect(photos.first['height'], 800);
print('Photos triées par qualité:'); print('Photos triées par qualité:');
for (var photo in photos) { for (var photo in photos) {
final ratio = photo['width']! / photo['height']!; 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)})',
);
} }
}); });
}); });
} }