fix chats: one chat per ad, ordering, delivery after commit, errors
A chat was unique per user pair, so contacting the same author about a second ad returned the old chat with the old post_id, and the chat list showed the other ad's title and image. - chats are unique per (user_one_id, user_two_id, post_id); migration 015 drops the old pair constraint whatever its name and adds the new one - getOrCreateChat looks the chat up by users and post, and checks that the other user exists and the post belongs to one of the participants - chat list is sorted by last message time (chat creation as fallback) - WebSocket message and unread events are sent only after commit - chat errors are ApiException: 404 not found, 403 not a participant, 400 validation; messages are limited to 4000 characters - Post.images ordered by id so the cover image is stable everywhere Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -6,10 +6,15 @@ import com.krylov.refound.dto.MessageDto;
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.MessageRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -17,15 +22,21 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatService {
|
||||
|
||||
/** Максимальная длина сообщения в символах. */
|
||||
public static final int MAX_MESSAGE_LENGTH = 4000;
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final MessageRepository messageRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
@@ -36,13 +47,27 @@ public class ChatService {
|
||||
@Transactional
|
||||
public ChatDto getOrCreateChat(Long currentUserId, Long otherUserId, Long postId) {
|
||||
if (currentUserId.equals(otherUserId)) {
|
||||
throw new IllegalArgumentException("Нельзя создать чат с самим собой");
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (!userRepository.existsById(otherUserId)) {
|
||||
throw new ApiException(ErrorCode.NOT_FOUND, "Пользователь не найден", HttpStatus.NOT_FOUND);
|
||||
}
|
||||
if (postId != null) {
|
||||
// Иначе клиент мог прикрепить к чату любое чужое объявление
|
||||
Post post = postRepository.findById(postId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Объявление не найдено", HttpStatus.NOT_FOUND));
|
||||
Long ownerId = post.getUser().getId();
|
||||
if (!ownerId.equals(currentUserId) && !ownerId.equals(otherUserId)) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Объявление не принадлежит участнику чата", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
Long userId1 = Math.min(currentUserId, otherUserId);
|
||||
Long userId2 = Math.max(currentUserId, otherUserId);
|
||||
|
||||
Chat chat = chatRepository.findByUsers(userId1, userId2).orElseGet(() -> {
|
||||
// Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому
|
||||
// объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов)
|
||||
Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> {
|
||||
Chat newChat = new Chat();
|
||||
newChat.setUserOneId(userId1);
|
||||
newChat.setUserTwoId(userId2);
|
||||
@@ -53,11 +78,19 @@ public class ChatService {
|
||||
return toDto(chat, currentUserId);
|
||||
}
|
||||
|
||||
// Все чаты пользователя
|
||||
// Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет)
|
||||
@Transactional(readOnly = true)
|
||||
public List<ChatDto> getUserChats(Long userId) {
|
||||
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
|
||||
}
|
||||
|
||||
return chatRepository.findAllByUserId(userId).stream()
|
||||
.map(c -> toDto(c, userId))
|
||||
.map(c -> {
|
||||
ChatDto dto = toDto(c, userId);
|
||||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : c.getCreatedAt());
|
||||
})
|
||||
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.map(ChatWithActivity::dto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -73,6 +106,11 @@ public class ChatService {
|
||||
// Отправка сообщения (вызывается из WebSocket контроллера)
|
||||
@Transactional
|
||||
public void sendMessage(Long senderId, Long chatId, String content) {
|
||||
if (content.length() > MAX_MESSAGE_LENGTH) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
Chat chat = getChatOrThrow(chatId);
|
||||
checkParticipant(chat, senderId);
|
||||
|
||||
@@ -84,8 +122,6 @@ public class ChatService {
|
||||
|
||||
MessageDto dto = toMessageDto(message);
|
||||
|
||||
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
|
||||
// Уведомляем получателя об непрочитанных
|
||||
Long recipientId = chat.getUserOneId().equals(senderId)
|
||||
? chat.getUserTwoId()
|
||||
@@ -93,11 +129,28 @@ public class ChatService {
|
||||
|
||||
long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId);
|
||||
|
||||
messagingTemplate.convertAndSend(
|
||||
"/topic/user/" + recipientId + "/unread",
|
||||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||||
);
|
||||
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
|
||||
// историю, мог не увидеть ещё не закоммиченное сообщение
|
||||
afterCommit(() -> {
|
||||
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
messagingTemplate.convertAndSend(
|
||||
"/topic/user/" + recipientId + "/unread",
|
||||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private static void afterCommit(Runnable action) {
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
action.run();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
action.run();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -128,12 +181,13 @@ public class ChatService {
|
||||
}
|
||||
|
||||
private Chat getChatOrThrow(Long chatId) {
|
||||
return chatRepository.findById(chatId).orElseThrow(() -> new IllegalArgumentException("Чат не найден"));
|
||||
return chatRepository.findById(chatId)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Чат не найден", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
private void checkParticipant(Chat chat, Long userId) {
|
||||
if (!chat.getUserOneId().equals(userId) && !chat.getUserTwoId().equals(userId)) {
|
||||
throw new SecurityException("Вы не участник этого чата");
|
||||
throw new ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user