fix(chat): Correction race condition + Implémentation TODOs

## Corrections Critiques

### Race Condition - Statuts de Messages
- Fix : Les icônes de statut (✓, ✓✓, ✓✓ bleu) ne s'affichaient pas
- Cause : WebSocket delivery confirmations arrivaient avant messages locaux
- Solution : Pattern Optimistic UI dans chat_bloc.dart
  - Création message temporaire immédiate
  - Ajout à la liste AVANT requête HTTP
  - Remplacement par message serveur à la réponse
- Fichier : lib/presentation/state_management/chat_bloc.dart

## Implémentation TODOs (13/21)

### Social (social_header_widget.dart)
-  Copier lien du post dans presse-papiers
-  Partage natif via Share.share()
-  Dialogue de signalement avec 5 raisons

### Partage (share_post_dialog.dart)
-  Interface sélection d'amis avec checkboxes
-  Partage externe via Share API

### Média (media_upload_service.dart)
-  Parsing JSON réponse backend
-  Méthode deleteMedia() pour suppression
-  Génération miniature vidéo

### Posts (create_post_dialog.dart, edit_post_dialog.dart)
-  Extraction URL depuis uploads
-  Documentation chargement médias

### Chat (conversations_screen.dart)
-  Navigation vers notifications
-  ConversationSearchDelegate pour recherche

## Nouveaux Fichiers

### Configuration
- build-prod.ps1 : Script build production avec dart-define
- lib/core/constants/env_config.dart : Gestion environnements

### Documentation
- TODOS_IMPLEMENTED.md : Documentation complète TODOs

## Améliorations

### Architecture
- Refactoring injection de dépendances
- Amélioration routing et navigation
- Optimisation providers (UserProvider, FriendsProvider)

### UI/UX
- Amélioration thème et couleurs
- Optimisation animations
- Meilleure gestion erreurs

### Services
- Configuration API avec env_config
- Amélioration datasources (events, users)
- Optimisation modèles de données
This commit is contained in:
dahoud
2026-01-10 10:43:17 +00:00
parent 06031b01f2
commit 92612abbd7
321 changed files with 43137 additions and 4285 deletions

View File

@@ -1,66 +1,251 @@
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
/// [FriendCard] est un widget représentant une carte d'ami.
/// Cette carte inclut l'image de l'ami, son nom, et un bouton qui permet
/// d'interagir avec cette carte (via le `onTap`).
///
/// Ce widget est conçu pour être utilisé dans des listes d'amis, comme
/// dans la section "Mes Amis" de l'application.
class FriendCard extends StatelessWidget {
final String name; // Le nom de l'ami
final String imageUrl; // URL de l'image de profil de l'ami
final VoidCallback onTap; // Fonction callback exécutée lors d'un clic sur la carte
import '../../../core/constants/design_system.dart';
import '../../../core/utils/page_transitions.dart';
import '../../../data/datasources/chat_remote_data_source.dart';
import '../../../data/services/secure_storage.dart';
import '../../../domain/entities/friend.dart';
import '../../screens/chat/chat_screen.dart';
import '../animated_widgets.dart';
import '../custom_snackbar.dart';
import '../friend_detail_screen.dart';
import '../social_badge_widget.dart';
/// Constructeur de [FriendCard] avec des paramètres obligatoires.
const FriendCard({
Key? key,
required this.name,
required this.imageUrl,
required this.onTap,
}) : super(key: key);
/// [FriendCard] est un widget qui représente la carte d'un ami dans la liste.
/// Il affiche une image de profil, le nom, le statut, la dernière interaction,
/// un voyant pour l'état en ligne, et la durée de l'amitié.
class FriendCard extends StatefulWidget {
const FriendCard({required this.friend, super.key});
final Friend friend;
@override
State<FriendCard> createState() => _FriendCardState();
}
class _FriendCardState extends State<FriendCard> {
final ChatRemoteDataSource _chatDataSource = ChatRemoteDataSource(http.Client());
final SecureStorage _storage = SecureStorage();
bool _isCreatingConversation = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// Lorsque l'utilisateur clique sur la carte, on déclenche la fonction onTap.
debugPrint("[LOG] Carte de l'ami $name cliquée.");
onTap(); // Exécuter le callback fourni
},
child: Card(
elevation: 4, // Élévation de la carte pour donner un effet d'ombre
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)), // Bordure arrondie
color: Colors.grey.shade800, // Couleur de fond de la carte
child: Padding(
padding: const EdgeInsets.all(12.0), // Padding interne pour espacer le contenu
child: Row(
// Calcul de la durée de l'amitié
final duration = _calculateFriendshipDuration(widget.friend.dateAdded);
return AnimatedCard(
onTap: () => _navigateToFriendDetail(context),
elevation: DesignSystem.elevationSm,
hoverElevation: DesignSystem.elevationLg,
borderRadius: DesignSystem.borderRadiusLg,
padding: DesignSystem.paddingAll(DesignSystem.spacingMd),
child: Column(
children: [
Stack(
alignment: Alignment.topRight,
children: [
// Image de profil de l'ami affichée sous forme de cercle
Hero(
tag: name, // Le tag Hero permet de créer une transition animée vers un autre écran.
tag: 'friend_avatar_${widget.friend.friendId}',
child: CircleAvatar(
backgroundImage: NetworkImage(imageUrl), // Charger l'image depuis l'URL
radius: 30, // Taille de l'avatar
radius: 50,
backgroundImage: _getImageProvider(),
),
),
const SizedBox(width: 16), // Espacement entre l'image et le nom
// Le nom de l'ami avec un texte en gras et blanc
Expanded(
child: Text(
name,
style: const TextStyle(
fontSize: 18, // Taille de la police
color: Colors.white, // Couleur du texte
fontWeight: FontWeight.bold, // Style en gras
// Indicateur de statut en ligne
Positioned(
right: 0,
top: 0,
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
child: CircleAvatar(
key: ValueKey<bool>(widget.friend.isOnline ?? false),
radius: 8,
backgroundColor: (widget.friend.isOnline ?? false)
? Colors.green
: Colors.grey,
),
),
),
// Icône de flèche indiquant que la carte est cliquable
Icon(Icons.chevron_right, color: Colors.white70),
],
),
),
const SizedBox(height: 10),
Text(
'${widget.friend.friendFirstName} ${widget.friend.friendLastName}',
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
const SizedBox(height: 5),
Text(
widget.friend.status.name,
style: const TextStyle(fontSize: 14),
),
const SizedBox(height: 5),
Text(
widget.friend.lastInteraction ?? 'Aucune interaction récente',
style: const TextStyle(
fontStyle: FontStyle.italic,
fontSize: 12,
),
),
const SizedBox(height: 10),
// Affichage de la durée de l'amitié
Text(
'Amis depuis: $duration',
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
const SizedBox(height: 10),
// Affichage des badges
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: _buildBadges(),
),
const SizedBox(height: 8),
// Bouton de message compact
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _isCreatingConversation ? null : _openChat,
icon: _isCreatingConversation
? const SizedBox(
width: 14,
height: 14,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.chat_bubble_outline_rounded, size: 16),
label: Text(
_isCreatingConversation ? 'Envoi...' : 'Message',
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500),
),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
elevation: 1,
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
),
],
),
);
}
Future<void> _openChat() async {
final userId = await _storage.getUserId();
if (userId == null) {
if (mounted) {
context.showError('Erreur: Utilisateur non connecté');
}
return;
}
setState(() {
_isCreatingConversation = true;
});
try {
// Obtenir ou créer la conversation
final conversationModel = await _chatDataSource.getOrCreateConversation(
userId,
widget.friend.friendId,
);
if (mounted) {
setState(() {
_isCreatingConversation = false;
});
// Naviguer vers l'écran de chat
context.pushSlideUp(ChatScreen(conversation: conversationModel.toEntity()));
}
} catch (e) {
if (mounted) {
setState(() {
_isCreatingConversation = false;
});
context.showError('Erreur lors de l\'ouverture du chat');
}
}
}
/// Retourne l'image de l'ami, soit à partir d'une URL soit une image par défaut.
ImageProvider _getImageProvider() {
return widget.friend.imageUrl != null && widget.friend.imageUrl!.isNotEmpty
? (widget.friend.imageUrl!.startsWith('https')
? NetworkImage(widget.friend.imageUrl!) // Image depuis une URL
: AssetImage(widget.friend.imageUrl!) as ImageProvider) // Image locale
: const AssetImage('lib/assets/images/default_avatar.png'); // Image par défaut
}
/// Calcule la durée de l'amitié depuis la date d'ajout.
String _calculateFriendshipDuration(String? dateAdded) {
if (dateAdded == null || dateAdded.isEmpty) return 'Inconnu';
final date = DateTime.parse(dateAdded);
final duration = DateTime.now().difference(date);
if (duration.inDays < 30) {
return '${duration.inDays} jour${duration.inDays > 1 ? 's' : ''}';
} else if (duration.inDays < 365) {
final months = (duration.inDays / 30).floor();
return '$months mois';
} else {
final years = (duration.inDays / 365).floor();
return '$years an${years > 1 ? 's' : ''}';
}
}
/// Navigation vers l'écran de détails de l'ami
void _navigateToFriendDetail(BuildContext context) {
debugPrint(
"[LOG] Navigation : Détails de l'ami ${widget.friend.friendFirstName} ${widget.friend.friendLastName}",);
context.pushFadeScale(
FriendDetailScreen(
friendFirstName: widget.friend.friendFirstName,
friendLastName: widget.friend.friendLastName,
imageUrl: widget.friend.imageUrl ?? '',
friendId: widget.friend.friendId,
status: widget.friend.status,
lastInteraction: widget.friend.lastInteraction ?? 'Aucune',
dateAdded: widget.friend.dateAdded ?? 'Inconnu',
),
);
}
/// Crée une liste de badges à afficher sur la carte de l'ami.
List<Widget> _buildBadges() {
final List<Widget> badges = [];
// Exemple de badges en fonction des attributs de l'ami
if (widget.friend.isBestFriend != null && widget.friend.isBestFriend == true) {
badges.add(const BadgeWidget(
badge: 'Meilleur Ami',
icon: Icons.star,
),);
}
if (widget.friend.hasKnownSinceChildhood != null && widget.friend.hasKnownSinceChildhood == true) {
badges.add(const BadgeWidget(
badge: 'Ami d\'enfance',
icon: Icons.child_care,
),);
}
if (widget.friend.isOnline != null && widget.friend.isOnline == true) {
badges.add(const BadgeWidget(
badge: 'En ligne',
icon: Icons.circle,
),);
}
// Ajouter d'autres badges si nécessaire
return badges;
}
}