create chats only together with the first message

- GET /api/v1/chats/with/{otherUserId}?postId= finds an existing chat
  (404 if there is none) and never creates one
- POST /api/v1/chats/with/{otherUserId}/messages?postId= with {content}
  finds or creates the chat and saves the first message in one
  transaction; same participant/post checks as before, WebSocket events
  still sent after commit
- the old POST /with/{otherUserId} that created empty chats is removed
- chat list hides chats without messages (existing empty rows stay in DB)
- empty messages are rejected with 400

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-13 01:45:18 +03:00
parent 73463f6c5b
commit cd0d2a4081
5 changed files with 102 additions and 18 deletions

View File

@@ -2,6 +2,7 @@ package com.krylov.refound.controller;
import com.krylov.refound.dto.ChatDto; import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.dto.MessageDto; import com.krylov.refound.dto.MessageDto;
import com.krylov.refound.dto.StartChatRequest;
import com.krylov.refound.service.ChatService; import com.krylov.refound.service.ChatService;
import com.krylov.refound.service.UserService; import com.krylov.refound.service.UserService;
import java.util.List; import java.util.List;
@@ -11,11 +12,13 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault; import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -29,12 +32,21 @@ public class ChatController {
private final UserService userService; private final UserService userService;
private final ChatService chatService; private final ChatService chatService;
// Создать чат с пользователем или получить существующий // Существующий чат с пользователем по объявлению; 404, если переписки ещё нет (чат не создаётся)
@PostMapping("/with/{otherUserId}") @GetMapping("/with/{otherUserId}")
public ChatDto createOrGetChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) { public ResponseEntity<ChatDto> findChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId, Authentication auth) {
Long currentUserId = extractUserId(auth); Long currentUserId = extractUserId(auth);
log.info("createOrGetChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId); log.info("findChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.getOrCreateChat(currentUserId, otherUserId, postId); return ResponseEntity.of(chatService.findChat(currentUserId, otherUserId, postId));
}
// Первое сообщение: чат создаётся (или находится) вместе с сообщением — пустых чатов не бывает
@PostMapping("/with/{otherUserId}/messages")
public ChatDto startChat(@PathVariable Long otherUserId, @RequestParam(required = false) Long postId,
@RequestBody StartChatRequest request, Authentication auth) {
Long currentUserId = extractUserId(auth);
log.info("startChat currentUserId {}, otherUserId {}, postId {}", currentUserId, otherUserId, postId);
return chatService.startChat(currentUserId, otherUserId, postId, request.getContent());
} }
// Список всех чатов текущего пользователя // Список всех чатов текущего пользователя

View File

@@ -0,0 +1,9 @@
package com.krylov.refound.dto;
import lombok.Data;
/** Первое сообщение, с которым создаётся чат. */
@Data
public class StartChatRequest {
private String content;
}

View File

@@ -20,8 +20,10 @@ public interface ChatRepository extends JpaRepository<Chat, Long> {
+ "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)") + "WHERE c.id = :chatId AND (c.userOneId = :userId OR c.userTwoId = :userId)")
boolean isParticipantOfChat(Long chatId, Long userId); boolean isParticipantOfChat(Long chatId, Long userId);
@Query("SELECT c FROM Chat c WHERE c.userOneId = :userId OR c.userTwoId = :userId ORDER BY c.createdAt DESC") /** Чаты пользователя, в которых есть хотя бы одно сообщение (пустые в списке не показываем). */
List<Chat> findAllByUserId(Long userId); // Changed from Optional to List @Query("SELECT c FROM Chat c WHERE (c.userOneId = :userId OR c.userTwoId = :userId) "
+ "AND EXISTS (SELECT 1 FROM Message m WHERE m.chatId = c.id) ORDER BY c.createdAt DESC")
List<Chat> findAllByUserId(Long userId);
/** /**
* Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась. * Объявление удалено администратором: обнуляем ссылку, чтобы переписка сохранилась.

View File

@@ -16,6 +16,7 @@ import com.krylov.refound.repository.UserRepository;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@@ -43,9 +44,26 @@ public class ChatService {
private final UserRepository userRepository; private final UserRepository userRepository;
private final PostRepository postRepository; private final PostRepository postRepository;
// Создать чат с пользователем (или вернуть существующий) /**
* Ищет существующий чат с пользователем по объявлению, ничего не создавая.
* Пустой чат «на будущее» не заводим: он появляется только с первым сообщением.
*/
@Transactional(readOnly = true)
public Optional<ChatDto> 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 @Transactional
public ChatDto getOrCreateChat(Long currentUserId, Long otherUserId, Long postId) { public ChatDto startChat(Long currentUserId, Long otherUserId, Long postId, String content) {
validateContent(content);
if (currentUserId.equals(otherUserId)) { if (currentUserId.equals(otherUserId)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST); throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
} }
@@ -75,6 +93,7 @@ public class ChatService {
return chatRepository.save(newChat); return chatRepository.save(newChat);
}); });
saveAndBroadcast(chat, currentUserId, content);
return toDto(chat, currentUserId); return toDto(chat, currentUserId);
} }
@@ -106,14 +125,26 @@ public class ChatService {
// Отправка сообщения (вызывается из WebSocket контроллера) // Отправка сообщения (вызывается из WebSocket контроллера)
@Transactional @Transactional
public void sendMessage(Long senderId, Long chatId, String content) { public void sendMessage(Long senderId, Long chatId, String content) {
if (content.length() > MAX_MESSAGE_LENGTH) { validateContent(content);
throw new ApiException(ErrorCode.VALIDATION_ERROR,
"Сообщение длиннее " + MAX_MESSAGE_LENGTH + " символов", HttpStatus.BAD_REQUEST);
}
Chat chat = getChatOrThrow(chatId); Chat chat = getChatOrThrow(chatId);
checkParticipant(chat, senderId); 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 message = new Message();
message.setChatId(chatId); message.setChatId(chatId);
message.setSenderId(senderId); message.setSenderId(senderId);

View File

@@ -5,10 +5,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import com.krylov.refound.dto.ChatDto; import com.krylov.refound.dto.ChatDto;
import com.krylov.refound.entity.Chat; import com.krylov.refound.entity.Chat;
import com.krylov.refound.entity.Message;
import com.krylov.refound.entity.Post; import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User; import com.krylov.refound.entity.User;
import com.krylov.refound.exception.ApiException; import com.krylov.refound.exception.ApiException;
@@ -20,6 +23,7 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.SimpMessagingTemplate;
@@ -28,6 +32,7 @@ class ChatServiceTest {
private ChatRepository chatRepository; private ChatRepository chatRepository;
private UserRepository userRepository; private UserRepository userRepository;
private PostRepository postRepository; private PostRepository postRepository;
private MessageRepository messageRepository;
private ChatService chatService; private ChatService chatService;
@BeforeEach @BeforeEach
@@ -35,7 +40,7 @@ class ChatServiceTest {
chatRepository = mock(ChatRepository.class); chatRepository = mock(ChatRepository.class);
userRepository = mock(UserRepository.class); userRepository = mock(UserRepository.class);
postRepository = mock(PostRepository.class); postRepository = mock(PostRepository.class);
MessageRepository messageRepository = mock(MessageRepository.class); messageRepository = mock(MessageRepository.class);
chatService = new ChatService(chatRepository, messageRepository, mock(SimpMessagingTemplate.class), chatService = new ChatService(chatRepository, messageRepository, mock(SimpMessagingTemplate.class),
userRepository, postRepository); userRepository, postRepository);
@@ -47,6 +52,11 @@ class ChatServiceTest {
chat.setId(100L); chat.setId(100L);
return chat; return chat;
}); });
when(messageRepository.save(any(Message.class))).thenAnswer(inv -> {
Message message = inv.getArgument(0);
message.setId(500L);
return message;
});
} }
private void postOwnedBy(long postId, long ownerId) { private void postOwnedBy(long postId, long ownerId) {
@@ -59,26 +69,46 @@ class ChatServiceTest {
} }
@Test @Test
void createsChatAboutPostOfOtherUser() { void startChatCreatesChatTogetherWithFirstMessage() {
postOwnedBy(41L, 19L); postOwnedBy(41L, 19L);
ChatDto chat = chatService.getOrCreateChat(14L, 19L, 41L); ChatDto chat = chatService.startChat(14L, 19L, 41L, "Здравствуйте");
assertThat(chat.getPostId()).isEqualTo(41L); assertThat(chat.getPostId()).isEqualTo(41L);
assertThat(chat.getOtherUserId()).isEqualTo(19L); assertThat(chat.getOtherUserId()).isEqualTo(19L);
ArgumentCaptor<Message> saved = ArgumentCaptor.forClass(Message.class);
verify(messageRepository).save(saved.capture());
assertThat(saved.getValue().getChatId()).isEqualTo(100L);
assertThat(saved.getValue().getContent()).isEqualTo("Здравствуйте");
}
@Test
void findChatDoesNotCreateChat() {
assertThat(chatService.findChat(14L, 19L, 41L)).isEmpty();
verify(chatRepository, never()).save(any());
}
@Test
void rejectsEmptyFirstMessageWithoutCreatingChat() {
postOwnedBy(41L, 19L);
assertThatThrownBy(() -> chatService.startChat(14L, 19L, 41L, " "))
.isInstanceOf(ApiException.class);
verify(chatRepository, never()).save(any());
} }
@Test @Test
void rejectsPostOfThirdUser() { void rejectsPostOfThirdUser() {
postOwnedBy(41L, 7L); postOwnedBy(41L, 7L);
assertThatThrownBy(() -> chatService.getOrCreateChat(14L, 19L, 41L)) assertThatThrownBy(() -> chatService.startChat(14L, 19L, 41L, "Здравствуйте"))
.isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST)); .isInstanceOfSatisfying(ApiException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
verify(chatRepository, never()).save(any());
} }
@Test @Test
void rejectsChatWithYourself() { void rejectsChatWithYourself() {
assertThatThrownBy(() -> chatService.getOrCreateChat(19L, 19L, 41L)) assertThatThrownBy(() -> chatService.startChat(19L, 19L, 41L, "Здравствуйте"))
.isInstanceOf(ApiException.class) .isInstanceOf(ApiException.class)
.hasMessageContaining("самим собой"); .hasMessageContaining("самим собой");
} }