Skip to content

Commit

Permalink
Merge pull request #253 from team9502/dev
Browse files Browse the repository at this point in the history
배포
  • Loading branch information
daeundada authored Jun 30, 2024
2 parents a175948 + 892add0 commit 481b582
Show file tree
Hide file tree
Showing 27 changed files with 310 additions and 125 deletions.
6 changes: 0 additions & 6 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,6 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-web-services'

//Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

// WebSocket
implementation 'org.springframework.boot:spring-boot-starter-websocket'

Expand Down Expand Up @@ -62,9 +59,6 @@ dependencies {

implementation 'com.sun.mail:jakarta.mail:2.0.1'

implementation 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate5-jakarta:2.14.1'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.1'

implementation 'javax.servlet:javax.servlet-api:4.0.1'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.mysql:mysql-connector-j'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
package team9502.sinchulgwinong.domain.chat.controller;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import team9502.sinchulgwinong.domain.chat.dto.request.ChatRequestDTO;
import team9502.sinchulgwinong.domain.chat.dto.response.ChatMessageResponseDTO;
import team9502.sinchulgwinong.domain.chat.dto.response.ChatRoomResponseDTO;
import team9502.sinchulgwinong.domain.chat.service.ChatService;
Expand All @@ -21,11 +17,12 @@

@RestController
@RequiredArgsConstructor
@RequestMapping("/chats")
public class ChatController {

private final ChatService chatService;

@PostMapping("/chats/cp-user/{cpUserId}")
@PostMapping("/cp-user/{cpUserId}")
public ResponseEntity<GlobalApiResponse<ChatRoomResponseDTO>> createChatRoom(
@AuthenticationPrincipal UserDetailsImpl userDetails,
@PathVariable("cpUserId") Long cpUserId) {
Expand All @@ -43,7 +40,7 @@ public ResponseEntity<GlobalApiResponse<ChatRoomResponseDTO>> createChatRoom(
);
}

@GetMapping("/chats/chat-rooms")
@GetMapping("/chat-rooms")
public ResponseEntity<GlobalApiResponse<List<ChatRoomResponseDTO>>> getChatRooms(
@AuthenticationPrincipal UserDetailsImpl userDetails) {

Expand All @@ -57,21 +54,12 @@ public ResponseEntity<GlobalApiResponse<List<ChatRoomResponseDTO>>> getChatRooms
);
}

@MessageMapping("/chats/chat-room/{chatRoomId}")
@SendTo("/topic/chatroom/{chatRoomId}")
public ChatMessageResponseDTO saveAndSendMessage(
@RequestBody @Valid ChatRequestDTO chatRequestDTO,
@GetMapping("/chat-room/{chatRoomId}")
public ResponseEntity<GlobalApiResponse<List<ChatMessageResponseDTO>>> getChatMessages(
@PathVariable(name = "chatRoomId") Long chatRoomId,
@AuthenticationPrincipal UserDetailsImpl userDetails) {

return chatService.saveAndSendMessage(userDetails, chatRequestDTO, chatRoomId);
}

@GetMapping("/chats/chat-room/{chatRoomId}")
public ResponseEntity<GlobalApiResponse<List<ChatMessageResponseDTO>>> getChatMessages(
@PathVariable(name = "chatRoomId") Long chatRoomId) {

List<ChatMessageResponseDTO> messages = chatService.getChatMessages(chatRoomId);
List<ChatMessageResponseDTO> messages = chatService.getChatMessages(chatRoomId, userDetails);

return ResponseEntity.status(SUCCESS_READ_CHAT_MESSAGES.getHttpStatus())
.body(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
package team9502.sinchulgwinong.domain.chat.dto.request;

import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
public class ChatRequestDTO {

@NotBlank
private String message;
private Long userId;

private Long cpUserId;

private Long chatRoomId;

private String content;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ public class ChatMessageResponseDTO {

private Long userId;

private String message;
private String content;

private LocalDateTime createAt;

public ChatMessageResponseDTO(ChatMessage chatMessage) {
this.chatMessageId = chatMessage.getChatMessageId();
this.chatRoomId = chatMessage.getChatRoom().getChatRoomId();
this.message = chatMessage.getMessage();
this.content = chatMessage.getContent();
this.createAt = chatMessage.getCreatedAt();

if (chatMessage.getCompanyUser() != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package team9502.sinchulgwinong.domain.chat.dto.response;

import jakarta.persistence.Column;
import lombok.Getter;
import team9502.sinchulgwinong.domain.chat.entity.ChatRoom;

Expand All @@ -18,7 +19,9 @@ public class ChatRoomResponseDTO {

private String chatName;

private boolean chatCheck;
private boolean userRead;

private boolean companyUserRead;

public ChatRoomResponseDTO(ChatRoom chatRoom) {
this.chatRoomId = chatRoom.getChatRoomId();
Expand All @@ -27,6 +30,7 @@ public ChatRoomResponseDTO(ChatRoom chatRoom) {
this.userName = chatRoom.getUser().getUsername();
this.cpName = chatRoom.getCompanyUser().getCpName();
this.chatName = chatRoom.getChatName();
this.chatCheck = chatRoom.isChatCheck();
this.userRead = chatRoom.isUserRead();
this.companyUserRead = chatRoom.isCompanyUserRead();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ public class ChatMessage extends BaseTimeEntity {

@Setter
@Column(nullable = false, length = 400)
private String message;
private String content;
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,9 @@ public class ChatRoom extends BaseTimeEntity {

@Setter
@Column(nullable = false)
private boolean chatCheck;
private boolean userRead; // 일반 사용자의 읽음 상태

@Setter
@Column(nullable = false)
private boolean companyUserRead; // 회사 사용자의 읽음 상태
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@


import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team9502.sinchulgwinong.domain.chat.dto.request.ChatRequestDTO;
import team9502.sinchulgwinong.domain.chat.dto.response.ChatMessageResponseDTO;
import team9502.sinchulgwinong.domain.chat.dto.response.ChatRoomResponseDTO;
import team9502.sinchulgwinong.domain.chat.entity.ChatMessage;
Expand All @@ -15,23 +14,25 @@
import team9502.sinchulgwinong.domain.companyUser.entity.CompanyUser;
import team9502.sinchulgwinong.domain.companyUser.repository.CompanyUserRepository;
import team9502.sinchulgwinong.domain.user.entity.User;
import team9502.sinchulgwinong.domain.user.repository.UserRepository;
import team9502.sinchulgwinong.global.exception.ApiException;
import team9502.sinchulgwinong.global.exception.ErrorCode;
import team9502.sinchulgwinong.global.security.UserDetailsImpl;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
@RequiredArgsConstructor
public class ChatService {

private final ChatMessageRepository chatMessageRepository;
private final CompanyUserRepository companyUserRepository;
private final ChatRoomRepository chatRoomRepository;
private final SimpMessagingTemplate messagingTemplate;
private final UserRepository userRepository;

//채팅방 생성
@Transactional
public ChatRoomResponseDTO createChatRoom(User user, Long cpUserId) {

Expand All @@ -42,86 +43,110 @@ public ChatRoomResponseDTO createChatRoom(User user, Long cpUserId) {
chatRoom.setChatName(companyUser.getCpName());
chatRoom.setUser(user);
chatRoom.setCompanyUser(companyUser);
chatRoom.setChatCheck(false);
chatRoom.setUserRead(false);
chatRoom.setCompanyUserRead(false);

chatRoomRepository.save(chatRoom);

notifyChatRoomUpdate();

return new ChatRoomResponseDTO(chatRoom);
}

@Transactional(readOnly = true)
// 채팅방 목록
@Transactional
public List<ChatRoomResponseDTO> getChatRooms(UserDetailsImpl userDetails) {
List<ChatRoom> chatRooms;

if (userDetails.getUser() != null) {
chatRooms = chatRoomRepository.findByUser_UserId(userDetails.getUserId());
} else {
chatRooms = chatRoomRepository.findByCompanyUser_CpUserId(userDetails.getCpUserId());
List<ChatRoom> chatRooms = null;

switch (userDetails.getUserType()) {
case "USER":
if (userDetails.getUser() != null) {
chatRooms = chatRoomRepository.findByUser_UserId(userDetails.getUserId());
}
break;
case "COMPANY_USER":
if (userDetails.getCpUserId() != null) {
chatRooms = chatRoomRepository.findByCompanyUser_CpUserId(userDetails.getCpUserId());
}
break;
default:
throw new ApiException(ErrorCode.USER_NOT_FOUND);
}

if (chatRooms == null) {
throw new ApiException(ErrorCode.CHAT_NOT_FOUND);
}

return chatRooms.stream()
.map(ChatRoomResponseDTO::new)
.collect(Collectors.toList());
}

public void notifyChatRoomUpdate() {
List<ChatRoomResponseDTO> chatRooms = chatRoomRepository.findAll()
.stream()
.map(ChatRoomResponseDTO::new)
.collect(Collectors.toList());
//이전 채팅 내역 불러오기
@Transactional
public List<ChatMessageResponseDTO> getChatMessages(Long chatRoomId, UserDetailsImpl userDetails) {

ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
.orElseThrow(() -> new ApiException(ErrorCode.CHAT_NOT_FOUND));

messagingTemplate.convertAndSend("/topic/chatrooms", chatRooms);
List<ChatMessage> messages = chatMessageRepository.findByChatRoom_ChatRoomId(chatRoomId);

switch (userDetails.getUserType()) {
case "USER":
if (userDetails.getUser() != null) {
chatRoom.setUserRead(false);
}
break;
case "COMPANY_USER":
if (userDetails.getCpUserId() != null) {
chatRoom.setCompanyUserRead(false);
}
break;
default:
throw new ApiException(ErrorCode.USER_NOT_FOUND);
}

chatMessageRepository.saveAll(messages);

return messages.stream()
.map(ChatMessageResponseDTO::new)
.collect(Collectors.toList());
}

@Transactional
public ChatMessageResponseDTO saveAndSendMessage(UserDetailsImpl userDetails, ChatRequestDTO chatRequestDTO, Long chatRoomId) {
public ChatMessage saveMessage(Long cpUserId, Long userId, Long chatRoomId, String content) {

ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
.orElseThrow(() -> new ApiException(ErrorCode.CHAT_NOT_FOUND));

ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessage(chatRequestDTO.getMessage());
chatMessage.setChatRoom(chatRoom);

if (userDetails.getUser() != null) {
User user = (User) userDetails.getUser();
if (userId != null) {

User user = userRepository.findById(userId)
.orElseThrow(() -> new ApiException(ErrorCode.USER_NOT_FOUND));

chatMessage.setUser(user);
chatMessage.setCompanyUser(null);
} else if (userDetails.getCpUserId() != null) {
CompanyUser companyUser = companyUserRepository.findById(userDetails.getCpUserId())

chatRoom.setCompanyUserRead(true); // 유저가 메시지를 보낸 경우 읽음으로 설정
chatRoom.setUserRead(false); // 유저가 메시지를 보낸 경우 유저는 읽음으로 설정

} else {
CompanyUser companyUser = companyUserRepository.findById(cpUserId)
.orElseThrow(() -> new ApiException(ErrorCode.COMPANY_USER_NOT_FOUND));

chatMessage.setCompanyUser(companyUser);
chatMessage.setUser(null);

chatRoom.setUserRead(true); // 기업 유저가 메시지를 보낸 경우 읽음으로 설정
chatRoom.setCompanyUserRead(false); // 기업 유저가 메시지를 보낸 경우 기업 유저는 읽음으로 설정
}

chatMessageRepository.save(chatMessage);
chatMessage.setContent(content);
chatMessage.setChatRoom(chatRoom);

chatRoom.setChatCheck(true);
chatRoomRepository.save(chatRoom);

messagingTemplate.convertAndSend("/topic/chatroom/" + chatRoomId, new ChatMessageResponseDTO(chatMessage));

notifyChatRoomUpdate();

return new ChatMessageResponseDTO(chatMessage);
}

@Transactional
public List<ChatMessageResponseDTO> getChatMessages(Long chatRoomId) {
ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId)
.orElseThrow(() -> new ApiException(ErrorCode.CHAT_NOT_FOUND));

List<ChatMessage> messages = chatMessageRepository.findByChatRoom_ChatRoomId(chatRoomId);

if (chatRoom.isChatCheck()) {
chatRoom.setChatCheck(false);
}

chatMessageRepository.saveAll(messages);

return messages.stream()
.map(ChatMessageResponseDTO::new)
.collect(Collectors.toList());
return chatMessageRepository.save(chatMessage);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public ResponseEntity<GlobalApiResponse<Void>> updateUserProfile(
@ApiResponses({
@ApiResponse(responseCode = "200", description = "기업 사용자 전체 조회 성공",
content = @Content(mediaType = "application/json",
examples = @ExampleObject(value = "{ \"message\": \"기업 사용자 전체 조회 성공\", \"data\": { \"cpUsers\": [{ \"cpUserId\": 1, \"cpName\": \"고양이탕후루\", \"reviewCount\": 3, \"averageRating\": 3.0 }], \"totalCpUserCount\": 1, \"currentPage\": 0, \"totalPages\": 1 } }"))),
examples = @ExampleObject(value = "{ \"message\": \"기업 사용자 전체 조회 성공\", \"data\": { \"cpUsers\": [{ \"cpUserId\": 1, \"cpName\": \"고양이탕후루\", \"reviewCount\": 3, \"averageRating\": 3.0 }], \"totalCpUserCount\": 1, \"currentPage\": 0, \"totalPages\": 1, \"viewCount\": null } }"))),
@ApiResponse(responseCode = "400", description = "잘못된 요청 값",
content = @Content(mediaType = "application/json",
examples = @ExampleObject(value = "{\"message\": \"잘못된 요청 값입니다.\" }"))),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ public class CpUserResponseDTO {
private Integer reviewCount;

private Float averageRating;

private Integer viewCount;
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,13 @@ public void usePointsForBanner(Long cpUserId) {
}

private CpUserResponseDTO convertToDTO(CompanyUser companyUser) {

return new CpUserResponseDTO(
companyUser.getCpUserId(),
companyUser.getCpName(),
companyUser.getReviewCount(),
companyUser.getAverageRating()
companyUser.getAverageRating(),
companyUser.getViewCount()
);
}
}
Loading

0 comments on commit 481b582

Please sign in to comment.