Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

640 방 나가기 api #677

Merged
merged 11 commits into from
Mar 5, 2024
12 changes: 12 additions & 0 deletions gg-data/src/main/java/gg/data/party/Room.java
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,16 @@ public Room(User host, User creator, Category category, String title, String con
this.dueDate = dueDate;
this.status = status;
}

public void updateCurrentPeople(int currentPeople) {
this.currentPeople = currentPeople;
}

public void updateStatus(RoomType status) {
this.status = status;
}

public void updateHost(User host) {
this.host = host;
}
}
10 changes: 7 additions & 3 deletions gg-data/src/main/java/gg/data/party/UserRoom.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gg.data.party;

import java.time.LocalDateTime;
import static gg.utils.exception.BusinessChecker.*;
import static gg.utils.exception.ErrorCode.*;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

static 처음보네요 음 뭐 없으면 안된다니 참고하겠습니다


import javax.persistence.Column;
import javax.persistence.Entity;
Expand All @@ -12,10 +13,8 @@
import javax.persistence.ManyToOne;

import gg.data.BaseTimeEntity;
import gg.data.tournament.Tournament;
import gg.data.user.User;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

Expand Down Expand Up @@ -48,6 +47,11 @@ public UserRoom(User user, Room room, String randomNickname) {
this.isExist = true;
}

public void updateIsExist(boolean isExist) {
mustNotNull(isExist, NULL_POINT);
this.isExist = isExist;
}

public boolean getIsExist() {
return this.isExist;
}
Expand Down
31 changes: 27 additions & 4 deletions gg-data/src/main/java/gg/data/party/type/RoomType.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
package gg.data.party.type;

import java.util.Locale;

import com.fasterxml.jackson.annotation.JsonCreator;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public enum RoomType {
OPEN, // Ordinal 0
START, // Ordinal 1
FINISH, // Ordinal 2
HIDDEN // Ordinal 3
OPEN("open", "방 시작 전"),
START("live", "방 진행 중"),
FINISH("end", "방 종료"),
HIDDEN("end", "신고로 인한 가림 상태"),
FAIL("end", "매칭 실패한 방");

private final String code;
private final String desc;

@JsonCreator
public static RoomType getEnumFromValue(String value) {
if (value == null) {
return null;
}
for (RoomType e : values()) {
if (e.name().equals(value)) {
return e;
} else if (e.code.toUpperCase(Locale.ROOT).equals(value.toUpperCase(Locale.ROOT))) {
return e;
}
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public class CommentService {
@Transactional
public void createComment(Long roomId, CommentCreateReqDto reqDto, Long userId) {
Room room = roomRepository.findById(roomId)
.orElseThrow(() -> new RoomNotFoundException("방을 찾을 수 없습니다."));
.orElseThrow(() -> new RoomNotFoundException(ErrorCode.ROOM_NOT_FOUND));
if (LocalDateTime.now().isAfter(room.getDueDate())) {
throw new RoomUpdateException(ErrorCode.ROOM_FINISHED);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
Expand All @@ -12,6 +13,7 @@
import gg.auth.UserDto;
import gg.auth.argumentresolver.Login;
import gg.party.api.user.room.controller.request.RoomCreateReqDto;
import gg.party.api.user.room.controller.response.LeaveRoomResDto;
import gg.party.api.user.room.controller.response.RoomDetailResDto;
import gg.party.api.user.room.controller.response.RoomListResDto;
import gg.party.api.user.room.service.RoomService;
Expand Down Expand Up @@ -79,4 +81,14 @@ public ResponseEntity<RoomDetailResDto> roomDetailInfo(@Parameter(hidden = true)
RoomDetailResDto roomDetailResDto = roomService.findOrderRoomDetail(user.getId(), roomId);
return ResponseEntity.status(HttpStatus.OK).body(roomDetailResDto);
}

/**
* 참여한 방을 나가기 한다
* @return 나간 사람의 닉네임
*/
@PatchMapping("/{room_id}")
public ResponseEntity<LeaveRoomResDto> leaveRoom(@PathVariable("room_id") Long roomId,
@Parameter(hidden = true) @Login UserDto user) {
return ResponseEntity.status(HttpStatus.OK).body(roomService.modifyOrderLeaveRoom(roomId, user));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package gg.party.api.user.room.controller.response;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public class LeaveRoomResDto {
private String nickname;
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import gg.data.user.User;
import gg.party.api.user.room.controller.request.RoomCreateReqDto;
import gg.party.api.user.room.controller.response.CommentResDto;
import gg.party.api.user.room.controller.response.LeaveRoomResDto;
import gg.party.api.user.room.controller.response.RoomDetailResDto;
import gg.party.api.user.room.controller.response.RoomListResDto;
import gg.party.api.user.room.controller.response.RoomResDto;
Expand All @@ -30,8 +31,11 @@
import gg.repo.party.RoomRepository;
import gg.repo.party.UserRoomRepository;
import gg.repo.user.UserRepository;
import gg.utils.exception.ErrorCode;
import gg.utils.exception.party.CategoryNotFoundException;
import gg.utils.exception.party.RoomNotFoundException;
import gg.utils.exception.party.RoomNotOpenException;
import gg.utils.exception.party.RoomNotParticipantException;
import gg.utils.exception.party.RoomReportedException;
import gg.utils.exception.user.UserNotFoundException;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -132,6 +136,52 @@ public RoomListResDto findOrderMyHistoryRoomList(Long userId) {
return new RoomListResDto(roomListResDto);
}

/**
* 유저가 방을 나간다
* 참가자가 방에 참가한 상태일때만 취소해 준다.
* @param roomId
* @param user 참여 유저(사용자 본인)
* @throws RoomNotFoundException 방 없음 || 방 입장자가 아님
* @return
*/
@Transactional
public LeaveRoomResDto modifyOrderLeaveRoom(Long roomId, UserDto user) {
Room targetRoom = roomRepository.findById(roomId)
.orElseThrow(RoomNotFoundException::new);
if (!targetRoom.getStatus().equals(RoomType.OPEN)) {
throw new RoomNotOpenException();
}

UserRoom targetUserRoom = userRoomRepository.findByUserAndRoom(userRepository.findById(user.getId()).get(),
targetRoom).orElseThrow(RoomNotParticipantException::new);

// 모두 나갈 때 방 fail처리
if (targetRoom.getCurrentPeople() == 1) {
targetRoom.updateCurrentPeople(0);
targetRoom.updateStatus(RoomType.FAIL);
targetUserRoom.updateIsExist(false);
roomRepository.save(targetRoom);
userRoomRepository.save(targetUserRoom);
return new LeaveRoomResDto(targetUserRoom.getNickname());
}

// 방장 이권
if (user.getId().equals(targetRoom.getHost().getId())) {
List<User> existUser = userRoomRepository.findByIsExist(roomId);
if (existUser.isEmpty()) {
throw new RoomNotFoundException(ErrorCode.ROOM_NOT_FOUND);
}
targetRoom.updateHost(existUser.get(0));
}

targetRoom.updateCurrentPeople(targetRoom.getCurrentPeople() - 1);
targetUserRoom.updateIsExist(false);
userRoomRepository.save(targetUserRoom);
roomRepository.save(targetRoom);

return new LeaveRoomResDto(targetUserRoom.getNickname());
}

/**
* 방의 상세정보를 조회한다
* @param userId 자신의 id
Expand All @@ -144,7 +194,7 @@ public RoomListResDto findOrderMyHistoryRoomList(Long userId) {
@Transactional
public RoomDetailResDto findOrderRoomDetail(Long userId, Long roomId) {
Room room = roomRepository.findById(roomId)
.orElseThrow(() -> new RoomNotFoundException(roomId + "번 방을 찾을 수 없습니다."));
.orElseThrow(() -> new RoomNotFoundException(ErrorCode.ROOM_NOT_FOUND));
if (room.getStatus() == RoomType.HIDDEN) {
throw new RoomReportedException(roomId + "번방은 신고 상태로 접근이 불가능합니다.");
}
Expand Down
2 changes: 2 additions & 0 deletions gg-repo/src/main/java/gg/repo/party/RoomRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,6 @@

public interface RoomRepository extends JpaRepository<Room, Long> {
List<Room> findByStatus(RoomType status, Sort sort);

Long findById(Long id, Sort sort);
}
4 changes: 4 additions & 0 deletions gg-repo/src/main/java/gg/repo/party/UserRoomRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ public interface UserRoomRepository extends JpaRepository<UserRoom, Long> {

List<UserRoom> findByRoomId(Long roomId);

@Query("SELECT ur.user FROM UserRoom ur WHERE ur.room.id = :roomId AND ur.isExist = true "
+ "ORDER BY ur.modifiedAt ASC")
List<User> findByIsExist(@Param("roomId") Long roomId);

Optional<UserRoom> findByUserAndRoom(User user, Room room);

@Query("SELECT ur.room FROM UserRoom ur WHERE ur.user.id = :userId AND ur.isExist = true "
Expand Down
5 changes: 4 additions & 1 deletion gg-utils/src/main/java/gg/utils/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,11 @@ public enum ErrorCode {
ROOM_NOT_FOUND(404, "PT102", "존재하지 않는 방입니다."),
USER_NOT_IN_ROOM(404, "PT103", "방에 존재하지 않는 유저입니다."),
ROOM_REPORTED_ERROR(404, "PT104", "신고 상태로 접근이 불가능합니다."),
USER_NOT_EXIST(404, "PT105", "방에 유저가 존재하지 않습니다."),
COMMENT_TOO_LONG(400, "PT201", "댓글은 100자 이하로 작성해주세요."),
ROOM_FINISHED(403, "PT501", "마감된 방입니다.");
ROOM_FINISHED(403, "PT501", "마감된 방입니다."),
ROOM_NOT_PARTICIPANT(400, "PT002", "해당 방의 참여자가 아닙니다."),
ROOM_NOT_OPEN(400, "PT003", "해당 방의 참여자가 아닙니다.");
ghyen marked this conversation as resolved.
Show resolved Hide resolved

private final int status;
private final String errCode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
import gg.utils.exception.custom.NotExistException;

public class RoomNotFoundException extends NotExistException {
public RoomNotFoundException(String message) {
super(message, ErrorCode.ROOM_NOT_FOUND);
public RoomNotFoundException() {
super(ErrorCode.ROOM_NOT_FOUND.getMessage(), ErrorCode.ROOM_NOT_FOUND);
}

public RoomNotFoundException(ErrorCode errorCode) {
super(errorCode.getMessage(), errorCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package gg.utils.exception.party;

import gg.utils.exception.ErrorCode;
import gg.utils.exception.custom.NotExistException;

public class RoomNotOpenException extends NotExistException {
public RoomNotOpenException() {
super(ErrorCode.ROOM_NOT_OPEN.getMessage(), ErrorCode.ROOM_NOT_OPEN);
}

public RoomNotOpenException(ErrorCode errorCode) {
super(errorCode.getMessage(), errorCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package gg.utils.exception.party;

import gg.utils.exception.ErrorCode;
import gg.utils.exception.custom.NotExistException;

public class RoomNotParticipantException extends NotExistException {
public RoomNotParticipantException() {
super(ErrorCode.ROOM_NOT_PARTICIPANT.getMessage(), ErrorCode.ROOM_NOT_PARTICIPANT);
}

public RoomNotParticipantException(ErrorCode errorCode) {
super(errorCode.getMessage(), errorCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package gg.utils.exception.party;

import gg.utils.exception.ErrorCode;
import gg.utils.exception.custom.NotExistException;

public class UserNotFoundException extends NotExistException {
public UserNotFoundException() {
super(ErrorCode.USER_NOT_EXIST.getMessage(), ErrorCode.USER_NOT_EXIST);
}

}
2 changes: 1 addition & 1 deletion gg-utils/src/testFixtures/java/gg/utils/TestDataUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import org.springframework.stereotype.Component;

import gg.auth.utils.AuthTokenProvider;
import gg.data.game.Game;
import gg.data.game.PChange;
import gg.data.game.Team;
Expand Down Expand Up @@ -37,7 +38,6 @@
import gg.data.user.type.SnsType;
import gg.pingpong.api.admin.tournament.controller.request.TournamentAdminCreateRequestDto;
import gg.pingpong.api.admin.tournament.controller.request.TournamentAdminUpdateRequestDto;
import gg.auth.utils.AuthTokenProvider;
import gg.pingpong.api.user.tournament.controller.response.TournamentResponseDto;
import gg.pingpong.api.user.user.dto.UserImageDto;
import gg.repo.game.GameRepository;
Expand Down
Loading