Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package ru.practicum.explorewithme.main.controller.admin;

import jakarta.validation.constraints.Positive;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import ru.practicum.explorewithme.main.dto.CommentDto;
import ru.practicum.explorewithme.main.service.CommentService;

@RestController
@RequestMapping("/admin/comments")
@RequiredArgsConstructor
@Validated
@Slf4j
public class AdminCommentController {

private final CommentService commentService;

@DeleteMapping("/{commentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteComment(@PathVariable @Positive Long commentId) {
log.info("Admin: Received request to delete comment with Id: {}", commentId);
commentService.deleteCommentByAdmin(commentId);
log.info("Admin: Comment with Id: {} marked as deleted", commentId);
}

@PatchMapping("/{commentId}/restore")
@ResponseStatus(HttpStatus.OK)
public CommentDto restoreComment(@PathVariable @Positive Long commentId) {
log.info("Admin: Received request to restore comment with Id: {}", commentId);
CommentDto restoredComment = commentService.restoreCommentByAdmin(commentId);
log.info("Admin: Comment with Id: {} restored", commentId);
return restoredComment;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ public ResponseEntity<CommentDto> createComment(
@PathVariable @Positive Long userId,
@RequestParam @Positive Long eventId,
@Valid @RequestBody NewCommentDto newCommentDto) {

log.info("Создание нового комментария {} зарегистрированным пользователем c id {} " +
"к событию с id {}", newCommentDto, userId, eventId);

log.info("Создание нового комментария {} зарегистрированным пользователем c id {} к событию с id {}",
newCommentDto, userId, eventId);
return ResponseEntity.status(HttpStatus.CREATED)
.body(commentService.addComment(userId, eventId, newCommentDto));
}
Expand All @@ -43,23 +41,29 @@ public ResponseEntity<CommentDto> updateComment(
@PathVariable @Positive Long userId,
@PathVariable @Positive Long commentId,
@Valid @RequestBody UpdateCommentDto updateCommentDto) {

log.info("Обновление комментария c id {} пользователем c id {}," +
" новый комментарий {}", commentId, userId, updateCommentDto);

return ResponseEntity.status(HttpStatus.OK).body(commentService.updateUserComment(userId, commentId, updateCommentDto));
log.info("Обновление комментария c id {} пользователем c id {}, новый комментарий {}",
commentId, userId, updateCommentDto);
return ResponseEntity.status(HttpStatus.OK)
.body(commentService.updateUserComment(userId, commentId, updateCommentDto));
}

@GetMapping
public ResponseEntity<List<CommentDto>> getUserComments(
@PathVariable @Positive Long userId,
@RequestParam(defaultValue = "0") @PositiveOrZero int from,
@RequestParam(defaultValue = "10") @Positive int size) {

List<CommentDto> result = commentService.getUserComments(userId, from, size);

log.info("Получение списка комментариев {} пользователя c id {}", result, userId);

return ResponseEntity.status(HttpStatus.OK).body(result);
}

@DeleteMapping("/{commentId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteComment(
@PathVariable @Positive Long userId,
@PathVariable @Positive Long commentId) {
log.info("User id={}: Received request to delete comment with Id: {}", userId, commentId);
commentService.deleteUserComment(userId, commentId);
log.info("User id={}: Comment with Id: {} marked as deleted", userId, commentId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,10 @@ public interface CommentService {
CommentDto addComment(Long userId, Long eventId, NewCommentDto newCommentDto);

CommentDto updateUserComment(Long userId, Long commentId, UpdateCommentDto updateCommentDto);

void deleteCommentByAdmin(Long commentId);

void deleteUserComment(Long userId, Long commentId);

CommentDto restoreCommentByAdmin(Long commentId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
import ru.practicum.explorewithme.main.service.params.PublicCommentParameters;

import java.time.LocalDateTime;
import java.util.Optional;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
Expand All @@ -37,7 +37,6 @@ public class CommentServiceImpl implements CommentService {
@Override
@Transactional(readOnly = true)
public List<CommentDto> getCommentsForEvent(Long eventId, PublicCommentParameters parameters) {

Event event = eventRepository.findByIdAndState(eventId, EventState.PUBLISHED)
.orElseThrow(() -> new EntityNotFoundException("Published event", "Id", eventId));

Expand All @@ -56,7 +55,6 @@ public List<CommentDto> getCommentsForEvent(Long eventId, PublicCommentParameter
@Override
@Transactional(readOnly = true)
public List<CommentDto> getUserComments(Long userId, int from, int size) {

if (!userRepository.existsById(userId)) {
throw new EntityNotFoundException("Пользователь с id " + userId + " не найден");
}
Expand All @@ -72,7 +70,6 @@ public List<CommentDto> getUserComments(Long userId, int from, int size) {
@Override
@Transactional
public CommentDto addComment(Long userId, Long eventId, NewCommentDto newCommentDto) {

User author = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("Пользователь с id " + userId + " не найден"));

Expand All @@ -88,7 +85,6 @@ public CommentDto addComment(Long userId, Long eventId, NewCommentDto newComment
}

Comment comment = commentMapper.toComment(newCommentDto);

comment.setAuthor(author);
comment.setEvent(event);

Expand All @@ -98,17 +94,16 @@ public CommentDto addComment(Long userId, Long eventId, NewCommentDto newComment
@Override
@Transactional
public CommentDto updateUserComment(Long userId, Long commentId, UpdateCommentDto updateCommentDto) {

Optional<Comment> comment = commentRepository.findById(commentId);

if (comment.isEmpty()) {
throw new EntityNotFoundException("Комментарий с id" + commentId + " не найден");
throw new EntityNotFoundException("Комментарий с id " + commentId + " не найден");
}

Comment existedComment = comment.get();

if (!existedComment.getAuthor().getId().equals(userId)) {
throw new EntityNotFoundException("Искомый комментарий с id " + commentId + " пользователя с id " + userId + "не найден");
throw new EntityNotFoundException("Искомый комментарий с id " + commentId + " пользователя с id " + userId + " не найден");
}

if (existedComment.isDeleted()) {
Expand All @@ -124,4 +119,41 @@ public CommentDto updateUserComment(Long userId, Long commentId, UpdateCommentDt

return commentMapper.toDto(commentRepository.saveAndFlush(existedComment));
}

@Override
@Transactional
public void deleteCommentByAdmin(Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new EntityNotFoundException(String.format("Comment with id=%d not found", commentId)));
if (!comment.isDeleted()) {
comment.setDeleted(true);
commentRepository.save(comment);
}
}

@Override
@Transactional
public void deleteUserComment(Long userId, Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new EntityNotFoundException(String.format("Comment with id=%d not found", commentId)));
if (!comment.getAuthor().getId().equals(userId)) {
throw new EntityNotFoundException(String.format("Comment with id=%d not found for user with id=%d", commentId, userId));
}
if (!comment.isDeleted()) {
comment.setDeleted(true);
commentRepository.save(comment);
}
}

@Override
@Transactional
public CommentDto restoreCommentByAdmin(Long commentId) {
Comment comment = commentRepository.findById(commentId)
.orElseThrow(() -> new EntityNotFoundException(String.format("Comment with id=%d not found", commentId)));
if (comment.isDeleted()) {
comment.setDeleted(false);
commentRepository.save(comment);
}
return commentMapper.toDto(comment);
}
}