From 046d3df150f1b488fc306d5be795b71786871978 Mon Sep 17 00:00:00 2001 From: Joan Manuel Jaramillo Avila <89425013+LifeRIP@users.noreply.github.com> Date: Tue, 10 Jun 2025 22:24:23 -0500 Subject: [PATCH] feat: Adds sender display names to direct chat messages - Enhances direct chat functionality by including sender display names in responses. - Updates service methods to fetch and attach sender names to the last message in direct chats. - Introduces corresponding models changes to support optional display name serialization. - Improves user experience by providing more informative chat details. --- internal/handlers/chat_handler.go | 4 +- internal/models/message.go | 15 ++-- internal/services/directchat_service.go | 91 +++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 9 deletions(-) diff --git a/internal/handlers/chat_handler.go b/internal/handlers/chat_handler.go index ce66707..24dd743 100644 --- a/internal/handlers/chat_handler.go +++ b/internal/handlers/chat_handler.go @@ -224,7 +224,7 @@ func (h *ChatHandler) GetUserDirectChats(w http.ResponseWriter, r *http.Request) return } - chats, err := h.DirectChatService.GetUserDirectChats(userID) + chats, err := h.DirectChatService.GetUserDirectChatsWithSenderNames(userID) if err != nil { http.Error(w, "Error getting direct chats: "+err.Error(), http.StatusInternalServerError) return @@ -401,7 +401,7 @@ func (h *ChatHandler) GetChat(w http.ResponseWriter, r *http.Request) { return } - chat, err := h.DirectChatService.GetDirectChat(chatID) + chat, err := h.DirectChatService.GetDirectChatWithSenderName(chatID) if err != nil { http.Error(w, "Error getting chat: "+err.Error(), http.StatusInternalServerError) return diff --git a/internal/models/message.go b/internal/models/message.go index bca0e73..0b0e9ef 100644 --- a/internal/models/message.go +++ b/internal/models/message.go @@ -4,13 +4,14 @@ import "time" // Message representa un mensaje enviado por un usuario type Message struct { - ID string `json:"id" firestore:"id"` - Content string `json:"content" firestore:"content"` - UserID string `json:"userId" firestore:"userId"` - RoomID string `json:"roomId" firestore:"roomId"` - CreatedAt time.Time `json:"createdAt" firestore:"createdAt"` - UpdatedAt time.Time `json:"updatedAt" firestore:"updatedAt"` - IsDeleted bool `json:"isDeleted" firestore:"isDeleted"` + ID string `json:"id" firestore:"id"` + Content string `json:"content" firestore:"content"` + UserID string `json:"userId" firestore:"userId"` + RoomID string `json:"roomId" firestore:"roomId"` + CreatedAt time.Time `json:"createdAt" firestore:"createdAt"` + UpdatedAt time.Time `json:"updatedAt" firestore:"updatedAt"` + IsDeleted bool `json:"isDeleted" firestore:"isDeleted"` + DisplayName string `json:"displayName,omitempty" firestore:"-"` // Excluido de Firestore } // MessageResponse es la respuesta que incluye un mensaje y el nombre del usuario que lo envió diff --git a/internal/services/directchat_service.go b/internal/services/directchat_service.go index a6f5567..c6006eb 100644 --- a/internal/services/directchat_service.go +++ b/internal/services/directchat_service.go @@ -1,6 +1,8 @@ package services import ( + "context" + "github.com/Parchat/backend/internal/models" "github.com/Parchat/backend/internal/repositories" ) @@ -34,6 +36,37 @@ func (s *DirectChatService) GetUserDirectChats(userID string) ([]models.DirectCh return s.DirectChatRepo.GetUserDirectChats(userID) } +// GetUserDirectChatsWithSenderNames obtiene todos los chats directos con nombres de remitentes +func (s *DirectChatService) GetUserDirectChatsWithSenderNames(userID string) ([]models.DirectChat, error) { + chats, err := s.DirectChatRepo.GetUserDirectChats(userID) + if err != nil { + return nil, err + } + + ctx := context.Background() + client := s.DirectChatRepo.FirestoreClient.Client + + // Para cada chat, obtener el nombre del remitente del último mensaje + for i := range chats { + if chats[i].LastMessage != nil && chats[i].LastMessage.UserID != "" { + userDoc, err := client.Collection("users").Doc(chats[i].LastMessage.UserID).Get(ctx) + if err == nil { + var user models.User + if err := userDoc.DataTo(&user); err == nil { + // Crear una copia del mensaje para añadir el displayName + messageCopy := *chats[i].LastMessage + // Agregar el displayName a la estructura Message (se serializa como JSON aunque no esté en la estructura) + messageCopy.DisplayName = user.DisplayName + // Reemplazar el mensaje original con la copia que incluye displayName + chats[i].LastMessage = &messageCopy + } + } + } + } + + return chats, nil +} + // GetDirectChatMessages obtiene los mensajes de un chat directo func (s *DirectChatService) GetDirectChatMessages(directChatID string, limit int) ([]models.MessageResponse, error) { return s.MessageRepo.GetDirectChatMessages(directChatID, limit) @@ -43,3 +76,61 @@ func (s *DirectChatService) GetDirectChatMessages(directChatID string, limit int func (s *DirectChatService) FindOrCreateDirectChat(userID1, userID2 string) (*models.DirectChat, error) { return s.DirectChatRepo.FindOrCreateDirectChat(userID1, userID2) } + +// FindOrCreateDirectChatWithSenderName encuentra o crea un chat directo e incluye el nombre del remitente +func (s *DirectChatService) FindOrCreateDirectChatWithSenderName(userID1, userID2 string) (*models.DirectChat, error) { + chat, err := s.DirectChatRepo.FindOrCreateDirectChat(userID1, userID2) + if err != nil { + return nil, err + } + + // Añadir el displayName al último mensaje si existe + if chat.LastMessage != nil && chat.LastMessage.UserID != "" { + ctx := context.Background() + client := s.DirectChatRepo.FirestoreClient.Client + + userDoc, err := client.Collection("users").Doc(chat.LastMessage.UserID).Get(ctx) + if err == nil { + var user models.User + if err := userDoc.DataTo(&user); err == nil { + // Crear una copia del mensaje para añadir el displayName + messageCopy := *chat.LastMessage + // Agregar el displayName a la estructura Message + messageCopy.DisplayName = user.DisplayName + // Reemplazar el mensaje original con la copia + chat.LastMessage = &messageCopy + } + } + } + + return chat, nil +} + +// GetDirectChatWithSenderName obtiene un chat directo por su ID e incluye el nombre del remitente del último mensaje +func (s *DirectChatService) GetDirectChatWithSenderName(directChatID string) (*models.DirectChat, error) { + chat, err := s.DirectChatRepo.GetDirectChat(directChatID) + if err != nil { + return nil, err + } + + // Añadir el displayName al último mensaje si existe + if chat.LastMessage != nil && chat.LastMessage.UserID != "" { + ctx := context.Background() + client := s.DirectChatRepo.FirestoreClient.Client + + userDoc, err := client.Collection("users").Doc(chat.LastMessage.UserID).Get(ctx) + if err == nil { + var user models.User + if err := userDoc.DataTo(&user); err == nil { + // Crear una copia del mensaje para añadir el displayName + messageCopy := *chat.LastMessage + // Agregar el displayName a la estructura Message + messageCopy.DisplayName = user.DisplayName + // Reemplazar el mensaje original con la copia + chat.LastMessage = &messageCopy + } + } + } + + return chat, nil +}