Skip to content

Commit

Permalink
Merge pull request #243 from prgrms-web-devcourse-final-project/feature/
Browse files Browse the repository at this point in the history
#234-AI-prompt-추가

채팅방 코드 수정
  • Loading branch information
Dom1046 authored Dec 26, 2024
2 parents 44f9e89 + d9e76c5 commit 49ed50e
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.mallangs.domain.chat.controller;

import com.mallangs.domain.chat.dto.response.ChatRoomCreateResponse;
import com.mallangs.domain.chat.dto.response.ChatRoomDeleteResponse;
import com.mallangs.domain.chat.dto.response.ChatRoomResponse;
import com.mallangs.domain.chat.dto.response.ParticipatedRoomListResponse;
import com.mallangs.domain.chat.service.ChatMessageService;
Expand All @@ -11,6 +13,7 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
Expand All @@ -34,14 +37,13 @@ public class ChatRoomController {
@Operation(summary = "채팅방 생성", description = "채팅방을 생성합니다.")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "채팅방 생성 성공"),
@ApiResponse(responseCode = "400", description = "잘못된 요청")
@ApiResponse(responseCode = "404", description = "회원정보를 찾을 수 없습니다.")
})
public ResponseEntity<Long> create(@PathVariable("memberId") Long memberId,
@AuthenticationPrincipal CustomMemberDetails customMemberDetails) {
public ResponseEntity<ChatRoomCreateResponse> create(@PathVariable("memberId") Long memberId,
@AuthenticationPrincipal CustomMemberDetails customMemberDetails) {

Long myId = customMemberDetails.getMemberId();
Long roomId = chatRoomService.create(memberId, myId);
return ResponseEntity.created(URI.create("/api/chat-room/" + roomId)).body(roomId);
return ResponseEntity.status(HttpStatus.CREATED).body(chatRoomService.create(memberId, myId));
}

//채팅방리스트 조회
Expand All @@ -54,7 +56,7 @@ public ResponseEntity<Long> create(@PathVariable("memberId") Long memberId,
public ResponseEntity<List<ParticipatedRoomListResponse>> getList(
@AuthenticationPrincipal CustomMemberDetails customMemberDetails) {
log.info("채팅방 조회 memberId 입력값: {}", customMemberDetails.getMemberId());
return ResponseEntity.ok(chatRoomService.get(customMemberDetails.getMemberId()));
return ResponseEntity.status(HttpStatus.CREATED).body(chatRoomService.get(customMemberDetails.getMemberId()));
}

// //채팅방 수정
Expand All @@ -74,28 +76,28 @@ public ResponseEntity<List<ParticipatedRoomListResponse>> getList(
@Operation(summary = "참여 채팅방 삭제", description = "참여 채팅방을 나갑니다.")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "삭제 성공"),
@ApiResponse(responseCode = "400", description = "참여 채팅방이 존재하지 않습니다.")
@ApiResponse(responseCode = "401", description = "참여 채팅방 삭제 권한이 없는 사용자 입니다."),
@ApiResponse(responseCode = "404", description = "참여 채팅방이 존재하지 않습니다.")
})
public ResponseEntity<?> delete(@PathVariable("participatedRoomId") Long participatedRoomId,
Authentication authentication) {
chatRoomService.delete(authentication.getName(), participatedRoomId);
return ResponseEntity.ok().build();
public ResponseEntity<ChatRoomDeleteResponse> delete(@PathVariable("participatedRoomId") Long participatedRoomId,
Authentication authentication) {
return ResponseEntity.status(HttpStatus.CREATED).body(chatRoomService.delete(authentication.getName(), participatedRoomId));
}


//참여 채팅방 조회
@ResponseBody
@GetMapping("/{participatedRoomId}")
@Operation(summary = "참여 채팅방 조회", description = "참여 채팅방을 조회합니다.")
@GetMapping("/{profileMemberId}")
@Operation(summary = "타인이 내 채팅방 조회", description = "타인이 내 채팅방을 조회합니다.")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "조회 성공"),
@ApiResponse(responseCode = "400", description = "채팅방이 존재하지 않습니다.")
})
public ResponseEntity<ChatRoomResponse> changeStatus(@PathVariable Long participatedRoomId,
public ResponseEntity<ChatRoomResponse> changeStatus(@PathVariable Long profileMemberId,
@AuthenticationPrincipal CustomMemberDetails customMemberDetails) {

String nickname = customMemberDetails.getNickname();
return ResponseEntity.ok(chatMessageService.changeUnReadToRead(participatedRoomId, nickname));
Long memberId = customMemberDetails.getMemberId();
return ResponseEntity.status(HttpStatus.CREATED).body(chatMessageService.changeUnReadToRead(profileMemberId, memberId));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.mallangs.domain.chat.dto.response;

import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
public class ChatRoomCreateResponse {
private String success;
private String message;
private Long chatRoomId;

public ChatRoomCreateResponse(Long chatRoomId) {
this.success = "성공";
this.message = "채팅 생성에 성공하였습니다.";
this.chatRoomId = chatRoomId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.mallangs.domain.chat.dto.response;

import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
public class ChatRoomDeleteResponse {
private String success;
private String message;
private Long participatedRoomId;

public ChatRoomDeleteResponse(Long participatedRoomId) {
this.success = "성공";
this.message = "참여채팅방 삭제에 성공하였습니다.";
this.participatedRoomId = participatedRoomId;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.mallangs.domain.chat.repository;

import com.mallangs.domain.chat.entity.ParticipatedRoom;
import com.mallangs.domain.member.entity.embadded.Nickname;
import com.mallangs.domain.member.entity.embadded.UserId;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
Expand Down Expand Up @@ -34,4 +35,12 @@ public interface ParticipatedRoomRepository extends JpaRepository<ParticipatedRo
" WHERE p.participatedRoomId = :participatedRoomId")
Optional<ParticipatedRoom> findByPRoomId(@Param("participatedRoomId") Long participatedRoomId);

// 참여채팅방 Id로 참여채팅방 불러오기- 회원, 채팅방 조인
@Query("SELECT DISTINCT p FROM ParticipatedRoom p" +
" LEFT JOIN FETCH p.participant m" +
" LEFT JOIN FETCH p.chatRoom c" +
" WHERE p.roomName = :myNickname" +
" AND p.participant.memberId = :otherId ")
Optional<ParticipatedRoom> findByMyNicknameAndOtherId(@Param("myNickname") String myNickname, @Param("otherId") Long otherId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import com.mallangs.domain.chat.repository.ChatMessageRepository;
import com.mallangs.domain.chat.repository.ParticipatedRoomRepository;
import com.mallangs.domain.member.dto.PageRequestDTO;
import com.mallangs.domain.member.entity.Member;
import com.mallangs.domain.member.repository.MemberRepository;
import com.mallangs.global.exception.ErrorCode;
import com.mallangs.global.exception.MallangsCustomException;
import lombok.RequiredArgsConstructor;
Expand All @@ -20,6 +22,8 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Log4j2
@Service
@Transactional
Expand All @@ -29,6 +33,7 @@ public class ChatMessageService {
private final ChatMessageRepository chatMessageRepository;
private final ParticipatedRoomRepository participatedRoomRepository;
private final RedisSubscriber redisSubscriber;
private final MemberRepository memberRepository;

//채팅 메세지 생성/송신
public ChatMessageSuccessResponse sendMessage(ChatMessageRequest chatMessageRequest) {
Expand Down Expand Up @@ -132,18 +137,24 @@ public Page<ChatMessageListResponse> getPage(PageRequestDTO pageRequestDTO, Long
}

//가장 최근 읽음 처리된 메세지 부터, 찾아 읽음 처리하는 메서드
public ChatRoomResponse changeUnReadToRead(Long participatedRoomId, String nickname) {
public ChatRoomResponse changeUnReadToRead(Long profileMemberId, Long myId) {

Member proFileMember = memberRepository.findById(profileMemberId)
.orElseThrow(() -> new MallangsCustomException(ErrorCode.MEMBER_NOT_FOUND));

Member myMember = memberRepository.findById(myId)
.orElseThrow(() -> new MallangsCustomException(ErrorCode.MEMBER_NOT_FOUND));

//참여 채팅 정보 추출
ParticipatedRoom foundPartRoom = participatedRoomRepository.findByParticipatedRoomId(participatedRoomId)
ParticipatedRoom foundPartRoom = participatedRoomRepository.findByMyNicknameAndOtherId(myMember.getNickname().getValue(), profileMemberId)
.orElseThrow(() -> new MallangsCustomException(ErrorCode.PARTICIPATED_ROOM_NOT_FOUND));

ChatRoom chatRoom = foundPartRoom.getChatRoom();
if (chatRoom == null) {
throw new MallangsCustomException(ErrorCode.CHATROOM_NOT_FOUND);
}

int numChanged = chatMessageRepository.updateRead(chatRoom.getChatRoomId(), nickname);
int numChanged = chatMessageRepository.updateRead(chatRoom.getChatRoomId(), proFileMember.getNickname().getValue());

//dto 로 변경
return ChatRoomResponse.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.mallangs.domain.chat.service;

import com.mallangs.domain.chat.dto.request.ChatRoomChangeNameRequest;
import com.mallangs.domain.chat.dto.response.ChatRoomCreateResponse;
import com.mallangs.domain.chat.dto.response.ChatRoomDeleteResponse;
import com.mallangs.domain.chat.dto.response.ChatRoomResponse;
import com.mallangs.domain.chat.dto.response.ParticipatedRoomListResponse;
import com.mallangs.domain.chat.entity.ChatMessage;
Expand Down Expand Up @@ -41,7 +43,7 @@ public class ChatRoomService {
private final SseEmitters sseEmitters;

// 채팅방 생성
public Long create(Long myId, Long partnerId) {
public ChatRoomCreateResponse create(Long myId, Long partnerId) {
//채팅방 생성
ChatRoom chatRoom = ChatRoom.builder().build();
ChatRoom savedChatRoom = chatRoomRepository.save(chatRoom);
Expand Down Expand Up @@ -95,7 +97,7 @@ public Long create(Long myId, Long partnerId) {
}
}

return savedChatRoom.getChatRoomId();
return new ChatRoomCreateResponse(savedChatRoom.getChatRoomId());
}

//채팅방 리스트 조회
Expand Down Expand Up @@ -152,12 +154,13 @@ public boolean update(ChatRoomChangeNameRequest chatRoomChangeNameRequest) {
}

//채팅방 삭제
public void delete(String userId, Long participatedRoomId) {
public ChatRoomDeleteResponse delete(String userId, Long participatedRoomId) {
ParticipatedRoom partRoom = participatedRoomRepository.findByPRoomId(participatedRoomId)
.orElseThrow(() -> new MallangsCustomException(ErrorCode.PARTICIPATED_ROOM_NOT_FOUND));

if (partRoom.getParticipant().getUserId().getValue().equals(userId)) {
participatedRoomRepository.deleteById(participatedRoomId);
return new ChatRoomDeleteResponse(partRoom.getParticipatedRoomId());
} else {
throw new MallangsCustomException(ErrorCode.FAILED_DELETE_CHATROOM);
}
Expand Down

0 comments on commit 49ed50e

Please sign in to comment.