Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add item requests #39

Closed
wants to merge 2 commits into from
Closed
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
10 changes: 9 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
</dependency>




<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
Expand Down Expand Up @@ -84,8 +86,14 @@
<artifactId>postgresql</artifactId>
<version>42.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
<scope>test</scope>
</dependency>

</dependencies>
</dependencies>

<build>
<resources>
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/ru/practicum/shareit/booking/Booking.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;

Expand All @@ -15,7 +15,8 @@
@Getter
@Setter
@NoArgsConstructor
@ToString

@Accessors(chain = true)
@Table(name = "bookings")
public class Booking {

Expand Down
21 changes: 16 additions & 5 deletions src/main/java/ru/practicum/shareit/booking/BookingController.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import ru.practicum.shareit.user.service.UserService;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(path = "/bookings")
Expand Down Expand Up @@ -37,14 +38,24 @@ public BookingDto getBookingById(@RequestHeader("X-Sharer-User-Id") int userId,

@GetMapping()
public List<BookingDto> getAllBookingCurrentUser(@RequestHeader("X-Sharer-User-Id") int userId,
@RequestParam(name = "state", defaultValue = "ALL") String state) {
return bookingService.getAllBookingCurrentUser(userId, state);
@RequestParam(name = "state", required = false,
defaultValue = "ALL") String state,
@RequestParam(name = "from", required = false)
Optional<Integer> from,
@RequestParam(name = "size", required = false)
Optional<Integer> size) {

return bookingService.getAllBookingCurrentUser(userId, state, from, size);
}


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

}
4 changes: 4 additions & 0 deletions src/main/java/ru/practicum/shareit/booking/BookingMapper.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package ru.practicum.shareit.booking;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.practicum.shareit.booking.dto.BookingDto;
import ru.practicum.shareit.item.ItemMapper;
import ru.practicum.shareit.user.UserMapper;

@Component
@Getter
@Setter
public class BookingMapper {
@Autowired
private ItemMapper itemMapper;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package ru.practicum.shareit.booking.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import ru.practicum.shareit.booking.Booking;
import ru.practicum.shareit.item.model.Item;
Expand All @@ -13,5 +16,12 @@ public interface BookingRepository extends JpaRepository<Booking, Integer> {
List<Booking> findByBookerEquals(User user);

List<Booking> findByItemEquals(Item item);

@Query(value = "SELECT * FROM bookings WHERE user_id = ?1 ORDER BY id DESC", nativeQuery = true)
Page<Booking> findByBookerIdWithPagination(int userId, Pageable pageable);

Page<Booking> findByItemOwnerId(int userId, Pageable pageable);


}

Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@
import ru.practicum.shareit.booking.dto.BookingDto;

import java.util.List;
import java.util.Optional;

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

BookingDto getBookingById(int bookingId, int userId);

List<BookingDto> getAllBookingCurrentUser(int userId, String state);
List<BookingDto> getAllBookingCurrentUser(int userId, String state, Optional<Integer> from, Optional<Integer> size);

List<BookingDto> getAllBookingCurrentOwner(int userId, String state);
List<BookingDto> getAllBookingCurrentOwner(int userId, String state, Optional<Integer> from, Optional<Integer> size);

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

import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import ru.practicum.shareit.booking.Booking;
import ru.practicum.shareit.booking.BookingMapper;
Expand All @@ -18,9 +21,11 @@
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Accessors(chain = true)
public class BookingServiceImpl implements BookingService {

@Autowired
Expand Down Expand Up @@ -68,14 +73,28 @@ public BookingDto getBookingById(int bookingId, int userId) {
}

@Override
public List<BookingDto> getAllBookingCurrentUser(int userId, String state) {
public List<BookingDto> getAllBookingCurrentUser(int userId, String state, Optional<Integer> from,
Optional<Integer> size) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new NoDataFoundException("Пользователь с id:" + userId + " не найден."));
switch (state) {
case "ALL":
return bookingRepository.findByBookerEquals(user).stream().sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).map(e -> bookingMapper.bookingDto(e))
.collect(Collectors.toList());
if (from.isPresent() && size.isPresent()) {
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
return bookingRepository.findByBookerIdWithPagination(userId,
PageRequest.of((int) Math.ceil(from.get() / size.get()),
size.get())).getContent()
.stream().sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.map(e -> bookingMapper.bookingDto(e))
.collect(Collectors.toList());
} else {
throw new UnavailableItemException("Не допустимое значение.");
}
} else {
return bookingRepository.findByBookerEquals(user).stream().sorted((e1, e2) ->
e2.getStart().compareTo(e1.getStart())).map(e -> bookingMapper.bookingDto(e))
.collect(Collectors.toList());
}
case "REJECTED":
return bookingRepository.findByBookerEquals(user).stream()
.filter(e -> e.getStatus().toString().equals("REJECTED")).sorted((e1, e2) ->
Expand Down Expand Up @@ -107,9 +126,9 @@ public List<BookingDto> getAllBookingCurrentUser(int userId, String state) {
}
}


@Override
public List<BookingDto> getAllBookingCurrentOwner(int userId, String state) {
public List<BookingDto> getAllBookingCurrentOwner(int userId, String state,
Optional<Integer> from, Optional<Integer> size) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new NoDataFoundException("Пользователь с id:" + userId + " не найден."));
List<Booking> ownerBookingList = new ArrayList<>();
Expand All @@ -119,8 +138,20 @@ public List<BookingDto> getAllBookingCurrentOwner(int userId, String state) {
}
switch (state) {
case "ALL":
return ownerBookingList.stream().sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.map(e -> bookingMapper.bookingDto(e)).collect(Collectors.toList());
if (from.isPresent() && size.isPresent()) {
if (from.isPresent() && from.get() >= 0 && size.isPresent() && size.get() > 0) {
return bookingRepository.findByItemOwnerId(userId,
PageRequest.of((int) Math.ceil(from.get() / size.get()),
size.get(), Sort.by("id").descending()))
.getContent().stream()
.map(e -> bookingMapper.bookingDto(e)).collect(Collectors.toList());
} else {
throw new UnavailableItemException("Не допустимое значение.");
}
} else {
return ownerBookingList.stream().sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
.map(e -> bookingMapper.bookingDto(e)).collect(Collectors.toList());
}
case "REJECTED":
return ownerBookingList.stream().filter(e -> e.getStatus().toString().equals("REJECTED"))
.sorted((e1, e2) -> e2.getStart().compareTo(e1.getStart()))
Expand Down Expand Up @@ -158,7 +189,6 @@ public Booking getBookingByOwner(int bookingId, int userId) {
throw new NoDataFoundException("Подтверждение или отклонение бронирования может осуществлять" +
"только владелец вещи.");
}

}

@Override
Expand Down
50 changes: 50 additions & 0 deletions src/main/java/ru/practicum/shareit/constants/MyConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,54 @@ public class MyConstants {

public static final String SEARCH_ITEM_POINTCUT = "execution(public java.util.List<ru.practicum.shareit.item.dto.ItemDto> " +
"ru.practicum.shareit.item.service.ItemServiceImpl.searchItem(..))";

public static final String SHEMA_SQL = "DROP TABLE IF EXISTS comments;\n" +
"DROP TABLE IF EXISTS bookings;\n" +
"DROP TABLE IF EXISTS items;\n" +
"DROP TABLE IF EXISTS requests;\n" +
"DROP TABLE IF EXISTS users;\n" +
"\n" +
"\n" +
"CREATE TABLE IF NOT EXISTS users(\n" +
"id INTEGER GENERATED ALWAYS AS IDENTITY,\n" +
"name varchar(250) NOT NULL,\n" +
"email varchar(250)NOT NULL,\n" +
"CONSTRAINT pk_user PRIMARY KEY (id),\n" +
"CONSTRAINT UQ_USER_EMAIL UNIQUE (email));\n" +
"\n" +
"CREATE TABLE IF NOT EXISTS requests(\n" +
"id INTEGER GENERATED ALWAYS AS IDENTITY,\n" +
"requester_id INTEGER REFERENCES users(id),\n" +
"description VARCHAR(2000),\n" +
"created TIMESTAMP WITHOUT TIME ZONE,\n" +
"CONSTRAINT request_id PRIMARY KEY(id)\n" +
");\n" +
"\n" +
"CREATE TABLE IF NOT EXISTS items(\n" +
"id INTEGER GENERATED ALWAYS AS IDENTITY,\n" +
"name VARCHAR(250) NOT NULL,\n" +
"description VARCHAR(500) NOT NULL,\n" +
"available BOOLEAN NOT NULL,\n" +
"owner_id INTEGER REFERENCES users(id),\n" +
"request_id INTEGER REFERENCES requests(id),\n" +
"CONSTRAINT item_id PRIMARY KEY(id));\n" +
"\n" +
"CREATE TABLE IF NOT EXISTS bookings(\n" +
"id INTEGER GENERATED ALWAYS AS IDENTITY,\n" +
"start_time TIMESTAMP WITHOUT TIME ZONE,\n" +
"end_time TIMESTAMP WITHOUT TIME ZONE,\n" +
"item_id INTEGER REFERENCES items(id),\n" +
"user_id INTEGER REFERENCES users(id),\n" +
"status VARCHAR(15),\n" +
"CONSTRAINT booking_id PRIMARY KEY(id));\n" +
"\n" +
"CREATE TABLE IF NOT EXISTS comments(\n" +
"id INTEGER GENERATED ALWAYS AS IDENTITY,\n" +
"text VARCHAR(1000),\n" +
"item_id INTEGER REFERENCES items(id) ON UPDATE CASCADE,\n" +
"author INTEGER REFERENCES users(id) ON UPDATE CASCADE,\n" +
"created TIMESTAMP WITHOUT TIME ZONE,\n" +
"CONSTRAINT comments_id PRIMARY KEY(id)\n" +
");";

}
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,5 @@ public ErrorResponse unavailableState(UnavailableStateException e) {
public ErrorResponse postWithoutBooking(PostWithoutBookingException e) {
return new ErrorResponse(e.getMessage(), "Пользователь не может оставить комментарий к данной вещи.");
}

}
2 changes: 2 additions & 0 deletions src/main/java/ru/practicum/shareit/item/Comment.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import ru.practicum.shareit.item.model.Item;
import ru.practicum.shareit.user.User;

Expand All @@ -13,6 +14,7 @@
@Entity
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@Table(name = "comments")
public class Comment {
Expand Down
17 changes: 13 additions & 4 deletions src/main/java/ru/practicum/shareit/item/ItemController.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/items")
Expand All @@ -29,8 +30,12 @@ public ItemDto getItemById(@PathVariable(name = "id") int itemId, @RequestHeader
}

@GetMapping
public List<ItemDto> getAllItemForOwner(@RequestHeader("X-Sharer-User-Id") int userId) {
return itemService.getAllItemForOwner(userId);
public List<ItemDto> getAllItemForOwner(@RequestHeader("X-Sharer-User-Id") int userId,
@RequestParam(name = "from", required = false)
Optional<Integer> from,
@RequestParam(name = "size", required = false)
Optional<Integer> size) {
return itemService.getAllItemForOwner(userId, from, size);
}

@PatchMapping("/{id}")
Expand All @@ -41,8 +46,12 @@ public ItemDto updateItem(@RequestHeader("X-Sharer-User-Id") int userId,
}

@GetMapping("/search")
public List<ItemDto> searchItem(@RequestParam(name = "text") String request) {
return itemService.searchItem(request);
public List<ItemDto> searchItem(@RequestParam(name = "text") String request,
@RequestParam(name = "from", required = false)
Optional<Integer> from,
@RequestParam(name = "size", required = false)
Optional<Integer> size) {
return itemService.searchItem(request, from, size);
}

@PostMapping("/{itemId}/comment")
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/ru/practicum/shareit/item/ItemMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ public ItemDto itemDto(Item item) {
return new ItemDto()
.setId(item.getId())
.setName(item.getName())
.setRequestId(item.getRequestId())
.setOwnerId(item.getOwnerId())
.setRequest(item.getRequest())
.setDescription(item.getDescription())
.setAvailable(item.getAvailable());
}
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/ru/practicum/shareit/item/dao/ItemRepository.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
package ru.practicum.shareit.item.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import ru.practicum.shareit.item.model.Item;

import java.util.List;

@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {

List<Item> findByOwnerId(int ownerId);

Page<Item> findByOwnerId(int ownerId, Pageable pageable);

List<Item> findByRequestId(int requestId);

List<Item> findByNameIgnoreCaseContaining(String request);

@Query(value = "SELECT * FROM items WHERE LOWER(name) LIKE LOWER(concat('%', ?1, '%')) or LOWER(description) " +
"LIKE LOWER(concat('%', ?1, '%'))", nativeQuery = true)
Page<Item> findByNameOrDescriptionWithPagination(String request, Pageable pageable);

List<Item> findByDescriptionIgnoreCaseContaining(String request);

}
Loading
Loading