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

@@ -16,6 +16,7 @@ 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;
@@ -43,9 +44,26 @@ public class ChatService {
private final UserRepository userRepository;
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
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)) {
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нельзя создать чат с самим собой", HttpStatus.BAD_REQUEST);
}
@@ -75,6 +93,7 @@ public class ChatService {
return chatRepository.save(newChat);
});
saveAndBroadcast(chat, currentUserId, content);
return toDto(chat, currentUserId);
}
@@ -106,14 +125,26 @@ 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);
}
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);