diff --git a/README.md b/README.md index 18a246e..dca63f8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,4 @@ # java-explore-with-me Template repository for ExploreWithMe project. + +https://github.com/aigunov/java-explore-with-me/pull/5 \ No newline at end of file diff --git a/main-service/Dockerfile b/main-service/Dockerfile index 8d19b54..61d098d 100644 --- a/main-service/Dockerfile +++ b/main-service/Dockerfile @@ -1,4 +1,4 @@ -FROM amazoncorretto:21 +FROM openjdk:21 COPY target/*.jar app.jar ENTRYPOINT ["java","-jar","/app.jar"] EXPOSE 8080 \ No newline at end of file diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/ExceptionController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/ExceptionController.java index 5a21a4e..df5dcfa 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/controller/ExceptionController.java +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/ExceptionController.java @@ -9,9 +9,10 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.HandlerMethodValidationException; -import ru.practicum.mainservice.data.model.EntityCreationDataIncorrect; -import ru.practicum.mainservice.data.model.EntityUpdateConflict; -import ru.practicum.mainservice.data.model.NoValidParameter; +import ru.practicum.mainservice.data.model.exceptions.CommentActionException; +import ru.practicum.mainservice.data.model.exceptions.EntityCreationDataIncorrect; +import ru.practicum.mainservice.data.model.exceptions.EntityUpdateConflict; +import ru.practicum.mainservice.data.model.exceptions.NoValidParameter; import java.util.List; import java.util.Map; @@ -58,7 +59,7 @@ public Map handleMissingURLParameter(MissingServletRequestParame @ExceptionHandler(NoSuchElementException.class) @ResponseStatus(HttpStatus.NOT_FOUND) - public Map handleNotFoundEntity(RuntimeException e) { + public Map handleNotFoundEntity(NoSuchElementException e) { log.error("Получен статус 404 NOT_FOUND {}", e.getMessage()); return Map.of("Ошибка: ", e.getMessage()); } @@ -77,6 +78,13 @@ public Map handleConflict(final EntityCreationDataIncorrect e) { return Map.of("Ошибка", e.getMessage()); } + @ExceptionHandler + @ResponseStatus(HttpStatus.CONFLICT) + public Map handleCommentException(final CommentActionException e) { + log.error("Получен Статус 409 CONFLIC {}", e.getMessage()); + return Map.of("Ошибка", e.getMessage()); + } + @ExceptionHandler(DataIntegrityViolationException.class) @ResponseStatus(HttpStatus.CONFLICT) public Map handleConstraintViolationException(final DataIntegrityViolationException e) { diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCommentController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCommentController.java new file mode 100644 index 0000000..c8725b0 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCommentController.java @@ -0,0 +1,38 @@ +package ru.practicum.mainservice.controller.adminapi; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.PositiveOrZero; +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.mainservice.data.dto.comment.CommentDto; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateRequest; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateResult; +import ru.practicum.mainservice.service.interfaces.CommentService; + +@RestController +@RequestMapping("/admin/comments") +@RequiredArgsConstructor +@Slf4j +@Validated +public class AdminCommentController { + private final CommentService commentService; + + @GetMapping("/{commentId}") + public CommentDto getCommentById(@PositiveOrZero @PathVariable Long commentId) { + CommentDto commentById = commentService.findCommentById(commentId); + log.info("GET /admin/comments/{commentId} commentId = {} result = {}", commentById, commentById); + return commentById; + } + + @PatchMapping("/event/{eventId}") + @ResponseStatus(HttpStatus.CREATED) + public CommentStatusUpdateResult decisionComments(@PositiveOrZero @PathVariable Long eventId, + @Valid @RequestBody CommentStatusUpdateRequest commentStatusUpdateRequest) { + CommentStatusUpdateResult decision = commentService.decisionComments(eventId, commentStatusUpdateRequest); + log.info("PATCH /admin/comments/event/{eventId}eventId = {} patchedComment = {}", eventId, decision); + return decision; + } +} \ No newline at end of file diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCompilationsController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCompilationsController.java index 26d940e..b968122 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCompilationsController.java +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminCompilationsController.java @@ -5,8 +5,8 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import ru.practicum.mainservice.data.dto.NewCompilationDto; -import ru.practicum.mainservice.data.dto.UpdateCompilationRequest; +import ru.practicum.mainservice.data.dto.compilation.NewCompilationDto; +import ru.practicum.mainservice.data.dto.compilation.UpdateCompilationRequest; import ru.practicum.mainservice.data.model.Compilations; import ru.practicum.mainservice.service.interfaces.CompilationsService; diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminEventsController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminEventsController.java index 9b1dc97..9c34bac 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminEventsController.java +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminEventsController.java @@ -8,10 +8,10 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import ru.practicum.mainservice.data.dto.EventResponseDto; -import ru.practicum.mainservice.data.dto.UpdateEventAdminRequest; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.UpdateEventAdminRequest; import ru.practicum.mainservice.data.model.RequestParameters; -import ru.practicum.mainservice.data.model.States; +import ru.practicum.mainservice.data.model.enums.States; import ru.practicum.mainservice.service.interfaces.EventService; import ru.practicum.mainservice.stat.StatAdapter; diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminUserController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminUserController.java index c8d4938..00a975c 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminUserController.java +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/adminapi/AdminUserController.java @@ -8,7 +8,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import ru.practicum.mainservice.data.dto.NewUserRequest; +import ru.practicum.mainservice.data.dto.user.NewUserRequest; import ru.practicum.mainservice.service.interfaces.UserService; import ru.practicum.statsdto.dto.UserDto; diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateCommentsController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateCommentsController.java new file mode 100644 index 0000000..6971b99 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateCommentsController.java @@ -0,0 +1,64 @@ +package ru.practicum.mainservice.controller.privateapi; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.PositiveOrZero; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import ru.practicum.mainservice.data.dto.comment.CommentDto; +import ru.practicum.mainservice.service.interfaces.CommentService; + +import java.util.List; + +@Slf4j +@RestController +@RequestMapping("/users/{userId}/event/{eventId}/comments") +@RequiredArgsConstructor +public class PrivateCommentsController { + private final CommentService commentService; + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public CommentDto createComment(@PositiveOrZero @PathVariable Long userId, + @PositiveOrZero @PathVariable Long eventId, + @Valid @RequestBody CommentDto comment) { + CommentDto createdComment = commentService.createComment(userId, eventId, comment); + log.info("POST /users/{userId}/event/{eventId}/comments userId = {} eventId = {} createdComment = {}", userId, + eventId, createdComment); + return createdComment; + } + + @DeleteMapping("/{commentId}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void deleteComment(@PositiveOrZero @PathVariable Long userId, + @PositiveOrZero @PathVariable Long eventId, + @PositiveOrZero @PathVariable Long commentId) { + log.info("DELETE /users/{userId}/event/{eventId}/comments/{commentId} userId = {}," + + " eventId = {}, commentId = {}", userId, eventId, commentId); + commentService.deleteComment(userId, eventId, commentId); + } + + @GetMapping + public List getCommentsByEventId(@PositiveOrZero @PathVariable Long userId, + @PositiveOrZero @PathVariable Long eventId, + @PositiveOrZero @RequestParam(defaultValue = "0") Integer from, + @PositiveOrZero @RequestParam(defaultValue = "0") Integer size) { + List commentsByEventId = commentService.getCommentsByEventId(userId, eventId, PageRequest.of(from / size, size)); + log.info("GET /users/{userId}/event/{eventId}/comments userId = {} eventId = {} result = {}", userId, + eventId, commentsByEventId); + return commentsByEventId; + } + + @GetMapping("/{commentId}") + public CommentDto findComment(@PositiveOrZero @PathVariable Long userId, + @PositiveOrZero @PathVariable Long eventId, + @PositiveOrZero @PathVariable Long commentId) { + log.info("GET /users/{userId}/event/{eventId}/comments/{commentId}" + + " userId = {} eventId = {} commentId = {}", userId, eventId, commentId); + CommentDto commentByIdAndEventId = commentService.getCommentByIdAndEventId(userId, eventId, commentId); + log.info("Найденный комментарий {}", commentByIdAndEventId); + return commentByIdAndEventId; + } +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateEventsController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateEventsController.java index d6c7217..c52dcd5 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateEventsController.java +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/privateapi/PrivateEventsController.java @@ -7,7 +7,8 @@ import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import ru.practicum.mainservice.data.dto.*; +import ru.practicum.mainservice.data.dto.RequestDto; +import ru.practicum.mainservice.data.dto.event.*; import ru.practicum.mainservice.service.interfaces.EventService; import ru.practicum.mainservice.service.interfaces.RequestService; diff --git a/main-service/src/main/java/ru/practicum/mainservice/controller/publicapi/PublicEventsController.java b/main-service/src/main/java/ru/practicum/mainservice/controller/publicapi/PublicEventsController.java index db708d8..34b8033 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/controller/publicapi/PublicEventsController.java +++ b/main-service/src/main/java/ru/practicum/mainservice/controller/publicapi/PublicEventsController.java @@ -8,9 +8,9 @@ import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import ru.practicum.mainservice.data.dto.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; import ru.practicum.mainservice.data.model.RequestParameters; -import ru.practicum.mainservice.data.model.Sort; +import ru.practicum.mainservice.data.model.enums.Sort; import ru.practicum.mainservice.service.interfaces.EventService; import ru.practicum.mainservice.stat.StatAdapter; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/RequestDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/RequestDto.java index 12a756a..a6a6f0b 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/RequestDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/RequestDto.java @@ -2,7 +2,7 @@ import com.fasterxml.jackson.annotation.JsonFormat; import lombok.*; -import ru.practicum.mainservice.data.model.Status; +import ru.practicum.mainservice.data.model.enums.Status; import java.time.LocalDateTime; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentDto.java new file mode 100644 index 0000000..7879870 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentDto.java @@ -0,0 +1,26 @@ +package ru.practicum.mainservice.data.dto.comment; + +import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.validation.constraints.NotBlank; +import lombok.*; +import ru.practicum.mainservice.data.model.enums.CommentStatus; +import ru.practicum.statsdto.dto.UserDto; + +import java.time.LocalDateTime; + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder(toBuilder = true) +public class CommentDto { + private Long id; + private Long eventId; + private String comment; + private UserDto user; + @NotBlank + private String description; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime publishedOn; + private CommentStatus status; +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentStatusUpdateRequest.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentStatusUpdateRequest.java new file mode 100644 index 0000000..28b48c1 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentStatusUpdateRequest.java @@ -0,0 +1,26 @@ +package ru.practicum.mainservice.data.dto.comment; + +import com.fasterxml.jackson.annotation.JsonInclude; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Set; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CommentStatusUpdateRequest { + @NotEmpty + private Set ids; + @NotNull + private Status status; + + public enum Status { + APPROVE, + REJECT + } +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentStatusUpdateResult.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentStatusUpdateResult.java new file mode 100644 index 0000000..9f3e1e9 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/comment/CommentStatusUpdateResult.java @@ -0,0 +1,12 @@ +package ru.practicum.mainservice.data.dto.comment; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; + +@Data +@Builder(toBuilder = true) +public class CommentStatusUpdateResult { + private List resolvedComments; +} \ No newline at end of file diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/CompilationDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/CompilationDto.java similarity index 72% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/CompilationDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/CompilationDto.java index 2ee1947..e633ba6 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/CompilationDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/CompilationDto.java @@ -1,8 +1,9 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.compilation; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; +import ru.practicum.mainservice.data.dto.event.EventShortDto; import java.util.Set; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/NewCompilationDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/NewCompilationDto.java similarity index 91% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/NewCompilationDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/NewCompilationDto.java index 6188117..38e7226 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/NewCompilationDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/NewCompilationDto.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.compilation; import com.fasterxml.jackson.annotation.JsonInclude; import jakarta.validation.constraints.NotBlank; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateCompilationRequest.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/UpdateCompilationRequest.java similarity index 88% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateCompilationRequest.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/UpdateCompilationRequest.java index d2c4dde..92a8470 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateCompilationRequest.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/compilation/UpdateCompilationRequest.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.compilation; import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatus.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatus.java similarity index 55% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatus.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatus.java index 79fca7d..9d42d20 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatus.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatus.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; public enum EventRequestStatus { CONFIRMED, REJECTED; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatusUpdateRequest.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatusUpdateRequest.java similarity index 90% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatusUpdateRequest.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatusUpdateRequest.java index 9cb202d..725003b 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatusUpdateRequest.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatusUpdateRequest.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatusUpdateResult.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatusUpdateResult.java similarity index 70% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatusUpdateResult.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatusUpdateResult.java index 3a2242b..1919033 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventRequestStatusUpdateResult.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventRequestStatusUpdateResult.java @@ -1,7 +1,8 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import lombok.Builder; import lombok.Data; +import ru.practicum.mainservice.data.dto.RequestDto; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventResponseDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventResponseDto.java similarity index 90% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/EventResponseDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventResponseDto.java index 9949a6d..b9bac22 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventResponseDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventResponseDto.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import com.fasterxml.jackson.annotation.JsonFormat; @@ -6,7 +6,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import ru.practicum.mainservice.data.model.States; +import ru.practicum.mainservice.data.model.enums.States; import ru.practicum.statsdto.dto.CategoryDto; import ru.practicum.statsdto.dto.UserDto; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventShortDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventShortDto.java similarity index 83% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/EventShortDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventShortDto.java index de86451..7baa61b 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/EventShortDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/EventShortDto.java @@ -1,11 +1,12 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import ru.practicum.mainservice.data.model.States; +import ru.practicum.mainservice.data.dto.user.UserShortDto; +import ru.practicum.mainservice.data.model.enums.States; import ru.practicum.statsdto.dto.CategoryDto; import java.time.LocalDateTime; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/LocationDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/LocationDto.java similarity index 90% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/LocationDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/LocationDto.java index 2efa108..07089dd 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/LocationDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/LocationDto.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/NewEventDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/NewEventDto.java similarity index 91% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/NewEventDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/NewEventDto.java index 84dd967..0ad002c 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/NewEventDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/NewEventDto.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import com.fasterxml.jackson.annotation.JsonFormat; import jakarta.validation.Valid; @@ -7,7 +7,7 @@ import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import ru.practicum.mainservice.data.model.NoValidParameter; +import ru.practicum.mainservice.data.model.exceptions.NoValidParameter; import java.time.LocalDateTime; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEvent.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEvent.java similarity index 95% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEvent.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEvent.java index ed8d506..b77183b 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEvent.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEvent.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import com.fasterxml.jackson.annotation.JsonFormat; import jakarta.validation.Valid; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEventAdminRequest.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEventAdminRequest.java similarity index 88% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEventAdminRequest.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEventAdminRequest.java index 0a537ce..8194c5d 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEventAdminRequest.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEventAdminRequest.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEventUserRequest.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEventUserRequest.java similarity index 88% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEventUserRequest.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEventUserRequest.java index 5978a68..668e340 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UpdateEventUserRequest.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/event/UpdateEventUserRequest.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.event; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/NewUserRequest.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/user/NewUserRequest.java similarity index 91% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/NewUserRequest.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/user/NewUserRequest.java index 2874b90..ff5d348 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/NewUserRequest.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/user/NewUserRequest.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.user; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UserShortDto.java b/main-service/src/main/java/ru/practicum/mainservice/data/dto/user/UserShortDto.java similarity index 84% rename from main-service/src/main/java/ru/practicum/mainservice/data/dto/UserShortDto.java rename to main-service/src/main/java/ru/practicum/mainservice/data/dto/user/UserShortDto.java index f643eab..7c13ec4 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/dto/UserShortDto.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/dto/user/UserShortDto.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.dto; +package ru.practicum.mainservice.data.dto.user; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/Comment.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/Comment.java new file mode 100644 index 0000000..abb6714 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/Comment.java @@ -0,0 +1,40 @@ +package ru.practicum.mainservice.data.model; + +import jakarta.persistence.*; +import lombok.*; +import ru.practicum.mainservice.data.model.enums.CommentStatus; + +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@ToString +@Builder +@EqualsAndHashCode(of = {"id"}) +@Entity +@Table(name = "comments") +public class Comment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne + @JoinColumn(name = "event_id", nullable = false) + private Event event; + + @ManyToOne + @JoinColumn(name = "author_id", nullable = false) + private User author; + + @Column(name = "description") + private String description; + + @Column(name = "status") + private CommentStatus status; + + @Column(name = "published_on") + private LocalDateTime publishedOn; +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/Event.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/Event.java index b1cded0..93454bc 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/Event.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/Event.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import lombok.*; +import ru.practicum.mainservice.data.model.enums.States; import java.time.LocalDateTime; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/Request.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/Request.java index a10286d..34f2f65 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/Request.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/Request.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import lombok.*; +import ru.practicum.mainservice.data.model.enums.Status; import java.time.LocalDateTime; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/RequestParameters.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/RequestParameters.java index 9cba56a..9038399 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/RequestParameters.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/RequestParameters.java @@ -2,6 +2,9 @@ import lombok.*; import org.springframework.data.domain.PageRequest; +import ru.practicum.mainservice.data.model.enums.Sort; +import ru.practicum.mainservice.data.model.enums.States; +import ru.practicum.mainservice.data.model.exceptions.NoValidParameter; import java.time.LocalDateTime; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/Sort.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/Sort.java deleted file mode 100644 index 66cf3b1..0000000 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/Sort.java +++ /dev/null @@ -1,6 +0,0 @@ -package ru.practicum.mainservice.data.model; - -public enum Sort { - EVENT_DATE, - VIEWS; -} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/CommentStatus.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/CommentStatus.java new file mode 100644 index 0000000..6d1cb88 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/CommentStatus.java @@ -0,0 +1,7 @@ +package ru.practicum.mainservice.data.model.enums; + +public enum CommentStatus { + PENDING, + APPROVED, + REJECTED +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/Sort.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/Sort.java new file mode 100644 index 0000000..58d8210 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/Sort.java @@ -0,0 +1,6 @@ +package ru.practicum.mainservice.data.model.enums; + +public enum Sort { + EVENT_DATE, + VIEWS; +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/States.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/States.java similarity index 76% rename from main-service/src/main/java/ru/practicum/mainservice/data/model/States.java rename to main-service/src/main/java/ru/practicum/mainservice/data/model/enums/States.java index 80d8e81..976a54f 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/States.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/States.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.model; +package ru.practicum.mainservice.data.model.enums; public enum States { PUBLISHED, // опубликованный, diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/Status.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/Status.java similarity index 81% rename from main-service/src/main/java/ru/practicum/mainservice/data/model/Status.java rename to main-service/src/main/java/ru/practicum/mainservice/data/model/enums/Status.java index 916c2f5..39a9976 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/Status.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/enums/Status.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.model; +package ru.practicum.mainservice.data.model.enums; public enum Status { PENDING, // рассматриваемый diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/CommentActionException.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/CommentActionException.java new file mode 100644 index 0000000..342fe0d --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/CommentActionException.java @@ -0,0 +1,7 @@ +package ru.practicum.mainservice.data.model.exceptions; + +public class CommentActionException extends RuntimeException { + public CommentActionException(String message) { + super(message); + } +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/EntityCreationDataIncorrect.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityCreationDataIncorrect.java similarity index 73% rename from main-service/src/main/java/ru/practicum/mainservice/data/model/EntityCreationDataIncorrect.java rename to main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityCreationDataIncorrect.java index daa9748..63d5e3b 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/EntityCreationDataIncorrect.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityCreationDataIncorrect.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.model; +package ru.practicum.mainservice.data.model.exceptions; public class EntityCreationDataIncorrect extends RuntimeException { public EntityCreationDataIncorrect(String message) { diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/EntityIsRelatedWithOthers.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityIsRelatedWithOthers.java similarity index 77% rename from main-service/src/main/java/ru/practicum/mainservice/data/model/EntityIsRelatedWithOthers.java rename to main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityIsRelatedWithOthers.java index 8270c32..138b029 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/EntityIsRelatedWithOthers.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityIsRelatedWithOthers.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.model; +package ru.practicum.mainservice.data.model.exceptions; public class EntityIsRelatedWithOthers extends RuntimeException { public EntityIsRelatedWithOthers(final String theCategoryIsNotEmpty) { diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/EntityUpdateConflict.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityUpdateConflict.java similarity index 72% rename from main-service/src/main/java/ru/practicum/mainservice/data/model/EntityUpdateConflict.java rename to main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityUpdateConflict.java index 7824b72..aba74c3 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/EntityUpdateConflict.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/EntityUpdateConflict.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.model; +package ru.practicum.mainservice.data.model.exceptions; public class EntityUpdateConflict extends RuntimeException { public EntityUpdateConflict(String message) { diff --git a/main-service/src/main/java/ru/practicum/mainservice/data/model/NoValidParameter.java b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/NoValidParameter.java similarity index 69% rename from main-service/src/main/java/ru/practicum/mainservice/data/model/NoValidParameter.java rename to main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/NoValidParameter.java index e824064..ad82174 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/data/model/NoValidParameter.java +++ b/main-service/src/main/java/ru/practicum/mainservice/data/model/exceptions/NoValidParameter.java @@ -1,4 +1,4 @@ -package ru.practicum.mainservice.data.model; +package ru.practicum.mainservice.data.model.exceptions; public class NoValidParameter extends RuntimeException { public NoValidParameter(String mes) { diff --git a/main-service/src/main/java/ru/practicum/mainservice/mapper/Mapper.java b/main-service/src/main/java/ru/practicum/mainservice/mapper/Mapper.java index fee7848..e55360b 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/mapper/Mapper.java +++ b/main-service/src/main/java/ru/practicum/mainservice/mapper/Mapper.java @@ -1,11 +1,18 @@ package ru.practicum.mainservice.mapper; import lombok.experimental.UtilityClass; -import ru.practicum.mainservice.data.dto.*; +import ru.practicum.mainservice.data.dto.RequestDto; +import ru.practicum.mainservice.data.dto.comment.CommentDto; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateResult; +import ru.practicum.mainservice.data.dto.compilation.NewCompilationDto; +import ru.practicum.mainservice.data.dto.compilation.UpdateCompilationRequest; +import ru.practicum.mainservice.data.dto.event.*; +import ru.practicum.mainservice.data.dto.user.NewUserRequest; import ru.practicum.mainservice.data.model.*; import ru.practicum.statsdto.dto.CategoryDto; import ru.practicum.statsdto.dto.UserDto; +import java.util.List; import java.util.Set; @UtilityClass @@ -161,4 +168,32 @@ public static RequestDto toRequestDto(final Request request) { .status(request.getStatus()) .build(); } + + public static Comment toComment(CommentDto dto, User currentUser, Event currentEvent) { + return Comment.builder() + .author(currentUser) + .description(dto.getDescription()) + .event(currentEvent) + .status(dto.getStatus()) + .publishedOn(dto.getPublishedOn()) + .build(); + } + + + public static CommentDto toCommentDto(final Comment comment) { + return CommentDto.builder() + .id(comment.getId()) + .eventId(comment.getEvent().getId()) + .description(comment.getDescription()) + .user(toUserDto(comment.getAuthor())) + .publishedOn(comment.getPublishedOn()) + .status(comment.getStatus()) + .build(); + } + + public static CommentStatusUpdateResult concertToUpdatedResult(List list) { + return CommentStatusUpdateResult.builder() + .resolvedComments(list) + .build(); + } } diff --git a/main-service/src/main/java/ru/practicum/mainservice/repository/CommentRepository.java b/main-service/src/main/java/ru/practicum/mainservice/repository/CommentRepository.java new file mode 100644 index 0000000..e28bec3 --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/repository/CommentRepository.java @@ -0,0 +1,43 @@ +package ru.practicum.mainservice.repository; + +import jakarta.transaction.Transactional; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import ru.practicum.mainservice.data.model.Comment; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +@Repository +public interface CommentRepository extends JpaRepository { + + @Query(value = """ + select * + from comments as c + where c.event_id = :eventId + and c.id in (:ids) + """, nativeQuery = true) + List getCommentsByIdsAndEventId(@Param("ids") final Set ids, @Param("eventId") final Long eventId); + + @Transactional + @Modifying + @Query("UPDATE Comment c SET c.status = CommentStatus.APPROVED, c.publishedOn = ?1 WHERE c.id IN(?2)") + void publishComment(LocalDateTime published, List ids); + + @Transactional + @Modifying + @Query("UPDATE Comment c SET c.status = CommentStatus.REJECTED WHERE c.id IN(:ids)") + void rejectComment(@Param("ids") final List ids); + + + List getCommentsByEventId(Long eventId, PageRequest of); + + Optional findByEventIdAndId(Long eventId, Long commentId); + +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/repository/CustomEventRepository.java b/main-service/src/main/java/ru/practicum/mainservice/repository/CustomEventRepository.java index 711609e..a906363 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/repository/CustomEventRepository.java +++ b/main-service/src/main/java/ru/practicum/mainservice/repository/CustomEventRepository.java @@ -1,6 +1,6 @@ package ru.practicum.mainservice.repository; -import ru.practicum.mainservice.data.dto.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; import ru.practicum.mainservice.data.model.RequestParameters; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/repository/RequestRepository.java b/main-service/src/main/java/ru/practicum/mainservice/repository/RequestRepository.java index dda462b..26252cb 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/repository/RequestRepository.java +++ b/main-service/src/main/java/ru/practicum/mainservice/repository/RequestRepository.java @@ -5,6 +5,7 @@ import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import ru.practicum.mainservice.data.model.Request; +import ru.practicum.mainservice.data.model.enums.Status; import java.util.List; @@ -27,4 +28,6 @@ int doesRequestAlreadyExists(@Param("requesterId") final long userId, List findAllRequestsByIdAndRequesterId(final Long id, final Long requesterId); + + boolean existsByRequesterIdAndEventIdAndStatusIn(final Long requesterId, final Long eventId, final List statuses); } \ No newline at end of file diff --git a/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomEventRepositoryImpl.java b/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomEventRepositoryImpl.java index 7afd553..a5640ad 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomEventRepositoryImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomEventRepositoryImpl.java @@ -8,10 +8,10 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Repository; -import ru.practicum.mainservice.data.dto.EventResponseDto; -import ru.practicum.mainservice.data.dto.LocationDto; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.LocationDto; import ru.practicum.mainservice.data.model.RequestParameters; -import ru.practicum.mainservice.data.model.Status; +import ru.practicum.mainservice.data.model.enums.Status; import ru.practicum.mainservice.repository.CustomEventRepository; import ru.practicum.statsdto.dto.CategoryDto; import ru.practicum.statsdto.dto.UserDto; diff --git a/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomRequestRepositoryImpl.java b/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomRequestRepositoryImpl.java index 423ffca..f1a08cd 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomRequestRepositoryImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/repository/implementations/CustomRequestRepositoryImpl.java @@ -4,7 +4,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; import ru.practicum.mainservice.data.model.Request; -import ru.practicum.mainservice.data.model.Status; +import ru.practicum.mainservice.data.model.enums.Status; import ru.practicum.mainservice.repository.CustomRequestRepository; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CategoriesServiceImpl.java b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CategoriesServiceImpl.java index 43b33ce..e1f1116 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CategoriesServiceImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CategoriesServiceImpl.java @@ -7,7 +7,7 @@ import org.springframework.transaction.annotation.Transactional; import ru.practicum.mainservice.data.dto.CategoryCreate; import ru.practicum.mainservice.data.model.Category; -import ru.practicum.mainservice.data.model.EntityUpdateConflict; +import ru.practicum.mainservice.data.model.exceptions.EntityUpdateConflict; import ru.practicum.mainservice.mapper.Mapper; import ru.practicum.mainservice.repository.CategoriesRepository; import ru.practicum.mainservice.repository.EventRepository; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CommentServiceImpl.java b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CommentServiceImpl.java new file mode 100644 index 0000000..13c19fd --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CommentServiceImpl.java @@ -0,0 +1,159 @@ +package ru.practicum.mainservice.service.implemetations; + +import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import ru.practicum.mainservice.data.dto.comment.CommentDto; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateRequest; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateResult; +import ru.practicum.mainservice.data.model.enums.CommentStatus; +import ru.practicum.mainservice.data.model.enums.States; +import ru.practicum.mainservice.data.model.enums.Status; +import ru.practicum.mainservice.data.model.exceptions.CommentActionException; +import ru.practicum.mainservice.mapper.Mapper; +import ru.practicum.mainservice.repository.CommentRepository; +import ru.practicum.mainservice.repository.EventRepository; +import ru.practicum.mainservice.repository.RequestRepository; +import ru.practicum.mainservice.repository.UserRepository; +import ru.practicum.mainservice.service.interfaces.CommentService; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.stream.Collectors; + +import static ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateRequest.Status.APPROVE; + +@Service +@RequiredArgsConstructor +@Transactional +public class CommentServiceImpl implements CommentService { + private static final Logger log = LoggerFactory.getLogger(CommentServiceImpl.class); + private final CommentRepository commentRepository; + private final UserRepository userRepository; + private final EventRepository eventRepository; + private final RequestRepository requestRepository; + + + @Override + public CommentStatusUpdateResult decisionComments(Long eventId, CommentStatusUpdateRequest commentStatusUpdateRequest) { + + eventRepository.findById(eventId).orElseThrow(NoSuchElementException::new); + + List comments = commentRepository.getCommentsByIdsAndEventId(commentStatusUpdateRequest.getIds(), eventId) + .stream().map(Mapper::toCommentDto).toList(); + + if (commentStatusUpdateRequest.getStatus() == APPROVE + && comments.stream().anyMatch(c -> c.getStatus() == CommentStatus.APPROVED)) { + throw new CommentActionException("Нельзя дважды одобрить публикацию комментария"); + } + + if (commentStatusUpdateRequest.getStatus() == CommentStatusUpdateRequest.Status.REJECT + && comments.stream().anyMatch(c -> c.getStatus() == CommentStatus.REJECTED)) { + throw new CommentActionException("Нельзя дважды отклонить публикацию комментария"); + } + + CommentStatus updatedStatus = commentStatusUpdateRequest.getStatus() == APPROVE + ? CommentStatus.APPROVED + : CommentStatus.REJECTED; + + Set commentsIds = comments.stream() + .peek(c -> c.setStatus(updatedStatus)) + .map(CommentDto::getId).collect(Collectors.toSet()); + + if (updatedStatus == CommentStatus.APPROVED) { + commentRepository.publishComment(LocalDateTime.now(), commentsIds.stream().toList()); + } else { + commentRepository.rejectComment(commentsIds.stream().toList()); + } + CommentStatusUpdateResult commentStatusUpdateResult = Mapper.concertToUpdatedResult(comments); + log.info("Принято решение по следующим комментариям: {}\nРезультат: {}", commentStatusUpdateResult, commentStatusUpdateResult); + return commentStatusUpdateResult; + } + + @Override + public CommentDto createComment(Long userId, Long eventId, CommentDto dto) { + var user = userRepository.findById(userId).orElseThrow(NoSuchElementException::new); + var event = eventRepository.findById(eventId).orElseThrow(NoSuchElementException::new); + + if (event.getState() != States.PUBLISHED) { + throw new CommentActionException("Комментировать неопубликованное событие невозможно"); + } + + if (event.getInitiator().getId() == user.getId()) { + dto.setStatus(CommentStatus.APPROVED); + dto.setPublishedOn(LocalDateTime.now()); + } else { + if (!hasConfirmedRequestOnEvent(userId, eventId)) { + throw new CommentActionException("Пользователь не может оставлять комментарий не приняв участие в событии."); + } + dto.setStatus(CommentStatus.PENDING); + } + + var comment = commentRepository.save(Mapper.toComment(dto, user, event)); + log.info("Comment saved: {}", comment); + return Mapper.toCommentDto(comment); + } + + @Override + public void deleteComment(Long userId, Long eventId, Long commentId) { + userRepository.findById(userId).orElseThrow(NoSuchElementException::new); + var event = eventRepository.findById(eventId).orElseThrow(NoSuchElementException::new); + var comment = commentRepository.findById(commentId).orElseThrow(NoSuchElementException::new); + + if (userId != comment.getAuthor().getId() && userId != event.getInitiator().getId()) { + throw new CommentActionException("Комментарий могут удалять или автор или инициатор события"); + } + + commentRepository.delete(comment); + log.info("Comment deleted: {}", comment); + } + + @Transactional(readOnly = true) + @Override + public List getCommentsByEventId(Long userId, Long eventId, PageRequest of) { + var user = userRepository.findById(userId).orElseThrow(NoSuchElementException::new); + var event = eventRepository.findById(eventId).orElseThrow(NoSuchElementException::new); + + if (!(user.getId() == (event.getInitiator().getId()))) { + throw new CommentActionException("Нельзя просмотреть все комментариии если вы не владаелец события"); + } + List commentsByEventId = commentRepository.getCommentsByEventId(eventId, of) + .stream().map(Mapper::toCommentDto).toList(); + log.info("Найдены комментарии: {}", commentsByEventId); + return commentsByEventId; + } + + @Transactional(readOnly = true) + @Override + public CommentDto getCommentByIdAndEventId(Long userId, Long eventId, Long commentId) { + userRepository.findById(userId).orElseThrow(NoSuchElementException::new); + eventRepository.findById(eventId).orElseThrow(NoSuchElementException::new); + var comment = commentRepository.findByEventIdAndId(eventId, commentId) + .orElseThrow(NoSuchElementException::new); + + log.info("Comment get: {}", comment); + return Mapper.toCommentDto(comment); + } + + + @Transactional(readOnly = true) + @Override + public CommentDto findCommentById(Long commentId) { + var dto = Mapper.toCommentDto(commentRepository.findById(commentId).orElseThrow(NoSuchElementException::new)); + log.info("Comment found: {}", dto); + return dto; + } + + private boolean hasConfirmedRequestOnEvent(final long userId, final long eventId) { + return requestRepository.existsByRequesterIdAndEventIdAndStatusIn( + userId, + eventId, + List.of(Status.CONFIRMED) + ); + } +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CompilationsServiceImpl.java b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CompilationsServiceImpl.java index 85ded23..2aafbf7 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CompilationsServiceImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/CompilationsServiceImpl.java @@ -5,8 +5,8 @@ import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.practicum.mainservice.data.dto.NewCompilationDto; -import ru.practicum.mainservice.data.dto.UpdateCompilationRequest; +import ru.practicum.mainservice.data.dto.compilation.NewCompilationDto; +import ru.practicum.mainservice.data.dto.compilation.UpdateCompilationRequest; import ru.practicum.mainservice.data.model.Compilations; import ru.practicum.mainservice.data.model.Event; import ru.practicum.mainservice.mapper.Mapper; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/EventServiceImpl.java b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/EventServiceImpl.java index a8dc693..36cf850 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/EventServiceImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/EventServiceImpl.java @@ -5,11 +5,17 @@ import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.practicum.mainservice.data.dto.EventResponseDto; -import ru.practicum.mainservice.data.dto.NewEventDto; -import ru.practicum.mainservice.data.dto.UpdateEventAdminRequest; -import ru.practicum.mainservice.data.dto.UpdateEventUserRequest; -import ru.practicum.mainservice.data.model.*; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.NewEventDto; +import ru.practicum.mainservice.data.dto.event.UpdateEventAdminRequest; +import ru.practicum.mainservice.data.dto.event.UpdateEventUserRequest; +import ru.practicum.mainservice.data.model.Category; +import ru.practicum.mainservice.data.model.Event; +import ru.practicum.mainservice.data.model.RequestParameters; +import ru.practicum.mainservice.data.model.User; +import ru.practicum.mainservice.data.model.enums.States; +import ru.practicum.mainservice.data.model.exceptions.EntityUpdateConflict; +import ru.practicum.mainservice.data.model.exceptions.NoValidParameter; import ru.practicum.mainservice.mapper.Mapper; import ru.practicum.mainservice.repository.CategoriesRepository; import ru.practicum.mainservice.repository.EventRepository; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/RequestServiceImpl.java b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/RequestServiceImpl.java index ec58c75..798560c 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/RequestServiceImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/RequestServiceImpl.java @@ -5,11 +5,15 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.practicum.mainservice.data.dto.EventRequestStatus; -import ru.practicum.mainservice.data.dto.EventRequestStatusUpdateRequest; -import ru.practicum.mainservice.data.dto.EventRequestStatusUpdateResult; import ru.practicum.mainservice.data.dto.RequestDto; -import ru.practicum.mainservice.data.model.*; +import ru.practicum.mainservice.data.dto.event.EventRequestStatus; +import ru.practicum.mainservice.data.dto.event.EventRequestStatusUpdateRequest; +import ru.practicum.mainservice.data.dto.event.EventRequestStatusUpdateResult; +import ru.practicum.mainservice.data.model.Request; +import ru.practicum.mainservice.data.model.enums.States; +import ru.practicum.mainservice.data.model.enums.Status; +import ru.practicum.mainservice.data.model.exceptions.EntityCreationDataIncorrect; +import ru.practicum.mainservice.data.model.exceptions.EntityUpdateConflict; import ru.practicum.mainservice.mapper.Mapper; import ru.practicum.mainservice.repository.EventRepository; import ru.practicum.mainservice.repository.RequestRepository; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/UserServiceImpl.java b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/UserServiceImpl.java index 966d47e..f99f88e 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/UserServiceImpl.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/implemetations/UserServiceImpl.java @@ -5,7 +5,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import ru.practicum.mainservice.data.dto.NewUserRequest; +import ru.practicum.mainservice.data.dto.user.NewUserRequest; import ru.practicum.mainservice.data.model.User; import ru.practicum.mainservice.mapper.Mapper; import ru.practicum.mainservice.repository.UserRepository; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CommentService.java b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CommentService.java new file mode 100644 index 0000000..aa112aa --- /dev/null +++ b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CommentService.java @@ -0,0 +1,23 @@ +package ru.practicum.mainservice.service.interfaces; + +import org.springframework.data.domain.PageRequest; +import ru.practicum.mainservice.data.dto.comment.CommentDto; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateRequest; +import ru.practicum.mainservice.data.dto.comment.CommentStatusUpdateResult; + +import java.util.List; + +public interface CommentService { + + CommentDto findCommentById(Long commentId); + + CommentStatusUpdateResult decisionComments(Long eventId, CommentStatusUpdateRequest commentStatusUpdateRequest); + + CommentDto createComment(Long userId, Long eventId, CommentDto comment); + + void deleteComment(Long userId, Long eventId, Long commentId); + + List getCommentsByEventId(Long userId, Long eventId, PageRequest of); + + CommentDto getCommentByIdAndEventId(Long userId, Long eventId, Long commentId); +} diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CompilationsService.java b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CompilationsService.java index ff3978f..176dd8f 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CompilationsService.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/CompilationsService.java @@ -1,8 +1,8 @@ package ru.practicum.mainservice.service.interfaces; import org.springframework.data.domain.PageRequest; -import ru.practicum.mainservice.data.dto.NewCompilationDto; -import ru.practicum.mainservice.data.dto.UpdateCompilationRequest; +import ru.practicum.mainservice.data.dto.compilation.NewCompilationDto; +import ru.practicum.mainservice.data.dto.compilation.UpdateCompilationRequest; import ru.practicum.mainservice.data.model.Compilations; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/EventService.java b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/EventService.java index e6d13ff..98523ce 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/EventService.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/EventService.java @@ -1,10 +1,10 @@ package ru.practicum.mainservice.service.interfaces; import org.springframework.data.domain.PageRequest; -import ru.practicum.mainservice.data.dto.EventResponseDto; -import ru.practicum.mainservice.data.dto.NewEventDto; -import ru.practicum.mainservice.data.dto.UpdateEventAdminRequest; -import ru.practicum.mainservice.data.dto.UpdateEventUserRequest; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.NewEventDto; +import ru.practicum.mainservice.data.dto.event.UpdateEventAdminRequest; +import ru.practicum.mainservice.data.dto.event.UpdateEventUserRequest; import ru.practicum.mainservice.data.model.RequestParameters; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/RequestService.java b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/RequestService.java index f3c7a08..fb76c64 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/RequestService.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/RequestService.java @@ -1,9 +1,9 @@ package ru.practicum.mainservice.service.interfaces; import jakarta.validation.Valid; -import ru.practicum.mainservice.data.dto.EventRequestStatusUpdateRequest; -import ru.practicum.mainservice.data.dto.EventRequestStatusUpdateResult; import ru.practicum.mainservice.data.dto.RequestDto; +import ru.practicum.mainservice.data.dto.event.EventRequestStatusUpdateRequest; +import ru.practicum.mainservice.data.dto.event.EventRequestStatusUpdateResult; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/UserService.java b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/UserService.java index 7269e27..c986c39 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/UserService.java +++ b/main-service/src/main/java/ru/practicum/mainservice/service/interfaces/UserService.java @@ -1,7 +1,7 @@ package ru.practicum.mainservice.service.interfaces; import org.springframework.data.domain.PageRequest; -import ru.practicum.mainservice.data.dto.NewUserRequest; +import ru.practicum.mainservice.data.dto.user.NewUserRequest; import ru.practicum.statsdto.dto.UserDto; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/stat/EventStatConverter.java b/main-service/src/main/java/ru/practicum/mainservice/stat/EventStatConverter.java index b7b3846..8458b5d 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/stat/EventStatConverter.java +++ b/main-service/src/main/java/ru/practicum/mainservice/stat/EventStatConverter.java @@ -3,7 +3,7 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; -import ru.practicum.mainservice.data.dto.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; import ru.practicum.statsdto.dto.ViewStats; import java.util.List; diff --git a/main-service/src/main/java/ru/practicum/mainservice/stat/StatAdapter.java b/main-service/src/main/java/ru/practicum/mainservice/stat/StatAdapter.java index ff4f9e2..92c2800 100644 --- a/main-service/src/main/java/ru/practicum/mainservice/stat/StatAdapter.java +++ b/main-service/src/main/java/ru/practicum/mainservice/stat/StatAdapter.java @@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import ru.practicum.mainservice.data.dto.EventResponseDto; +import ru.practicum.mainservice.data.dto.event.EventResponseDto; import ru.practicum.statsclient.StatClient; import ru.practicum.statsdto.dto.StatDto; import ru.practicum.statsdto.dto.URLParameter; diff --git a/main-service/src/main/resources/application-dev.properties b/main-service/src/main/resources/application-dev.properties index 90e511e..bf5d159 100644 --- a/main-service/src/main/resources/application-dev.properties +++ b/main-service/src/main/resources/application-dev.properties @@ -1,6 +1,6 @@ spring.sql.init.mode=always spring.jpa.properties.hibernate.format_sql=true -spring.jpa.show-sql=true +#spring.jpa.show-sql=true stats-server.url=${STATS_SERVER_URL:http://localhost:9090} logging.level.org.springframework.jdbc.datasource.init.ScriptUtils=DEBUG logging.level.org.springframework.boot.autoconfigure.sql.init=DEBUG @@ -8,6 +8,6 @@ logging.level.org.springframework.orm.jpa=INFO logging.level.org.springframework.transaction=INFO logging.level.org.springframework.transaction.interceptor=TRACE logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG -spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:6432}/${DB_NAME:ewn-db} +spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:6432}/${DB_NAME:ewm-db} spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.datasource.driverClassName=org.postgresql.Driver \ No newline at end of file diff --git a/main-service/src/main/resources/schema.sql b/main-service/src/main/resources/schema.sql index 70dc1f4..da977c9 100644 --- a/main-service/src/main/resources/schema.sql +++ b/main-service/src/main/resources/schema.sql @@ -54,4 +54,14 @@ CREATE TABLE IF NOT EXISTS compilations_events ( compilation_id INTEGER NOT NULL REFERENCES compilations (id) ON DELETE CASCADE, event_id INTEGER NOT NULL REFERENCES events (id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS comments +( + id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY NOT NULL, + event_id BIGINT REFERENCES events (id), + author_id BIGINT REFERENCES users (id), + description VARCHAR(2000), + status VARCHAR(255), + published_on TIMESTAMP ); \ No newline at end of file diff --git a/postman/feature.json b/postman/feature.json new file mode 100644 index 0000000..3e33862 --- /dev/null +++ b/postman/feature.json @@ -0,0 +1,1048 @@ +{ + "info": { + "_postman_id": "150652fb-c5e5-4957-b8a6-8778af72c8a5", + "name": "Comments", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Validation", + "item": [ + { + "name": "Добавление комментария с пустым телом", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 400 и данные в формате json\", function () {\r", + " pm.response.to.be.badRequest; \r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"description\" : \"\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + } + ] + } + }, + "response": [] + } + ] + }, + { + "name": "409 Conflict", + "item": [ + { + "name": "Добавление комментария от неучастника", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 409 и данные в формате json\", function () {\r", + " pm.response.to.be.clientError; \r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript" + } + }, + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try { \r", + " const user1 = await api.addUser(rnd.getUser());\r", + " const user2 = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"userId\", user2.id)\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let event = await api.addEvent(user1.id, rnd.getEvent(category.id));\r", + " pm.collectionVariables.set(\"eventId\", event.id);\r", + " event = await api.publishEvent(event.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"description\" : \"commentsdfsdfdsfdsfdsfdsafdfgfdhsfghfgjhfgdhjdfghjfgdjdfgjdfgjdfg\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Добавление комментария на неопубликованное событие", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try { \r", + " const user1 = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"userId\", user1.id)\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let event = await api.addEvent(user1.id, rnd.getEvent(category.id));\r", + " pm.collectionVariables.set(\"eventId\", event.id);\r", + " const comment = rnd.getComment();\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 409 и данные в формате json\", function () {\r", + " pm.response.to.be.clientError; \r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"description\": \"dsgsdgsdgsdgsdgdsgsdgsdgsdgg\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + } + ] + } + }, + "response": [] + } + ] + }, + { + "name": "Добавление нового комментария от владельца события", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try { \r", + " const user = await api.addUser(rnd.getUser());\r", + " pm.collectionVariables.set(\"userId\", user.id)\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let event = await api.addEvent(user.id, rnd.getEvent(category.id));\r", + " pm.collectionVariables.set(\"eventId\", event.id);\r", + " event = await api.publishEvent(event.id);\r", + " const comment = rnd.getComment();\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 201 и данные в формате json\", function () {\r", + " pm.response.to.have.status(201);\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "\r", + "const source = JSON.parse(pm.request.body.raw);\r", + "const target = pm.response.json();\r", + "pm.collectionVariables.set(\"commentId\", target.id);\r", + "\r", + "pm.test(\"Представление комментария должно содержать поля: id, eventId, user, description, publishedOn, status\", function () {\r", + "pm.expect(target).to.have.property('id');\r", + "pm.expect(target).to.have.property('eventId');\r", + "pm.expect(target).to.have.property('user');\r", + "pm.expect(target).to.have.property('description');\r", + "pm.expect(target).to.have.property('publishedOn');\r", + "pm.expect(target).to.have.property('status');\r", + "});\r", + "\r", + "pm.test(\"Данные в ответе должны соответствовать данным в запросе\", function () {\r", + " pm.expect(target.id).to.not.be.null;\r", + " pm.expect(source.description).equal(target.description, 'Содержание комментария должно совпадать с отправленным');\r", + " pm.expect(target.status).equal(\"APPROVED\", 'Если автор события сам оставляет комментарий, то его статуст должен быть APPROVED')\r", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"description\": \"dsfdsgdsgsdgdsggdwsgdsgsdgsdgsdgsdg\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Добавление комментария от участиника (не владельца)", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " const user1 = await api.addUser(rnd.getUser());\r", + " const user2 = await api.addUser(rnd.getUser());\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let eventBody = rnd.getEvent(category.id);\r", + " eventBody['requestModeration'] = true\r", + " let event = await api.addEvent(user1.id, eventBody);\r", + " event = await api.publishEvent(event.id);\r", + " const requestToJoin = await api.publishParticipationRequest(event.id, user2.id);\r", + " pm.collectionVariables.set('userId', user2.id);\r", + " pm.collectionVariables.set('eventId', event.id);\r", + " api.acceptParticipationRequest(event.id, user1.id, requestToJoin.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " // выполняем наш скрипт\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 201 и данные в формате json\", function () {\r", + " pm.response.to.have.status(201);\r", + " pm.response.to.be.withBody;\r", + " pm.response.to.be.json;\r", + "});\r", + "\r", + "const source = JSON.parse(pm.request.body.raw);\r", + "const target = pm.response.json();\r", + "pm.collectionVariables.set(\"commentId\", target.id);\r", + "\r", + "pm.test(\"Представление комментария должно содержать поля: id, eventId, user, description, publishedOn, status\", function () {\r", + "pm.expect(target).to.have.property('id');\r", + "pm.expect(target).to.have.property('eventId');\r", + "pm.expect(target).to.have.property('user');\r", + "pm.expect(target).to.have.property('description');\r", + "pm.expect(target).to.have.property('publishedOn');\r", + "pm.expect(target).to.have.property('status');\r", + "});\r", + "\r", + "pm.test(\"Данные в ответе должны соответствовать данным в запросе\", function () {\r", + " pm.expect(target.id).to.not.be.null;\r", + " pm.expect(source.description).equal(target.description, 'Содержание комментария должно совпадать с отправленным');\r", + " pm.expect(target.status).equal(\"PENDING\", 'Cтатус комментария отсавленного участником должен быть PENDING')\r", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"description\" : \"dsfsdfdsf\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Поиск комментария по id от автора", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " const user1 = await api.addUser(rnd.getUser());\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let event = await api.addEvent(user1.id, rnd.getEvent(category.id));\r", + " event = await api.publishEvent(event.id);\r", + " \r", + " pm.collectionVariables.set('userId', user1.id);\r", + " pm.collectionVariables.set('eventId', event.id);\r", + " \r", + " let commentBody = rnd.getComment();\r", + " const comment = await api.addComment(pm.collectionVariables.get('userId'), pm.collectionVariables.get('eventId'), commentBody);\r", + " pm.collectionVariables.set('commentId', comment.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " // выполняем наш скрипт\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments/:commentId", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments", + ":commentId" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + }, + { + "key": "commentId", + "value": "{{commentId}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Удаление комментария автором комментария", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " const user1 = await api.addUser(rnd.getUser());\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let eventBody = rnd.getEvent(category.id);\r", + " eventBody['requestModeration'] = true\r", + " let event = await api.addEvent(user1.id, eventBody);\r", + " event = await api.publishEvent(event.id);\r", + " pm.collectionVariables.set('userId', user1.id);\r", + " pm.collectionVariables.set('eventId', event.id);\r", + "\r", + " const comment = await api.addComment(user1.id, event.id, rnd.getComment());\r", + " pm.collectionVariables.set('commentId', comment.id);\r", + "\r", + " const foundedComment = await api.findComment(user1.id, event.id, comment.id);\r", + " pm.collectionVariables.set('response', foundedComment)\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " // выполняем наш скрипт\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 204\", function () {\r", + " pm.response.to.have.status(204);\r", + "});\r", + "\r", + "const source = pm.collectionVariables.get('response');\r", + "const commentId = pm.collectionVariables.get('commentId');\r", + "\r", + "pm.test(\"Комментарий должен быть найден до выполнения запроса\", function(){\r", + " pm.expect(source.id).to.eql(commentId);\r", + "});\r", + "let body\r", + "const req = {\r", + " url: \"http://localhost:8080/users/\" + pm.collectionVariables.get(\"userId\") + \"/event/\" \r", + " + pm.collectionVariables.get(\"eventId\") + \"/comments/\" + commentId,\r", + " method: \"GET\",\r", + " body: body == null ? \"\" : JSON.stringify(body),\r", + " header: { \"Content-Type\": \"application/json\" },\r", + " };\r", + "pm.sendRequest(req, (error, response) => {\r", + " pm.test(\"Комментарий должен быть удалён после выполнения запроса\", function(){\r", + " pm.expect(response.code).to.eql(500);\r", + " });\r", + "})" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "url": { + "raw": "{{baseUrl}}/users/:userId/event/:eventId/comments/:commentId", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "users", + ":userId", + "event", + ":eventId", + "comments", + ":commentId" + ], + "variable": [ + { + "key": "userId", + "value": "{{userId}}" + }, + { + "key": "eventId", + "value": "{{eventId}}" + }, + { + "key": "commentId", + "value": "{{commentId}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Отклонение публикации комментария после решения владельца события", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "const main = async () => {\r", + " const api = new API(pm);\r", + " const rnd = new RandomUtils();\r", + "\r", + " try {\r", + " const user1 = await api.addUser(rnd.getUser());\r", + " const user2 = await api.addUser(rnd.getUser());\r", + " const category = await api.addCategory(rnd.getCategory());\r", + " let eventBody = rnd.getEvent(category.id);\r", + " eventBody['requestModeration'] = true\r", + " let event = await api.addEvent(user1.id, eventBody);\r", + " event = await api.publishEvent(event.id);\r", + " const requestToJoin = await api.publishParticipationRequest(event.id, user2.id);\r", + " pm.collectionVariables.set('userId', user1.id);\r", + " pm.collectionVariables.set('eventId', event.id);\r", + " await api.acceptParticipationRequest(event.id, user1.id, requestToJoin.id);\r", + " const comment = await api.addComment(user2.id, event.id, rnd.getComment());\r", + " pm.collectionVariables.set('commentId', comment.id);\r", + " } catch(err) {\r", + " console.error(\"Ошибка при подготовке тестовых данных.\", err);\r", + " }\r", + "};\r", + "\r", + "const interval = setInterval(() => {}, 1000);\r", + "\r", + "setTimeout(async () => \r", + " {\r", + " try {\r", + " // выполняем наш скрипт\r", + " await main();\r", + " } catch (e) {\r", + " console.error(e);\r", + " } finally {\r", + " clearInterval(interval);\r", + " }\r", + " }, \r", + " 100 \r", + ");" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "pm.test(\"Ответ должен содержать код статуса 201\", function () {\r", + " pm.response.to.have.status(201);\r", + "});\r", + "\r", + "const source = pm.collectionVariables.get('response');\r", + "const commentId = pm.collectionVariables.get('commentId');\r", + "// pm.test(\"Комментарий должен быть найден до выполнения запроса\", function(){\r", + "// pm.expect(source.id).to.eql(commentId);\r", + "// });\r", + "let body\r", + "const req = {\r", + " url: \"http://localhost:8080/admin/comments/\" + commentId,\r", + " method: \"GET\",\r", + " body: body == null ? \"\" : JSON.stringify(body),\r", + " header: { \"Content-Type\": \"application/json\" },\r", + " };\r", + "\r", + "pm.sendRequest(req, (error, response) => {\r", + " pm.test(\"Статус комментария должен быть изменен после выполнения запроса\", function() {\r", + " // Проверяем, что ответ возвращен в формате JSON\r", + " pm.expect(response).to.have.jsonBody();\r", + " const responseBody = response.json();\r", + " pm.expect(responseBody).to.have.property('id');\r", + " // Проверяем, что статус изменился\r", + " pm.expect(responseBody.status).to.eql(\"REJECTED\");\r", + " });\r", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PATCH", + "header": [], + "body": { + "mode": "raw", + "raw": "{\r\n \"ids\":[{{commentId}}],\r\n \"status\": \"REJECT\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{baseUrl}}/admin/comments/event/:eventId", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "admin", + "comments", + "event", + ":eventId" + ], + "variable": [ + { + "key": "eventId", + "value": "{{eventId}}" + } + ] + } + }, + "response": [] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "API = class {", + " constructor(postman, verbose = false, baseUrl = \"http://localhost:8080\") {", + " this.baseUrl = baseUrl;", + " this.pm = postman;", + " this._verbose = verbose;", + " }", + "", + " async addUser(user, verbose=null) {", + " return this.post(\"/admin/users\", user, \"Ошибка при добавлении нового пользователя: \", verbose);", + " }", + "", + " async addCategory(category, verbose=null) {", + " return this.post(\"/admin/categories\", category, \"Ошибка при добавлении новой категории: \", verbose);", + " }", + "", + " async addEvent(userId, event, verbose=null) {", + " return this.post(\"/users/\" + userId + \"/events\", event, \"Ошибка при добавлении нового события: \", verbose);", + " }", + "", + " async addCompilation(compilation, verbose=null) {", + " return this.post(\"/admin/compilations\", compilation, \"Ошибка при добавлении новой подборки: \", verbose);", + " }", + "", + " async addComment(userId, eventId, comment, verbose=null) {", + " return this.post('/users/' + userId + '/event/' + eventId + '/comments', comment, \"Ошибка при добавлении нового комментария: \", verbose);", + " }", + "", + " async publishParticipationRequest(eventId, userId, verbose=null) {", + " return this.post('/users/' + userId + '/requests?eventId=' + eventId, null, \"Ошибка при добавлении нового запроса на участие в событии\", verbose);", + " }", + "", + " async publishEvent(eventId, verbose=null) {", + " return this.patch('/admin/events/' + eventId, {stateAction: \"PUBLISH_EVENT\"}, \"Ошибка при публикации события\", verbose);", + " }", + " ", + " async rejectEvent(eventId, verbose=null) {", + " return this.patch('/admin/events/' + eventId, {stateAction: \"REJECT_EVENT\"}, \"Ошибка при отмене события\", verbose);", + " }", + "", + " async acceptParticipationRequest(eventId, userId, reqId, verbose=null) {", + " return this.patch('/users/' + userId + '/events/' + eventId + '/requests', {requestIds:[reqId], status: \"CONFIRMED\"}, \"Ошибка при принятии заявки на участие в событии\", verbose);", + " }", + "", + " async findCategory(catId, verbose=null) {", + " return this.get('/categories/' + catId, null, \"Ошибка при поиске категории по id\", verbose);", + " }", + "", + " async findCompilation(compId, verbose=null) {", + " return this.get('/compilations/' + compId, null, \"Ошибка при поиске подборки по id\", verbose);", + " }", + "", + " async findEvent(eventId, verbose=null) {", + " return this.get('/events/' + eventId, null, \"Ошибка при поиске события по id\", verbose);", + " }", + "", + " async findUser(userId, verbose=null) {", + " return this.get('/admin/users?ids=' + userId, null, \"Ошибка при поиске пользователя по id\", verbose);", + " }", + "", + " async findComment(userId, eventId, commentId, verbose=null) {", + " return this.get('/users/' + userId + '/event/'+ eventId + '/comments/'+ commentId, null, \"Ошибка поиска комментария\", verbose);", + " }", + "", + " async post(path, body, errorText = \"Ошибка при выполнении post-запроса: \", verbose=null) {", + " return this.sendRequest(\"POST\", path, body, errorText, verbose);", + " }", + "", + " async patch(path, body = null, errorText = \"Ошибка при выполнении patch-запроса: \", verbose=null) {", + " return this.sendRequest(\"PATCH\", path, body, errorText, verbose);", + " }", + "", + " async get(path, body = null, errorText = \"Ошибка при выполнении get-запроса: \", verbose=null) {", + " return this.sendRequest(\"GET\", path, body, errorText, verbose);", + " }", + " async sendRequest(method, path, body=null, errorText = \"Ошибка при выполнении запроса: \", verbose=null) {", + " return new Promise((resolve, reject) => {", + " verbose = verbose == null ? this._verbose : verbose;", + " const request = {", + " url: this.baseUrl + path,", + " method: method,", + " body: body == null ? \"\" : JSON.stringify(body),", + " header: { \"Content-Type\": \"application/json\" },", + " };", + " if(verbose) {", + " console.log(\"Отправляю запрос: \", request);", + " }", + "", + " try {", + " this.pm.sendRequest(request, (error, response) => {", + " if(error || (response.code >= 400 && response.code <= 599)) {", + " let err = error ? error : JSON.stringify(response.json());", + " console.error(\"При выполнении запроса к серверу возникла ошика.\\n\", err,", + " \"\\nДля отладки проблемы повторите такой же запрос к вашей программе \" + ", + " \"на локальном компьютере. Данные запроса:\\n\", JSON.stringify(request));", + "", + " reject(new Error(errorText + err));", + " }", + " if(verbose) {", + " console.log(\"Результат обработки запроса: код состояния - \", response.code, \", тело: \", response.json());", + " }", + " if (response.stream.length === 0){", + " reject(new Error('Отправлено пустое тело ответа'))", + " }else{", + " resolve(response.json());", + " }", + " }); ", + " } catch(err) {", + " if(verbose) {", + " console.error(errorText, err);", + " }", + " return Promise.reject(err);", + " }", + " });", + " }", + "};", + "", + "RandomUtils = class {", + " constructor() {}", + "", + " getUser() {", + " return {", + " name: pm.variables.replaceIn('{{$randomFullName}}'),", + " email: pm.variables.replaceIn('{{$randomEmail}}')", + " };", + " }", + "", + " getCategory() {", + " return {", + " name: pm.variables.replaceIn('{{$randomWord}}') + Math.floor(Math.random() * 10000 * Math.random()).toString()", + " };", + " }", + "", + " getEvent(categoryId) {", + " return {", + " annotation: pm.variables.replaceIn('{{$randomLoremParagraph}}'),", + " category: categoryId,", + " description: pm.variables.replaceIn('{{$randomLoremParagraphs}}'),", + " eventDate: this.getFutureDateTime(),", + " location: {", + " lat: parseFloat(pm.variables.replaceIn('{{$randomLatitude}}')),", + " lon: parseFloat(pm.variables.replaceIn('{{$randomLongitude}}')),", + " },", + " paid: pm.variables.replaceIn('{{$randomBoolean}}'),", + " participantLimit: pm.variables.replaceIn('{{$randomInt}}'),", + " requestModeration: pm.variables.replaceIn('{{$randomBoolean}}'),", + " title: pm.variables.replaceIn('{{$randomLoremSentence}}'),", + " }", + " }", + "", + " getCompilation(...eventIds) {", + " return {", + " title: pm.variables.replaceIn('{{$randomLoremSentence}}').slice(0, 50),", + " pinned: pm.variables.replaceIn('{{$randomBoolean}}'),", + " events: eventIds", + " };", + " }", + "", + " getComment() {", + " return {", + " description: pm.variables.replaceIn('{{$randomLoremSentence}}')", + " };", + " }", + "", + " getFutureDateTime(hourShift = 5, minuteShift=0, yearShift=0) {", + " let moment = require('moment');", + "", + " let m = moment();", + " m.add(hourShift, 'hour');", + " m.add(minuteShift, 'minute');", + " m.add(yearShift, 'year');", + "", + " return m.format('YYYY-MM-DD HH:mm:ss');", + " }", + "", + " getWord(length = 1) {", + " let result = '';", + " const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';", + " const charactersLength = characters.length;", + " let counter = 0;", + " while (counter < length) {", + " result += characters.charAt(Math.floor(Math.random() * charactersLength));", + " counter += 1;", + " }", + " return result;", + " }", + "}" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "key": "baseUrl", + "value": "http://localhost:8080", + "type": "default" + }, + { + "key": "userId", + "value": 0, + "type": "default" + }, + { + "key": "eventId", + "value": 0, + "type": "default" + }, + { + "key": "commentId", + "value": "0", + "type": "default" + }, + { + "key": "response", + "value": "" + } + ] +} \ No newline at end of file diff --git a/stats/stats-server/Dockerfile b/stats/stats-server/Dockerfile index b279e45..bd17847 100644 --- a/stats/stats-server/Dockerfile +++ b/stats/stats-server/Dockerfile @@ -1,4 +1,4 @@ -FROM amazoncorretto:21 +FROM openjdk:21 COPY target/*.jar app.jar ENTRYPOINT ["java","-jar","/app.jar"] EXPOSE 9090 \ No newline at end of file