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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# java-explore-with-me
Template repository for ExploreWithMe project.
https://github.com/Siustoster/java-explore-with-me/pull/3
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.practicum.mainservice.model.user.dto.UserDto;
import ru.practicum.mainservice.model.user.dto.UserDtoWithRating;
import ru.practicum.mainservice.service.UserService;

import java.util.List;
Expand Down Expand Up @@ -40,4 +41,12 @@ public void deleteUser(@PathVariable @Positive Integer userId) {
log.info("Контроллер админа получил запрос на удаление пользователя с id = {}", userId);
userService.deleteUser(userId);
}

@GetMapping("/users/rating")
public List<UserDtoWithRating> getUsersWithRating(@RequestParam(defaultValue = "0") @PositiveOrZero Integer from,
@RequestParam(defaultValue = "10") @Positive Integer size) {
log.info("Контроллер админа получил запрос на получение списка пользователей с информацией " +
"об их рейтинге и сортировкой по возрастанию рейтинга");
return userService.getUsersWithRating(from, size);
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
package ru.practicum.mainservice.controller;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.practicum.mainservice.model.event.dto.EventFullDto;
import ru.practicum.mainservice.model.event.dto.EventShortDto;
import ru.practicum.mainservice.model.event.dto.NewEventDto;
import ru.practicum.mainservice.model.event.dto.UpdateEventRequest;
import ru.practicum.mainservice.model.event.dto.*;
import ru.practicum.mainservice.model.request.dto.EventRequestStatusUpdateRequest;
import ru.practicum.mainservice.model.request.dto.EventRequestStatusUpdateResult;
import ru.practicum.mainservice.model.request.dto.ParticipationRequestDto;
import ru.practicum.mainservice.service.EventService;
import ru.practicum.mainservice.service.RateService;
import ru.practicum.mainservice.service.ParticipationRequestService;


Expand All @@ -27,6 +26,7 @@
public class PrivateEventController {
private final EventService eventService;
private final ParticipationRequestService participationRequestService;
private final RateService rateService;

@GetMapping("/events")
public List<EventShortDto> getUserEvents(@PathVariable @Positive Integer userId,
Expand Down Expand Up @@ -77,4 +77,38 @@ public EventRequestStatusUpdateResult updateRequestsStatus(
"пользователя с id={}", eventId, userId);
return participationRequestService.updateRequestsStatus(userId, eventId, eventRequestStatusUpdateRequest);
}

@PutMapping("/events/{eventId}/likes")
@ResponseStatus(HttpStatus.CREATED)
public void putMark(@PathVariable @Positive Integer userId,
@PathVariable @Positive Integer eventId,
@RequestParam @NotNull Boolean score) {
log.info("Запрос от private контроллера от пользователя с id={} на добавление реакции по событию с id={}", userId, eventId);
rateService.putMark(userId, eventId, score);
}

@DeleteMapping("/events/{eventId}/likes")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteMark(@PathVariable @Positive Integer userId,
@PathVariable @Positive Integer eventId) {
log.info("Запрос от private контроллера от пользователя с id={} на удаление реакции по событию с id={}", userId, eventId);
rateService.deleteMark(userId, eventId);
}

@GetMapping("/events/{eventId}/rating")
public EventFullDtoWithRating getUserEventWithRating(@PathVariable @Positive Integer userId,
@PathVariable @Positive Integer eventId) {
log.info("Запрос от private контроллера от пользователя с id={} на получение подробной информации о событии " +
"с указанием рейтинга события и его инициатора", userId);
return eventService.getEventOfUserWithRating(userId, eventId);
}

@GetMapping("/events/rating")
public List<EventShortDtoWithRating> getEventsWithRating(@PathVariable @Positive Integer userId,
@RequestParam(defaultValue = "0") @PositiveOrZero Integer from,
@RequestParam(defaultValue = "10") @Positive Integer size) {
log.info("Запрос от private контроллера от пользователя с id={} на получение списка событий с наличием рейтинга " +
"с указанием рейтингов событий и их инициаторов с сортировкой по убыванию рейтинга событий", userId);
return eventService.getEventsWithRating(userId, from, size);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
import ru.practicum.mainservice.model.enums.EventState;
import ru.practicum.mainservice.model.event.Event;
import ru.practicum.mainservice.model.event.Location;
import ru.practicum.mainservice.model.event.dto.EventFullDto;
import ru.practicum.mainservice.model.event.dto.EventShortDto;
import ru.practicum.mainservice.model.event.dto.NewEventDto;
import ru.practicum.mainservice.model.event.dto.*;
import ru.practicum.mainservice.model.user.User;

import java.time.LocalDateTime;
Expand All @@ -29,7 +27,8 @@ public static Event toEvent(NewEventDto newEventDto, User initiator, Category ca
LocalDateTime.now(),
newEventDto.getRequestModeration() != null ? newEventDto.getRequestModeration() : true,
EventState.PENDING,
newEventDto.getTitle() != null ? newEventDto.getTitle() : ""
newEventDto.getTitle() != null ? newEventDto.getTitle() : "",
0
);
}

Expand Down Expand Up @@ -81,4 +80,41 @@ public static EventShortDto toEventShortDto(Event event) {
0
);
}

public static EventFullDtoWithRating toEventFullDtoWithRating(Event event) {
return new EventFullDtoWithRating(
event.getId(),
event.getAnnotation(),
CategoryMapper.toCategoryDto(event.getCategory()),
event.getConfirmedRequests(),
event.getCreatedOn().format(Constants.DATE_TIME_FORMAT),
event.getDescription(),
event.getEventDate().format(Constants.DATE_TIME_FORMAT),
UserMapper.toUserShortDtoWithRating(event.getInitiator()),
LocationMapper.toLocationDto(event.getLocation()),
event.getPaid(),
event.getParticipantLimit(),
event.getPublishedOn().format(Constants.DATE_TIME_FORMAT),
event.getRequestModeration(),
event.getState().toString(),
event.getTitle(),
0,
event.getRating()
);
}

public static EventShortDtoWithRating toEventShortDtoWithRating(Event event) {
return new EventShortDtoWithRating(
event.getId(),
event.getAnnotation(),
CategoryMapper.toCategoryDto(event.getCategory()),
event.getConfirmedRequests(),
event.getEventDate().format(Constants.DATE_TIME_FORMAT),
UserMapper.toUserShortDtoWithRating(event.getInitiator()),
event.getPaid(),
event.getTitle(),
0,
event.getRating()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import ru.practicum.mainservice.model.user.User;
import ru.practicum.mainservice.model.user.dto.UserDto;
import ru.practicum.mainservice.model.user.dto.UserDtoWithRating;
import ru.practicum.mainservice.model.user.dto.UserShortDto;
import ru.practicum.mainservice.model.user.dto.UserShortDtoWithRating;

public class UserMapper {
public static UserDto toUserDto(User user) {
Expand All @@ -26,7 +28,25 @@ public static User toUser(UserDto userDto) {
return new User(
userDto.getId() != null ? userDto.getId() : 0,
userDto.getName() != null ? userDto.getName() : "",
userDto.getEmail() != null ? (userDto.getEmail()) : ""
userDto.getEmail() != null ? (userDto.getEmail()) : "",
0
);
}

public static UserShortDtoWithRating toUserShortDtoWithRating(User user) {
return new UserShortDtoWithRating(
user.getId(),
user.getName(),
user.getRating()
);
}

public static UserDtoWithRating toUserDtoWithRating(User user) {
return new UserDtoWithRating(
user.getId(),
user.getName(),
user.getName(),
user.getRating()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ public class Constants {
public static final int FREE_TIME_INTERVAL = 100;
public static final int UPDATE_TIME_LIMIT_ADMIN = 1;
public static final int UPDATE_TIME_LIMIT_USER = 2;
public static final int CHANGING_RATING_WHEN_CHANGING_MARK = 2;
public static final int RATING_CHANGE_AT_NEW_MARK_OR_DELETE_MARK = 1;
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,6 @@ public class Event {
private EventState state;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private int rating;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package ru.practicum.mainservice.model.event.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import ru.practicum.mainservice.model.category.dto.CategoryDto;
import ru.practicum.mainservice.model.user.dto.UserShortDtoWithRating;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class EventFullDtoWithRating {
private Integer id;
private String annotation;
private CategoryDto category;
private Integer confirmedRequests;
private String createdOn;
private String description;
private String eventDate;
private UserShortDtoWithRating initiator;
private LocationDto location;
private Boolean paid;
private int participantLimit;
private String publishedOn;
private Boolean requestModeration;
private String state;
private String title;
private int views;
private int rating;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package ru.practicum.mainservice.model.event.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import ru.practicum.mainservice.model.category.dto.CategoryDto;
import ru.practicum.mainservice.model.user.dto.UserShortDtoWithRating;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class EventShortDtoWithRating {
protected Integer id;
protected String annotation;
protected CategoryDto category;
protected Integer confirmedRequests;
protected String eventDate;
protected UserShortDtoWithRating initiator;
protected Boolean paid;
protected String title;
protected int views;
protected int rating;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package ru.practicum.mainservice.model.rate;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.type.NumericBooleanConverter;
import ru.practicum.mainservice.model.event.Event;
import ru.practicum.mainservice.model.user.User;

@Entity
@Table(name = "MARKS", schema = "PUBLIC")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Rate {
@Id
@Column(name = "MARK_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@JoinColumn(name = "EVALUATOR_ID")
private User evaluator;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@JoinColumn(name = "EVENT_ID")
private Event event;
@Column(nullable = false)
@Convert(converter = NumericBooleanConverter.class)
private Boolean score;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ public class User {
private String name;
@Column(nullable = false)
private String email;
@Column(nullable = false)
private int rating;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ru.practicum.mainservice.model.user.dto;

import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class UserDtoWithRating {
private int id;
private String name;
private String email;
private int rating;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ru.practicum.mainservice.model.user.dto;

import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserShortDtoWithRating {
private int id;
private String name;
private int rating;
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,9 @@ Page<Event> findByParametersForAdmin(@Param("users") List<Integer> users,
@Param("categories") List<Integer> categories,
@Param("start") LocalDateTime rangeStart,
@Param("end") LocalDateTime rangeEnd, Pageable pageable);

@Query("SELECT e FROM Event AS e " +
"WHERE e.rating <> 0 " +
"ORDER BY e.rating DESC")
Page<Event> findAllWhereRatingNotEqualToZeroSortByRatingDesc(Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package ru.practicum.mainservice.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import ru.practicum.mainservice.model.rate.Rate;

public interface RateRepository extends JpaRepository<Rate, Integer> {

Rate findOneByEvaluator_IdAndEvent_Id(int evaluatorId, int eventId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,9 @@ public interface UserRepository extends JpaRepository<User, Integer> {
Page<User> findUsersForAdmin(@Param("ids") List<Integer> ids, Pageable pageable);

List<User> findAllByEmail(String email);

@Query("SELECT u FROM User AS u " +
"WHERE u.rating <> 0 " +
"ORDER BY u.rating")
Page<User> findAllWhereRatingNotEqualToZeroSortByRating(Pageable pageable);
}
Loading