Skip to content

Commit

Permalink
Merge pull request #73 from KNU-HAEDAL-Website/feat-delete-post-issue-69
Browse files Browse the repository at this point in the history
Feat: 게시글 삭제 API
  • Loading branch information
tfer2442 authored Aug 10, 2024
2 parents 38798d2 + e6f630c commit 0185a32
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
.requestMatchers("/admin/**").hasAnyRole("WEB_MASTER", "ADMIN")
.requestMatchers("/boards/generate-presigned-url").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER")
.requestMatchers(HttpMethod.GET, "/posts/generate-presigned-url").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER", "MEMBER")
.requestMatchers(HttpMethod.POST, "/notice/posts", "/event/posts").hasAnyRole("WEB_MASTER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/posts").hasAnyRole("WEB_MASTER", "ADMIN")
.requestMatchers(HttpMethod.DELETE, "/posts/{postId}").hasAnyRole("WEB_MASTER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/activities/{activityId}/boards").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER")
.requestMatchers(HttpMethod.POST, "/boards/{boardId}/posts").authenticated()
.requestMatchers(HttpMethod.DELETE, "/boards/{boardId}/posts/{postId}").authenticated()
.requestMatchers(HttpMethod.DELETE, "/activities/{activityId}/boards/{boardId}").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER")
.requestMatchers(HttpMethod.PATCH, "/activities/{activityId}/boards/{boardId}/**").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER")
.requestMatchers("/private/users").authenticated()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public enum ErrorCode implements ResponseCode{
EXIST_ACTIVITY(HttpStatus.CONFLICT, "016", "해당 학기에 활동이 존재하는 경우 삭제할 수 없습니다."),
EXIST_BOARD(HttpStatus.CONFLICT, "017", "해당 활동에 게시판이 존재하는 경우 삭제할 수 없습니다."),
NOT_FOUND_BOARD_ID(HttpStatus.NOT_FOUND, "018", "해당 게시판을 찾을 수 없습니다."),
FORBIDDEN_UPDATE(HttpStatus.FORBIDDEN, "019", "삭제 권한이 없습니다."),
FORBIDDEN_UPDATE(HttpStatus.FORBIDDEN, "019", "수정, 삭제 권한이 없습니다."),
NOT_FOUND_POST_TYPE(HttpStatus.NOT_FOUND, "020", "해당 게시글 타입이 존재하지 않습니다."),
EXIST_POST(HttpStatus.CONFLICT, "021", "해당 게시판에 게시글이 존재하는 경우 삭제할 수 없습니다."),
NOT_FOUND_POST_ID(HttpStatus.NOT_FOUND, "022", "해당 게시글을 찾을 수 없습니다.");
Expand Down
28 changes: 16 additions & 12 deletions src/main/java/com/haedal/haedalweb/controller/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.haedal.haedalweb.dto.response.common.SuccessResponse;
import com.haedal.haedalweb.service.PostService;
import com.haedal.haedalweb.service.S3Service;
import com.haedal.haedalweb.swagger.ApiErrorCodeExample;
import com.haedal.haedalweb.swagger.ApiErrorCodeExamples;
import com.haedal.haedalweb.swagger.ApiSuccessCodeExample;
import com.haedal.haedalweb.util.ResponseUtil;
Expand Down Expand Up @@ -52,27 +51,19 @@ public ResponseEntity<SuccessResponse> addPost(@PathVariable Long boardId, @Requ
return ResponseUtil.buildSuccessResponseEntity(SuccessCode.ADD_POST_SUCCESS);
}

@Operation(summary = "공지사항 게시글 생성")
@Operation(summary = "공지사항, 이벤트 게시글 생성")
@ApiSuccessCodeExample(SuccessCode.ADD_POST_SUCCESS)
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_USER_ID, ErrorCode.NOT_FOUND_BOARD_ID, ErrorCode.NOT_FOUND_POST_TYPE})
@PostMapping("/notice/posts")
@PostMapping("/posts")
public ResponseEntity<SuccessResponse> addNoticePost(@RequestBody @Valid CreatePostDTO createPostDTO) {
postService.createPost(createPostDTO);
return ResponseUtil.buildSuccessResponseEntity(SuccessCode.ADD_POST_SUCCESS);
}

@Operation(summary = "이벤트 게시글 생성")
@ApiSuccessCodeExample(SuccessCode.ADD_POST_SUCCESS)
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_USER_ID, ErrorCode.NOT_FOUND_BOARD_ID, ErrorCode.NOT_FOUND_POST_TYPE})
@PostMapping("/event/posts")
public ResponseEntity<SuccessResponse> addEventPost(@RequestBody @Valid CreatePostDTO createPostDTO) {
postService.createPost(createPostDTO);
return ResponseUtil.buildSuccessResponseEntity(SuccessCode.ADD_POST_SUCCESS);
}

@Operation(summary = "활동 게시글 삭제")
@ApiSuccessCodeExample(SuccessCode.DELETE_POST_SUCCESS)
@ApiErrorCodeExamples({})
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_POST_ID, ErrorCode.NOT_FOUND_BOARD_ID, ErrorCode.FORBIDDEN_UPDATE})
@Parameters({
@Parameter(name = "boardId", description = "게시글 삭제할 활동 게시판 ID"),
@Parameter(name = "postId", description = "해당 게시글 ID")
Expand All @@ -83,4 +74,17 @@ public ResponseEntity<SuccessResponse> deletePost(@PathVariable Long boardId, @P

return ResponseUtil.buildSuccessResponseEntity(SuccessCode.DELETE_POST_SUCCESS);
}

@Operation(summary = "공지사항, 이벤트 게시글 삭제")
@ApiSuccessCodeExample(SuccessCode.DELETE_POST_SUCCESS)
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_POST_ID, ErrorCode.NOT_FOUND_POST_TYPE})
@Parameters({
@Parameter(name = "postId", description = "해당 게시글 ID")
})
@DeleteMapping("/posts/{postId}")
public ResponseEntity<SuccessResponse> deleteNoticePost(@PathVariable Long postId) {
postService.deletePost(postId);

return ResponseUtil.buildSuccessResponseEntity(SuccessCode.DELETE_POST_SUCCESS);
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/haedal/haedalweb/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public class Post {
@JoinColumn(name = "user_id")
private User user;

@OneToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "board_id")
private Board board;
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,4 @@ public Activity findActivityById(Long activityId) {
return activityRepository.findById(activityId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ACTIVITY_ID));
}

public boolean isSemesterPresent(Long semesterId) {
return activityRepository.existsBySemesterId(semesterId);
}
}
25 changes: 10 additions & 15 deletions src/main/java/com/haedal/haedalweb/service/BoardService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
import com.haedal.haedalweb.dto.response.BoardDTO;
import com.haedal.haedalweb.dto.response.ParticipantDTO;
import com.haedal.haedalweb.exception.BusinessException;
import com.haedal.haedalweb.repository.ActivityRepository;
import com.haedal.haedalweb.repository.BoardRepository;
import com.haedal.haedalweb.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
Expand All @@ -25,24 +27,16 @@
@RequiredArgsConstructor
@Service
public class BoardService {
private final BoardRepository boardRepository;
private final ActivityService activityService;
private final PostService postService;
private final UserService userService;
private final BoardRepository boardRepository;
private final ActivityRepository activityRepository;
private final PostRepository postRepository;
private final S3Service s3Service;

public boolean isActivityPresent(Long activityId) {
return boardRepository.existsByActivityId(activityId);
}

public Board findBoardById(Long boardId) {
return boardRepository.findById(boardId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_BOARD_ID));
}

@Transactional
public void createBoard(Long activityId, CreateBoardDTO createBoardDTO) {
Activity activity = activityService.findActivityById(activityId);
Activity activity = activityRepository.findById(activityId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ACTIVITY_ID));
User creator = userService.getLoggedInUser();
List<String> participantIds = new ArrayList<>(createBoardDTO.getParticipants());
List<User> participants = userService.findUserByIds(participantIds);
Expand All @@ -64,7 +58,8 @@ public void createBoard(Long activityId, CreateBoardDTO createBoardDTO) {

@Transactional(readOnly = true)
public Page<BoardDTO> getBoardDTOs(Long activityId, Pageable pageable) {
Activity activity = activityService.findActivityById(activityId);
Activity activity = activityRepository.findById(activityId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ACTIVITY_ID));
Page<Board> boardPage = boardRepository.findBoardsByActivity(activity, pageable);

return boardPage.map(board -> convertToBoardDTO(board, activityId));
Expand Down Expand Up @@ -186,7 +181,7 @@ private void validateAuthorityOfBoardManagement(User loggedInUser, User creator)
}

private void validateDeleteBoardRequest(Long boardId) {
if (postService.isBoardPresent(boardId)) {
if (postRepository.existsByBoardId(boardId)) {
throw new BusinessException(ErrorCode.EXIST_POST);
}
}
Expand Down
49 changes: 38 additions & 11 deletions src/main/java/com/haedal/haedalweb/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.haedal.haedalweb.domain.Board;
import com.haedal.haedalweb.domain.Post;
import com.haedal.haedalweb.domain.PostType;
import com.haedal.haedalweb.domain.Role;
import com.haedal.haedalweb.domain.User;
import com.haedal.haedalweb.dto.request.CreatePostDTO;
import com.haedal.haedalweb.exception.BusinessException;
Expand All @@ -22,14 +23,10 @@ public class PostService {
private final PostRepository postRepository;
private final BoardRepository boardRepository;
private final UserService userService;

public boolean isBoardPresent(Long boardId) {
return postRepository.existsByBoardId(boardId);
}
private final S3Service s3Service;

@Transactional
public void createPost(Long boardId, CreatePostDTO createPostDTO) { // createPost 리팩토링 해야함.
// Board board = boardService.findBoardById(boardId);
public void createPost(Long boardId, CreatePostDTO createPostDTO) { // createPost 리팩토링 해야함. // 게시판 참여자만 게시글을 쓸 수 있게 해야하나?
Board board = boardRepository.findById(boardId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_BOARD_ID));
PostType postType;
Expand All @@ -54,7 +51,7 @@ public void createPost(Long boardId, CreatePostDTO createPostDTO) { // createPos
.activityDate(activityDate)
.createDate(createDate)
.user(creator)
.board(board) // 만약 boardId를 안 받았으면, 공지사항 or 이베트 게시글임
.board(board)
.build();

postRepository.save(post);
Expand Down Expand Up @@ -94,15 +91,45 @@ public void createPost(CreatePostDTO createPostDTO) {
public void deletePost(Long boardId, Long postId) { // 활동 게시글 삭제 method
Post post = postRepository.findByBoardIdAndId(boardId, postId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_POST_ID));
//Board board = boardService.findBoardById(boardId);
Board board = boardRepository.findById(boardId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_BOARD_ID));

User loggedInUser = userService.getLoggedInUser();
User postCreator = post.getUser();
// User boardCreator = board.getUser();
User boardCreator = board.getUser();

validateAuthorityOfPostManagement(loggedInUser, postCreator, boardCreator);

s3Service.deleteObject(post.getImageUrl());
postRepository.delete(post);
}

@Transactional
public void deletePost(Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_POST_ID));

//validateAuthorityOfPostManagement
try {
if (post.getPostType() != PostType.NOTICE && post.getPostType() != PostType.EVENT)
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
throw new BusinessException(ErrorCode.NOT_FOUND_POST_TYPE);
}

s3Service.deleteObject(post.getImageUrl());
postRepository.delete(post);
}

// 게시판 생성한 것은 팀장이므로, 게시판 생성자와 WEB_MASTER, 해구르르, 게시글 작성자만 삭제 가능
private void validateAuthorityOfPostManagement(User loggedInUser, User postCreator, User boardCreator) {
String loggedInUserId = loggedInUser.getId();
String postCreatorId = postCreator.getId();
String boardCreatorId = boardCreator.getId();

if (!postCreatorId.equals(loggedInUserId)
&& !boardCreatorId.equals(loggedInUserId)
&& loggedInUser.getRole() != Role.ROLE_ADMIN
&& loggedInUser.getRole() != Role.ROLE_WEB_MASTER) {
throw new BusinessException(ErrorCode.FORBIDDEN_UPDATE);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@

import com.haedal.haedalweb.constants.ErrorCode;
import com.haedal.haedalweb.domain.Activity;
import com.haedal.haedalweb.domain.Board;
import com.haedal.haedalweb.domain.Semester;
import com.haedal.haedalweb.dto.request.CreateActivityDTO;
import com.haedal.haedalweb.exception.BusinessException;
import com.haedal.haedalweb.repository.ActivityRepository;
import com.haedal.haedalweb.repository.BoardRepository;
import com.haedal.haedalweb.repository.SemesterRepository;
import com.haedal.haedalweb.service.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -19,7 +17,7 @@
public class AdminActivityService {
private final SemesterRepository semesterRepository;
private final ActivityRepository activityRepository;
private final BoardService boardService;
private final BoardRepository boardRepository;

@Transactional
public void createActivity(Long semesterId, CreateActivityDTO createActivityDTO) {
Expand All @@ -44,7 +42,7 @@ public void deleteActivity(Long activityId) {
}

private void validateDeleteActivityRequest(Long activityId) {
if (boardService.isActivityPresent(activityId)) {
if (boardRepository.existsByActivityId(activityId)) {
throw new BusinessException(ErrorCode.EXIST_BOARD);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import com.haedal.haedalweb.domain.Semester;
import com.haedal.haedalweb.dto.request.CreateSemesterDTO;
import com.haedal.haedalweb.exception.BusinessException;
import com.haedal.haedalweb.repository.ActivityRepository;
import com.haedal.haedalweb.repository.SemesterRepository;
import com.haedal.haedalweb.service.ActivityService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -14,7 +14,7 @@
@RequiredArgsConstructor
public class AdminSemesterService {
private final SemesterRepository semesterRepository;
private final ActivityService activityService;
private final ActivityRepository activityRepository;

@Transactional
public void createSemester(CreateSemesterDTO createSemesterDTO) {
Expand All @@ -35,7 +35,6 @@ public void deleteSemester(Long semesterId) {

validateDeleteSemesterRequest(semesterId);

// 학기 안에 활동이 존재할 때, 에러 코드 반환하는 로직 작성
semesterRepository.delete(semester);
}

Expand All @@ -46,7 +45,7 @@ private void validateAddSemesterRequest(CreateSemesterDTO createSemesterDTO) {
}

private void validateDeleteSemesterRequest(Long semesterId) {
if (activityService.isSemesterPresent(semesterId)) {
if (activityRepository.existsBySemesterId(semesterId)) {
throw new BusinessException(ErrorCode.EXIST_ACTIVITY);
}
}
Expand Down

0 comments on commit 0185a32

Please sign in to comment.