Skip to content

Commit

Permalink
refactor: создать shema.sql, exception UnavailableStateException.java…
Browse files Browse the repository at this point in the history
…, UnavailableItemException.java, PostWithoutBookingException.java, BookingServiceImpl, BookingController
  • Loading branch information
SergeyMalyuga committed Nov 14, 2023
1 parent 4ec25c5 commit aa9e0bc
Show file tree
Hide file tree
Showing 32 changed files with 766 additions and 333 deletions.
14 changes: 14 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.6.0</version>
</dependency>

</dependencies>

<build>
Expand Down
16 changes: 8 additions & 8 deletions src/main/java/ru/practicum/shareit/aspects/LoggingAspect.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.springframework.stereotype.Component;
import ru.practicum.shareit.constants.MyConstants;
import ru.practicum.shareit.item.dto.ItemDto;
import ru.practicum.shareit.user.User;
import ru.practicum.shareit.user.dto.UserDto;

import java.util.List;
Expand All @@ -17,10 +18,9 @@
@Aspect
@Slf4j
public class LoggingAspect {

@AfterReturning(pointcut = MyConstants.ADD_USER_POINTCUT, returning = "userDto")
public void afterReturningAddUserAdvices(UserDto userDto) {
log.info("Пользователь " + userDto + "добавлен.");
@AfterReturning(pointcut = MyConstants.ADD_USER_POINTCUT, returning = "user")
public void afterReturningAddUserAdvices(User user) {
log.info("Пользователь " + user + "добавлен.");
}

@AfterThrowing(pointcut = MyConstants.ADD_USER_POINTCUT, throwing = "exception")
Expand All @@ -29,9 +29,9 @@ public void afterThrowingAddUserAdvices(JoinPoint joinPoint, Throwable exception
log.info("В методе " + methodSignature.getMethod() + " выброшено исключение: " + exception.getMessage());
}

@AfterReturning(pointcut = MyConstants.REMOVE_USER_POINTCUT, returning = "response")
public void afterReturningRemoveUserByIdAdvices(String response) {
log.info(response);
@AfterReturning(pointcut = MyConstants.REMOVE_USER_POINTCUT)
public void afterReturningRemoveUserByIdAdvices() {
log.info("Пользователь удалён.");
}

@AfterThrowing(pointcut = MyConstants.REMOVE_USER_POINTCUT, throwing = "exception")
Expand All @@ -42,7 +42,7 @@ public void afterThrowingRemoveUserByIdAdvices(JoinPoint joinPoint, Throwable ex

@AfterReturning(pointcut = MyConstants.GET_ALL_USERS_POINTCUT)
public void afterReturningGetAllUserAdvice() {
log.info("Список всех пользователей получен.");
log.info("Получен список всех пользователей.");
}

@AfterReturning(pointcut = MyConstants.UPDATE_USER_POINTCUT, returning = "userDto")
Expand Down
19 changes: 18 additions & 1 deletion src/main/java/ru/practicum/shareit/booking/Booking.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,34 @@
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;

import javax.persistence.*;
import java.time.LocalDateTime;

@Data
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "bookings")
public class Booking {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "start_time")
private LocalDateTime start;
@Column(name = "end_time")
private LocalDateTime end;
@Transient
private int itemId;
@Enumerated(value = EnumType.STRING)
private BookingStatus status;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "item_id")
private Item item;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User booker;
private BookingStatus status;
@Transient
int bookerId;
}
47 changes: 42 additions & 5 deletions src/main/java/ru/practicum/shareit/booking/BookingController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,49 @@
package ru.practicum.shareit.booking;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ru.practicum.shareit.booking.service.BookingService;
import ru.practicum.shareit.user.service.UserService;

import java.util.List;

/**
* TODO Sprint add-bookings.
*/
@RestController
@RequestMapping(path = "/bookings")
public class BookingController {

@Autowired
private BookingService bookingService;
@Autowired
private UserService userService;

@PostMapping
public Booking addBooking(@RequestBody Booking booking, @RequestHeader("X-Sharer-User-Id") int userId) {
userService.getUserById(userId);
return bookingService.addBooking(booking, userId);
}

@PatchMapping("/{bookingId}")
public Booking confirmationOrRejectionBooking(@PathVariable int bookingId,
@RequestHeader("X-Sharer-User-Id") int userId,
@RequestParam(name = "approved") String bookingStatus) {
return bookingService.confirmationOrRejectionBooking(bookingId, userId, bookingStatus);
}

@GetMapping("/{bookingId}")
public Booking getBookingById(@RequestHeader("X-Sharer-User-Id") int userId, @PathVariable int bookingId) {
return bookingService.getBookingById(bookingId, userId);
}

@GetMapping()
public List<Booking> getAllBookingCurrentUser(@RequestHeader("X-Sharer-User-Id") int userId,
@RequestParam(name = "state", defaultValue = "ALL") String state) {
return bookingService.getAllBookingCurrentUser(userId, state);
}

@GetMapping("/owner")
public List<Booking> getAllBookingCurrentOwner(@RequestHeader("X-Sharer-User-Id") int userId,
@RequestParam(name = "state", defaultValue = "ALL") String state) {
return bookingService.getAllBookingCurrentOwner(userId, state);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ru.practicum.shareit.booking.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ru.practicum.shareit.booking.Booking;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;

import java.util.List;

@Repository
public interface BookingRepository extends JpaRepository<Booking, Integer> {
List<Booking> findByBookerEquals(User user);

List<Booking> findByItemEquals(Item item);
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package ru.practicum.shareit.booking.service;

import ru.practicum.shareit.booking.Booking;

import java.util.List;

public interface BookingService {
Booking addBooking(Booking booking, int bookerId);

Booking getBookingById(int bookingId, int userId);

List<Booking> getAllBookingCurrentUser(int userId, String state);

List<Booking> getAllBookingCurrentOwner(int userId, String state);

Booking confirmationOrRejectionBooking(int bookingId, int userId, String bookingStatus);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
package ru.practicum.shareit.booking.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.practicum.shareit.booking.Booking;
import ru.practicum.shareit.booking.BookingStatus;
import ru.practicum.shareit.booking.dao.BookingRepository;
import ru.practicum.shareit.exception.NoDataFoundException;
import ru.practicum.shareit.exception.UnavailableItemException;
import ru.practicum.shareit.exception.UnavailableStateException;
import ru.practicum.shareit.item.dao.ItemRepository;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;
import ru.practicum.shareit.user.dao.UserRepository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class BookingServiceImpl implements BookingService {

@Autowired
private BookingRepository bookingRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ItemRepository itemRepository;

@Override
public Booking addBooking(Booking booking, int bookerId) {
Optional<Item> optional = itemRepository.findById(booking.getItemId());
Optional<User> optionalUser = userRepository.findById(bookerId);
if (optional.isPresent() && optionalUser.isPresent()) {
Item item = optional.get();
User user = optionalUser.get();
booking.setBooker(user);
booking.setItem(item);
item.getBookingList().add(booking);
LocalDateTime start = booking.getStart();
LocalDateTime end = booking.getEnd();
if (item.getOwnerId() == bookerId) {
throw new NoDataFoundException("Владелец вещи не может разместить заказ на свою же вещь.");
}
if (item.getAvailable().toString().equals("true") && start != null && end != null && start.isBefore(end)
&& end.isAfter(start) && !start.isBefore(LocalDateTime.now())) {
booking.setStatus(BookingStatus.WAITING);
} else {
throw new UnavailableItemException(item.getName() + " статус " + item.getAvailable());
}
} else {
throw new NoDataFoundException("Item с id: " + booking.getItemId() + " не найдена.");
}
return bookingRepository.save(booking);
}

@Override
public Booking getBookingById(int bookingId, int userId) {
Optional<Booking> optional = bookingRepository.findById(bookingId);
if (optional.isPresent()) {
Booking booking = optional.get();
if (booking.getBooker().getId() == userId || booking.getItem().getOwnerId() == userId) {
return optional.get();
} else {
throw new NoDataFoundException("Booking с id: " + bookingId + " не найден.");
}
} else {
throw new NoDataFoundException("Booking с id: " + bookingId + " не найден.");
}
}

@Override
public List<Booking> getAllBookingCurrentUser(int userId, String state) {
Optional<User> optionalUser = userRepository.findById(userId);
if (optionalUser.isPresent()) {
switch (state) {
case "ALL":
return bookingRepository.findByBookerEquals(optionalUser.get()).stream().sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).collect(Collectors.toList());
case "REJECTED":
return bookingRepository.findByBookerEquals(optionalUser.get()).stream()
.filter(e -> e.getStatus().toString().equals("REJECTED")).sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).collect(Collectors.toList());
case "WAITING":
return bookingRepository.findByBookerEquals(optionalUser.get()).stream()
.filter(e -> e.getStatus().toString().equals("WAITING")).sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).collect(Collectors.toList());
case "FUTURE":
return bookingRepository.findByBookerEquals(optionalUser.get()).stream()
.filter(e -> e.getStart().isAfter(LocalDateTime.now())).sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).collect(Collectors.toList());
case "PAST":
return bookingRepository.findByBookerEquals(optionalUser.get()).stream()
.filter(e -> e.getEnd().isBefore(LocalDateTime.now())).sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).collect(Collectors.toList());
case "CURRENT":
return bookingRepository.findByBookerEquals(optionalUser.get()).stream()
.filter(e -> e.getStart().isBefore(LocalDateTime.now())
&& e.getEnd().isAfter(LocalDateTime.now())).sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).collect(Collectors.toList());
default:
throw new UnavailableStateException("Unknown state: UNSUPPORTED_STATUS");
}
} else {
throw new NoDataFoundException("Пользователь с id:" + userId + " не найден.");
}
}

@Override
public List<Booking> getAllBookingCurrentOwner(int userId, String state) { //TODO
Optional<User> optionalUser = userRepository.findById(userId);
List<Booking> ownerBookingList = new ArrayList<>();
if (optionalUser.isPresent()) {
List<Item> optionalItem = itemRepository.findByOwnerIdEquals(userId);
for (Item item : optionalItem) {
ownerBookingList.addAll(bookingRepository.findByItemEquals(item));
}
switch (state) {
case "ALL":
return ownerBookingList.stream().sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.collect(Collectors.toList());
case "REJECTED":
return ownerBookingList.stream().filter(e -> e.getStatus().toString().equals("REJECTED"))
.sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.collect(Collectors.toList());
case "WAITING":
return ownerBookingList.stream().filter(e -> e.getStatus().toString().equals("WAITING"))
.sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.collect(Collectors.toList());
case "FUTURE":
return ownerBookingList.stream().filter(e -> e.getStart().isAfter(LocalDateTime.now()))
.sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.collect(Collectors.toList());
case "PAST":
return ownerBookingList.stream().filter(e -> e.getEnd().isBefore(LocalDateTime.now()))
.sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.collect(Collectors.toList());
case "CURRENT":
return ownerBookingList.stream().filter(e -> e.getStart().isBefore(LocalDateTime.now())
&& e.getEnd().isAfter(LocalDateTime.now()))
.sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.collect(Collectors.toList());
default:
throw new UnavailableItemException("Unknown state: UNSUPPORTED_STATUS");
}
} else {
throw new NoDataFoundException("Пользователь с id:" + userId + " не найден.");
}
}

public Booking getBookingByOwner(int bookingId, int userId) {
Optional<Booking> optional = bookingRepository.findById(bookingId);
Optional<User> optionalUser = userRepository.findById(userId);
if (optional.isPresent() && optionalUser.isPresent()) {
if (optionalUser.get().getId() == optional.get().getItem().getOwnerId()) {
return optional.get();
} else {
throw new NoDataFoundException("Подтверждение или отклонение бронирования может осуществлять" +
"только владелец вещи.");
}
} else {
throw new NoDataFoundException("Пользователя или владельца вещи не существует.");
}
}

@Override
public Booking confirmationOrRejectionBooking(int bookingId, int userId, String bookingStatus) {
Booking booking = getBookingByOwner(bookingId, userId);
switch (bookingStatus) {
case "true":
if (booking.getStatus().toString().equals("APPROVED")) {
throw new UnavailableItemException("Статус уже был присвоен.");
}
booking.setStatus(BookingStatus.APPROVED);
bookingRepository.save(booking);
return booking;
case "false":
booking.setStatus(BookingStatus.REJECTED);
bookingRepository.save(booking);
return booking;
}
return booking;
}
}
Loading

0 comments on commit aa9e0bc

Please sign in to comment.