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

@@ -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';
@@ -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);
@@ -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( emit(
balances: userBalances, GroupBalancesLoaded(balances: userBalances, settlements: settlements),
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()));
@@ -121,15 +131,18 @@ class BalanceBloc extends Bloc<BalanceEvent, BalanceState> {
} }
// 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( emit(
balances: userBalances, GroupBalancesLoaded(balances: userBalances, settlements: settlements),
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()));

View File

@@ -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);
@@ -56,7 +57,9 @@ 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();
@@ -64,7 +67,8 @@ class ExpenseBloc extends Bloc<ExpenseEvent, ExpenseState> {
.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');
@@ -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');
@@ -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');

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();
@@ -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();
} }
@@ -57,32 +59,34 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
@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,
), ),
], ],
@@ -247,10 +389,8 @@ class _GroupExpensesPageState extends State<GroupExpensesPage>
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

@@ -31,10 +31,7 @@ class ChatGroupContent extends StatefulWidget {
/// ///
/// 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();
@@ -63,14 +60,16 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
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
@@ -96,23 +95,23 @@ 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();
@@ -152,32 +151,29 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
/// [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
@@ -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,
@@ -319,7 +326,9 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
? '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,7 +392,12 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
); );
} }
Widget _buildMessageBubble(Message message, bool isMe, bool isDark, String currentUserId) { Widget _buildMessageBubble(
Message message,
bool isMe,
bool isDark,
String currentUserId,
) {
final Color bubbleColor; final Color bubbleColor;
final Color textColor; final Color textColor;
@@ -402,39 +410,45 @@ 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()
@@ -448,7 +462,10 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
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),
@@ -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);
@@ -713,19 +749,22 @@ class _ChatGroupContentState extends State<ChatGroupContent> {
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,
), ),
@@ -744,7 +783,10 @@ 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,

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,6 +22,7 @@ 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.
/// ///
@@ -46,10 +47,7 @@ class CreateTripContent extends StatefulWidget {
/// 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();
@@ -151,7 +149,7 @@ 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);
@@ -207,7 +205,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
_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,
@@ -265,19 +265,25 @@ class _CreateTripContentState extends State<CreateTripContent> {
/// 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',
@@ -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,
@@ -414,26 +414,26 @@ class _CreateTripContentState extends State<CreateTripContent> {
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,7 +442,7 @@ 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;
@@ -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;
} }
@@ -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;
} }
@@ -978,7 +1015,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
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,20 +1034,18 @@ 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(
@@ -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

@@ -33,7 +33,8 @@ class _MapContentState extends State<MapContent> {
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,11 +66,13 @@ 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);
@@ -117,6 +120,8 @@ 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);
@@ -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,19 +245,13 @@ 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
@@ -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,11 +312,13 @@ 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);
@@ -324,10 +327,12 @@ class _MapContentState extends State<MapContent> {
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,6 +368,8 @@ 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);
@@ -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,
),
), ),
), ),
], ],
@@ -320,11 +329,7 @@ class ProfileContent extends StatelessWidget {
), ),
), ),
), ),
Icon( Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
Icons.arrow_forward_ios,
size: 16,
color: Colors.grey[400],
),
], ],
), ),
), ),
@@ -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);
}, },
@@ -515,56 +526,62 @@ class ProfileContent extends StatelessWidget {
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,7 +589,11 @@ class ProfileContent extends StatelessWidget {
} }
} }
Future<void> _uploadProfilePicture(BuildContext context, String imagePath, UserBloc userBloc) async { Future<void> _uploadProfilePicture(
BuildContext context,
String imagePath,
UserBloc userBloc,
) async {
try { try {
final File imageFile = File(imagePath); final File imageFile = File(imagePath);
@@ -582,7 +603,9 @@ class ProfileContent extends StatelessWidget {
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) {
@@ -593,14 +616,15 @@ 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 {
@@ -608,13 +632,17 @@ class ProfileContent extends StatelessWidget {
// É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

@@ -9,8 +9,10 @@ import 'expense_split.dart';
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');
@@ -29,14 +31,19 @@ enum ExpenseCurrency {
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);
@@ -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,15 +85,19 @@ 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 =>
userBalances.where((b) => b.shouldReceive).toList();
List<UserBalance> get debtors => userBalances.where((b) => b.shouldPay).toList(); List<UserBalance> get debtors =>
userBalances.where((b) => b.shouldPay).toList();
int get participantCount => userBalances.length; int get participantCount => userBalances.length;

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);
@@ -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,23 +225,36 @@ 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
@@ -240,7 +265,8 @@ class BalanceService {
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,7 +279,10 @@ 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);
@@ -283,7 +312,10 @@ class BalanceService {
// 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;

View File

@@ -1,5 +1,6 @@
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.
/// ///
@@ -97,13 +98,12 @@ class ErrorService {
/// [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.
@@ -111,7 +111,7 @@ class ErrorService {
/// [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.
@@ -119,6 +119,6 @@ class ErrorService {
/// [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,9 +18,11 @@ 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;
} }
@@ -29,17 +30,14 @@ class PlaceImageService {
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);
if (imageUrl != null) { if (imageUrl != null) {
@@ -48,9 +46,11 @@ class PlaceImageService {
} }
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;
} }
} }
@@ -127,7 +127,10 @@ class PlaceImageService {
/// 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
@@ -146,7 +149,7 @@ 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);
@@ -180,7 +183,7 @@ 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);
@@ -205,7 +208,7 @@ 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);
@@ -217,7 +220,6 @@ class PlaceImageService {
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
@@ -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;
} }
} }
@@ -275,23 +280,27 @@ class PlaceImageService {
} }
/// 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');
@@ -313,11 +322,13 @@ 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;
} }
} }
@@ -332,36 +343,43 @@ class PlaceImageService {
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',
);
} }
} }
} }
} }
@@ -384,7 +402,6 @@ 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 {
@@ -392,15 +409,19 @@ class PlaceImageService {
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',
);
} }
} }
@@ -417,7 +438,8 @@ class PlaceImageService {
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) {
@@ -448,13 +470,11 @@ class PlaceImageService {
} }
// 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);
@@ -466,17 +486,20 @@ class PlaceImageService {
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

@@ -25,6 +25,7 @@
/// 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';
@@ -45,11 +46,9 @@ class 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.
/// ///
@@ -62,7 +61,7 @@ class StorageService {
/// [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
@@ -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;
@@ -146,7 +151,7 @@ class StorageService {
/// [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
@@ -176,8 +181,10 @@ 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) {
@@ -244,12 +251,14 @@ class StorageService {
/// [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;
} }
} }
@@ -281,7 +293,10 @@ class StorageService {
// 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}',
);
} }
} }
} }
@@ -304,7 +319,10 @@ class StorageService {
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,23 +18,27 @@ 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'],
@@ -40,11 +46,13 @@ class TripGeocodingService {
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,7 +115,9 @@ 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 = [];
@@ -112,7 +133,7 @@ class TripGeocodingService {
} }
} }
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() {

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,3 +1,4 @@
// 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';
@@ -23,13 +24,7 @@ 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');
@@ -129,7 +124,9 @@ void main() {
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)})',
);
} }
}); });
}); });