Skip to content

Commit 6a9d72a

Browse files
committed
[future_comments] Добавил функцинальность и тест Postman
1 parent 3f90139 commit 6a9d72a

13 files changed

+2159
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package ru.practicum.ewm.controllers;
2+
3+
import lombok.RequiredArgsConstructor;
4+
import org.springframework.http.HttpStatus;
5+
import org.springframework.web.bind.annotation.*;
6+
import ru.practicum.ewm.serices.CommentService;
7+
8+
@RequiredArgsConstructor
9+
@RestController
10+
@RequestMapping(path = "/admin/comments")
11+
public class AdminCommentController {
12+
private final CommentService commentService;
13+
14+
@DeleteMapping("/{commentId}")
15+
@ResponseStatus(HttpStatus.NO_CONTENT)
16+
public void delete(@PathVariable long commentId) {
17+
commentService.deleteComment(commentId);
18+
}
19+
}

main-service/src/main/java/ru/practicum/ewm/controllers/ErrorHandler.java

+11
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.springframework.web.bind.annotation.ResponseStatus;
1010
import org.springframework.web.bind.annotation.RestControllerAdvice;
1111
import ru.practicum.dto.ErrorResponse;
12+
import ru.practicum.ewm.exceptions.ConflictException;
1213
import ru.practicum.ewm.exceptions.IdIsAlreadyInUseException;
1314
import ru.practicum.ewm.exceptions.NotFoundException;
1415
import ru.practicum.ewm.exceptions.NotValidException;
@@ -96,6 +97,16 @@ public ErrorResponse handlerNotValid(final IdIsAlreadyInUseException e) {
9697
e.getMessage());
9798
}
9899

100+
@ExceptionHandler
101+
@ResponseStatus(HttpStatus.CONFLICT)
102+
public ErrorResponse handlerNotValid(final ConflictException e) {
103+
log.debug(e.getMessage(), e);
104+
105+
return new ErrorResponse(
106+
"CONFLICT",
107+
e.getMessage());
108+
}
109+
99110
@ExceptionHandler
100111
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
101112
public ErrorResponse handlerOther(final Exception e) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package ru.practicum.ewm.controllers;
2+
3+
import jakarta.validation.Valid;
4+
import lombok.RequiredArgsConstructor;
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.web.bind.annotation.*;
7+
import ru.practicum.ewm.dto.CommentDto;
8+
import ru.practicum.ewm.serices.CommentService;
9+
10+
import java.util.List;
11+
12+
@RequiredArgsConstructor
13+
@RestController
14+
@RequestMapping(path = "/events/{eventId}/comments")
15+
public class EventCommentsController {
16+
private final CommentService commentService;
17+
18+
@PostMapping
19+
@ResponseStatus(HttpStatus.CREATED)
20+
public CommentDto create(@PathVariable long eventId,
21+
@RequestParam long userId,
22+
@RequestBody @Valid CommentDto commentDto) {
23+
return commentService.createComment(eventId, userId, commentDto);
24+
}
25+
26+
@GetMapping
27+
public List<CommentDto> getAll(@PathVariable long eventId,
28+
@RequestParam(defaultValue = "0") int from,
29+
@RequestParam(defaultValue = "10") int size) {
30+
return commentService.getAll(eventId, from, size);
31+
}
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package ru.practicum.ewm.controllers;
2+
3+
import jakarta.validation.Valid;
4+
import lombok.RequiredArgsConstructor;
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.web.bind.annotation.*;
7+
import ru.practicum.ewm.dto.CommentDto;
8+
import ru.practicum.ewm.serices.CommentService;
9+
10+
import java.util.List;
11+
12+
@RequiredArgsConstructor
13+
@RestController
14+
@RequestMapping(path = "/users/{userId}/comments")
15+
public class UserCommentsController {
16+
private final CommentService commentService;
17+
18+
@DeleteMapping("/{commentId}")
19+
@ResponseStatus(HttpStatus.NO_CONTENT)
20+
public void delete(@PathVariable long userId,
21+
@PathVariable long commentId) {
22+
commentService.deleteComment(commentId, userId);
23+
}
24+
25+
@PatchMapping("/{commentId}")
26+
public CommentDto update(@RequestParam long userId,
27+
@PathVariable long commentId,
28+
@RequestBody @Valid CommentDto commentDto) {
29+
return commentService.updateComment(commentId, userId, commentDto);
30+
}
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package ru.practicum.ewm.dto;
2+
3+
import jakarta.validation.constraints.NotBlank;
4+
import lombok.*;
5+
6+
import java.time.LocalDateTime;
7+
8+
9+
@Builder
10+
public record CommentDto(
11+
Long id,
12+
Long eventId,
13+
Long authorId,
14+
15+
@NotBlank
16+
String text,
17+
LocalDateTime created,
18+
LocalDateTime lastUpdateTime) { }
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package ru.practicum.ewm.entities;
2+
3+
import jakarta.persistence.*;
4+
import lombok.*;
5+
6+
import java.sql.Timestamp;
7+
8+
@Entity
9+
@Table(name = "comments")
10+
@Getter
11+
@Setter
12+
@Builder
13+
@AllArgsConstructor
14+
@NoArgsConstructor
15+
public class CommentEntity {
16+
17+
@Id
18+
@Column(name = "comment_id")
19+
@GeneratedValue(strategy = GenerationType.IDENTITY)
20+
private Long id;
21+
22+
@ManyToOne
23+
@JoinColumn(name = "event_id", nullable = false)
24+
private EventEntity eventEntity;
25+
26+
@ManyToOne
27+
@JoinColumn(name = "author_id", nullable = false)
28+
private UserEntity author;
29+
30+
@Column(name = "text", nullable = false)
31+
private String text;
32+
33+
@Column(name = "created", nullable = false)
34+
private Timestamp created;
35+
36+
@Column(name = "last_update")
37+
private Timestamp lastUpdateTime;
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package ru.practicum.ewm.exceptions;
2+
3+
public class ConflictException extends RuntimeException {
4+
public ConflictException(String message) {
5+
super(message);
6+
}
7+
8+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package ru.practicum.ewm.repository;
2+
3+
import org.springframework.data.domain.Pageable;
4+
import org.springframework.data.jpa.repository.JpaRepository;
5+
import ru.practicum.ewm.entities.CommentEntity;
6+
7+
import java.util.List;
8+
9+
public interface CommentRepository extends JpaRepository<CommentEntity, Long> {
10+
public List<CommentEntity> findByEventEntityId(long eventId, Pageable pageable);
11+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package ru.practicum.ewm.serices;
2+
3+
import lombok.AllArgsConstructor;
4+
import org.springframework.data.domain.PageRequest;
5+
import org.springframework.data.domain.Pageable;
6+
import org.springframework.stereotype.Service;
7+
import org.springframework.transaction.annotation.Transactional;
8+
import ru.practicum.ewm.dto.CommentDto;
9+
import ru.practicum.ewm.exceptions.ConflictException;
10+
import ru.practicum.ewm.exceptions.NotFoundException;
11+
import ru.practicum.ewm.repository.CommentRepository;
12+
import ru.practicum.ewm.repository.EventRepository;
13+
import ru.practicum.ewm.repository.UserRepository;
14+
15+
import java.sql.Timestamp;
16+
import java.time.LocalDateTime;
17+
import java.util.List;
18+
19+
@Service
20+
@AllArgsConstructor
21+
public class CommentService {
22+
private final CommentRepository commentRepository;
23+
private final UserRepository userRepository;
24+
private final EventRepository eventRepository;
25+
26+
@Transactional
27+
public void deleteComment(long commentId) {
28+
if (!commentRepository.existsById(commentId))
29+
throw new NotFoundException("Not found comment", commentId);
30+
31+
commentRepository.deleteById(commentId);
32+
}
33+
34+
@Transactional
35+
public void deleteComment(long commentId, long userId) {
36+
var comment = commentRepository.findById(commentId)
37+
.orElseThrow(() -> new NotFoundException("Not found comment", commentId));
38+
39+
if (comment.getAuthor().getId() != userId)
40+
throw new ConflictException("User is not the author of comment.");
41+
42+
commentRepository.deleteById(commentId);
43+
}
44+
45+
@Transactional
46+
public CommentDto createComment(long eventId, long userId, CommentDto commentDto) {
47+
var userEntity = userRepository.findById(userId)
48+
.orElseThrow(() -> new NotFoundException("Not found user", userId));
49+
50+
var eventEntity = eventRepository.findById(eventId)
51+
.orElseThrow(() -> new NotFoundException("Not found event", eventId));
52+
53+
var commentEntity = Mapper.toCommentEntity(commentDto);
54+
55+
commentEntity.setCreated(Timestamp.valueOf(LocalDateTime.now()));
56+
commentEntity.setAuthor(userEntity);
57+
commentEntity.setEventEntity(eventEntity);
58+
59+
commentRepository.saveAndFlush(commentEntity);
60+
61+
return Mapper.toCommentDto(commentEntity);
62+
}
63+
64+
@Transactional
65+
public CommentDto updateComment(long commentId, long userId, CommentDto commentDto) {
66+
var text = commentDto.text();
67+
68+
if (text == null || text.isBlank())
69+
return commentDto;
70+
71+
var commentEntity = commentRepository.findById(commentId)
72+
.orElseThrow(() -> new NotFoundException("Not found comment", commentId));
73+
74+
if (commentEntity.getAuthor().getId() != userId)
75+
throw new ConflictException("User is not the author of comment.");
76+
77+
commentEntity.setText(text);
78+
commentEntity.setLastUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
79+
80+
commentRepository.saveAndFlush(commentEntity);
81+
82+
return Mapper.toCommentDto(commentEntity);
83+
}
84+
85+
public List<CommentDto> getAll(long eventId, int from, int size) {
86+
var pageable = initPageable(from, size);
87+
88+
var page = commentRepository.findByEventEntityId(eventId, pageable);
89+
90+
return page.stream()
91+
.map(Mapper::toCommentDto)
92+
.toList();
93+
}
94+
95+
public static Pageable initPageable(int from, int size) {
96+
if (from <= 0)
97+
return PageRequest.ofSize(size);
98+
99+
return PageRequest.of(from / size, size);
100+
}
101+
}

main-service/src/main/java/ru/practicum/ewm/serices/Mapper.java

+25
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import ru.practicum.ewm.dto.*;
66
import ru.practicum.ewm.entities.*;
77

8+
import java.sql.Timestamp;
89
import java.time.LocalDateTime;
910
import java.util.Collection;
1011
import java.util.HashSet;
@@ -150,4 +151,28 @@ public static CategoryEntity toNewCategory(CategoryToAddDto categoryDto) {
150151
categoryEntity.setName(categoryDto.getName());
151152
return categoryEntity;
152153
}
154+
155+
public static CommentEntity toCommentEntity(CommentDto commentDto) {
156+
var entity = new CommentEntity();
157+
158+
entity.setText(commentDto.text());
159+
160+
if (commentDto.created() != null)
161+
entity.setCreated(Timestamp.valueOf(commentDto.created()));
162+
if (commentDto.lastUpdateTime() != null)
163+
entity.setLastUpdateTime(Timestamp.valueOf(commentDto.lastUpdateTime()));
164+
165+
return entity;
166+
}
167+
168+
public static CommentDto toCommentDto(CommentEntity commentEntity) {
169+
return CommentDto.builder()
170+
.id(commentEntity.getId())
171+
.text(commentEntity.getText())
172+
.authorId(commentEntity.getAuthor().getId())
173+
.eventId(commentEntity.getEventEntity().getId())
174+
.created(commentEntity.getCreated().toLocalDateTime())
175+
.lastUpdateTime(commentEntity.getLastUpdateTime().toLocalDateTime())
176+
.build();
177+
}
153178
}

main-service/src/main/resources/schema.sql

+12-1
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,15 @@ CREATE TABLE IF NOT EXISTS compilation_of_events (
6363
CONSTRAINT pk_compilation_of_events PRIMARY KEY (comp_id, event_id),
6464
CONSTRAINT fk_comofeve_on_compilation FOREIGN KEY (comp_id) REFERENCES compilations (comp_id),
6565
CONSTRAINT fk_comofeve_on_event FOREIGN KEY (event_id) REFERENCES events (event_id)
66-
);
66+
);
67+
68+
CREATE TABLE comments (
69+
comment_id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
70+
event_id INTEGER NOT NULL,
71+
author_id INTEGER NOT NULL,
72+
text VARCHAR(255) NOT NULL,
73+
created TIMESTAMP NOT NULL,
74+
last_update TIMESTAMP,
75+
CONSTRAINT fk_event FOREIGN KEY (event_id) REFERENCES events(event_id) ON DELETE CASCADE,
76+
CONSTRAINT fk_user FOREIGN KEY (author_id) REFERENCES users(user_id) ON DELETE CASCADE
77+
)

0 commit comments

Comments
 (0)