package com.krylov.refound.service; import com.krylov.refound.config.ClusterMessaging; import com.krylov.refound.dto.ChatDto; import com.krylov.refound.dto.ChatPostDto; 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.Optional; import java.util.Map; import java.util.stream.Collectors; 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.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; // Рассылка через Redis во все экземпляры: получатель может быть подключён к другому private final ClusterMessaging messaging; private final UserRepository userRepository; private final PostRepository postRepository; /** * Ищет существующий чат с пользователем по объявлению, ничего не создавая. * Пустой чат «на будущее» не заводим: он появляется только с первым сообщением. */ @Transactional(readOnly = true) public Optional findChat(Long currentUserId, Long otherUserId, Long postId) { Long userId1 = Math.min(currentUserId, otherUserId); Long userId2 = Math.max(currentUserId, otherUserId); return chatRepository.findByUsersAndPost(userId1, userId2, postId).stream() .findFirst() .map(chat -> toDto(chat, currentUserId)); } /** * Первое сообщение собеседнику по объявлению: в одной транзакции находит или создаёт * чат и сохраняет сообщение. Так в базе не остаётся чатов без сообщений. */ @Transactional public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) { validateContent(content); if (currentUserId.equals(otherUserId)) { 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); // Чат отдельный на каждое объявление: иначе обращение к тому же автору по другому // объявлению возвращало старый чат с чужим postId (и чужой картинкой в списке чатов) Chat chat = chatRepository.findByUsersAndPost(userId1, userId2, postId).stream().findFirst().orElseGet(() -> { Chat newChat = new Chat(); newChat.setUserOneId(userId1); newChat.setUserTwoId(userId2); newChat.setPostId(postId); return chatRepository.save(newChat); }); saveAndBroadcast(chat, currentUserId, content); return toDto(chat, currentUserId); } // Все чаты пользователя: сверху чаты с самым свежим сообщением (или самые новые, если сообщений нет) @Transactional(readOnly = true) public List getUserChats(Long userId) { record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) { } return chatRepository.findAllByUserId(userId).stream() .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()); } // История сообщений в чате, с пагинацией и проверкой доступа @Transactional(readOnly = true) public Page getMessages(Long chatId, Long userId, Pageable pageable) { Chat chat = getChatOrThrow(chatId); checkParticipant(chat, userId); return messageRepository.findByChatIdOrderByCreatedAtDesc(chatId, pageable).map(this::toMessageDto); } // Отправка сообщения (вызывается из WebSocket контроллера) @Transactional public void sendMessage(Long senderId, Long chatId, String content) { validateContent(content); Chat chat = getChatOrThrow(chatId); checkParticipant(chat, senderId); saveAndBroadcast(chat, senderId, content); } private void validateContent(String content) { if (content == null || content.isBlank()) { throw new ApiException(ErrorCode.VALIDATION_ERROR, "Пустое сообщение", HttpStatus.BAD_REQUEST); } if (content.length() > MAX_MESSAGE_LENGTH) { throw new ApiException(ErrorCode.VALIDATION_ERROR, "Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST); } } private void saveAndBroadcast(Chat chat, Long senderId, String content) { Long chatId = chat.getId(); Message message = new Message(); message.setChatId(chatId); message.setSenderId(senderId); message.setContent(content); message = messageRepository.save(message); MessageDto dto = toMessageDto(message); // Уведомляем получателя об непрочитанных Long recipientId = chat.getUserOneId().equals(senderId) ? chat.getUserTwoId() : chat.getUserOneId(); long unreadCount = messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chatId, recipientId); // Рассылаем только после коммита: иначе клиент, получив событие и перезапросив // историю, мог не увидеть ещё не закоммиченное сообщение afterCommit(() -> { messaging.convertAndSend("/topic/chat/" + chatId, dto); messaging.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 public void deleteChat(Long chatId, Long userId) { Chat chat = getChatOrThrow(chatId); checkParticipant(chat, userId); chatRepository.deleteById(chatId); } @Transactional public void markAsRead(Long chatId, Long userId) { Chat chat = getChatOrThrow(chatId); checkParticipant(chat, userId); messageRepository.markAsReadByChatIdAndRecipient(chatId, userId); } /** * Проверка для STOMP-интерцептора: пользователь состоит в чате или нет. * Не бросает исключений — вызывается на этапе авторизации подписки. */ @Transactional(readOnly = true) public boolean isParticipant(Long chatId, Long userId) { if (chatId == null || userId == null) { return false; } return chatRepository.isParticipantOfChat(chatId, userId); } private Chat getChatOrThrow(Long chatId) { 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 ApiException(ErrorCode.FORBIDDEN, "Вы не участник этого чата", HttpStatus.FORBIDDEN); } } private ChatDto toDto(Chat chat, Long currentUserId) { Long otherUserId = chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId(); ChatDto dto = new ChatDto(); dto.setId(chat.getId()); dto.setOtherUserId(otherUserId); dto.setPostId(chat.getPostId()); userRepository.findById(otherUserId).ifPresent(user -> { dto.setOtherUserName(user.getName() + " " + user.getLastName()); dto.setOtherUserAvatar(user.getAvatarUrl()); }); if (chat.getPostId() != null) { postRepository.findById(chat.getPostId()).ifPresent(post -> { ChatPostDto postDto = new ChatPostDto(); postDto.setId(post.getId()); postDto.setTitle(post.getTitle()); postDto.setImages(post.getImages().stream().map(Image::getUrl).toList()); dto.setPost(postDto); }); } // без N+1: берём только последнее сообщение, а не всю историю messageRepository.findFirstByChatIdOrderByCreatedAtDesc(chat.getId()) .ifPresent(last -> { dto.setLastMessage(last.getContent()); dto.setLastMessageAt(last.getCreatedAt()); }); dto.setUnreadCount( messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chat.getId(), currentUserId) ); return dto; } private MessageDto toMessageDto(Message m) { MessageDto dto = new MessageDto(); dto.setId(m.getId()); dto.setChatId(m.getChatId()); dto.setSenderId(m.getSenderId()); dto.setContent(m.getContent()); dto.setRead(m.isRead()); dto.setCreatedAt(m.getCreatedAt()); return dto; } }