Полностью готовая 3 лаба

This commit is contained in:
Илья 2024-05-10 14:37:56 +04:00
parent bb3b42bf2d
commit 631b60fc4b
11 changed files with 107 additions and 228 deletions

View File

@ -86,22 +86,18 @@ public class DemoApplication implements CommandLineRunner {
.create(new UserEntity("TestUser", "user53262@gmail.com", "lawy7728", "user"));
log.info("Create default orders values");
final var order1 = orderService
orderService
.create(user1.getId(), new OrderEntity("Выполняется",
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36"));
final var order2 = orderService
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36"),
Map.of(book1.getId(), 3, book3.getId(), 1, book5.getId(), 2));
orderService
.create(user2.getId(),
new OrderEntity("Выдан", "Томская область, город Мытищи, ул. Балканская, 25"));
final var order3 = orderService
new OrderEntity("Выдан", "Томская область, город Мытищи, ул. Балканская, 25"),
Map.of(book4.getId(), 5));
orderService
.create(user3.getId(),
new OrderEntity("Готов", "Челябинская область, город Раменское, пр. Гоголя, 31"));
orderService.addOrderBooks(user1.getId(), order1.getId(),
Map.of(book1.getId(), 3, book3.getId(), 1, book5.getId(), 2));
orderService.addOrderBooks(user2.getId(), order2.getId(),
Map.of(book4.getId(), 5));
orderService.addOrderBooks(user3.getId(), order3.getId(),
Map.of(book2.getId(), 1, book4.getId(), 1));
new OrderEntity("Готов", "Челябинская область, город Раменское, пр. Гоголя, 31"),
Map.of(book2.getId(), 1, book4.getId(), 1));
}
}
}

View File

@ -227,7 +227,7 @@ public class BookEntity extends BaseEntity {
@Override
public int hashCode() {
return Objects.hash(id, category, title, author, price, count, description, annotation, bookCode, publisher,
series, publicationYear, pagesNum, size, coverType, circulation, weight, image, orderBooks);
series, publicationYear, pagesNum, size, coverType, circulation, weight, image);
}
@Override
@ -254,7 +254,6 @@ public class BookEntity extends BaseEntity {
&& Objects.equals(other.getCoverType(), coverType)
&& Objects.equals(other.getCirculation(), circulation)
&& Objects.equals(other.getWeight(), weight)
&& Objects.equals(other.getImage(), image)
&& Objects.equals(other.getOrderBooks(), orderBooks);
&& Objects.equals(other.getImage(), image);
}
}

View File

@ -4,10 +4,15 @@ import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.backend.orders.api.OrderDto;
import com.example.backend.orders.model.OrderEntity;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
ModelMapper modelMapper = new ModelMapper();
modelMapper.typeMap(OrderEntity.class, OrderDto.class).addMappings(mapper -> mapper.skip(OrderDto::setBooks));
return modelMapper;
}
}

View File

@ -8,7 +8,7 @@ public final class Formatter {
private Formatter() {
}
private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String format(Date date) {
return dateFormatter.format(date);

View File

@ -0,0 +1,22 @@
package com.example.backend.orders.api;
public class OrderBookDto {
private Long bookId;
private Integer count;
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

@ -2,15 +2,15 @@ package com.example.backend.orders.api;
import java.text.ParseException;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@ -43,6 +43,10 @@ public class OrderController {
dto.setDate(Formatter.format(entity.getDate()));
dto.setSum(orderService.getSum(entity.getUser().getId(), entity.getId()));
dto.setCount(orderService.getFullCount(entity.getUser().getId(), entity.getId()));
dto.setBooks(orderService.getOrderBooks(entity.getUser().getId(), entity
.getId()).stream()
.map(orderBook -> toBookDto(orderBook.getBook()))
.toList());
return dto;
}
@ -75,15 +79,10 @@ public class OrderController {
public OrderDto create(
@PathVariable(name = "user") Long userId,
@RequestBody @Valid OrderDto dto) throws ParseException {
return toDto(orderService.create(userId, toEntity(dto)));
}
@PutMapping("/{id}")
public OrderDto update(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestBody @Valid OrderDto dto) throws ParseException {
return toDto(orderService.update(userId, id, toEntity(dto)));
dto.setDate(Formatter.format(new Date()));
Map<Long, Integer> booksIdsCount = dto.getOrderInfo().stream()
.collect(Collectors.toMap(OrderBookDto::getBookId, OrderBookDto::getCount));
return toDto(orderService.create(userId, toEntity(dto), booksIdsCount));
}
@DeleteMapping("/{id}")
@ -92,52 +91,4 @@ public class OrderController {
@PathVariable(name = "id") Long id) {
return toDto(orderService.delete(userId, id));
}
@GetMapping("/{id}/book")
public List<BookDto> getOrderBooks(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id) {
return orderService.getOrderBooks(userId, id).stream()
.map(this::toBookDto)
.toList();
}
@PostMapping("/{id}/book")
public List<BookDto> addBooks(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestBody Map<Long, Integer> booksIdsCount) {
return orderService.addOrderBooks(userId, id, booksIdsCount).stream()
.map(this::toBookDto)
.toList();
}
@PutMapping("/{id}/book")
public List<BookDto> changeBooksCount(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestBody Map<Long, Integer> booksIdsCount) {
return orderService.changeBooksCount(userId, id, booksIdsCount).stream()
.map(this::toBookDto)
.toList();
}
@DeleteMapping("/{id}/book")
public List<BookDto> deleteOrderBooks(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id,
@RequestParam(name = "books", defaultValue = "") List<Long> booksIds) {
return orderService.deleteOrderBooks(userId, id, booksIds).stream()
.map(this::toBookDto)
.toList();
}
@DeleteMapping("/{id}/book/all")
public List<BookDto> deleteAllOrderBooks(
@PathVariable(name = "user") Long userId,
@PathVariable(name = "id") Long id) {
return orderService.deleteAllOrderBooks(userId, id).stream()
.map(this::toBookDto)
.toList();
}
}

View File

@ -1,7 +1,10 @@
package com.example.backend.orders.api;
import com.example.backend.books.api.BookDto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import jakarta.validation.constraints.NotBlank;
public class OrderDto {
@ -12,12 +15,15 @@ public class OrderDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer count;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@NotBlank
private String date;
@NotBlank
private String status;
@NotBlank
private String shippingAddress;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private List<OrderBookDto> orderInfo;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private List<BookDto> books;
public Long getId() {
return id;
@ -66,4 +72,20 @@ public class OrderDto {
public void setShippingAddress(String shippingAddress) {
this.shippingAddress = shippingAddress;
}
public List<OrderBookDto> getOrderInfo() {
return orderInfo;
}
public void setOrderInfo(List<OrderBookDto> orderInfo) {
this.orderInfo = orderInfo;
}
public List<BookDto> getBooks() {
return books;
}
public void setBooks(List<BookDto> books) {
this.books = books;
}
}

View File

@ -98,7 +98,7 @@ public class OrderEntity extends BaseEntity {
@Override
public int hashCode() {
return Objects.hash(id, user.getId(), date, status, shippingAddress, orderBooks);
return Objects.hash(id, user.getId(), date, status, shippingAddress);
}
@Override
@ -112,7 +112,6 @@ public class OrderEntity extends BaseEntity {
&& Objects.equals(other.getUser().getId(), user.getId())
&& Objects.equals(other.getDate(), date)
&& Objects.equals(other.getStatus(), status)
&& Objects.equals(other.getShippingAddress(), shippingAddress)
&& Objects.equals(other.getOrderBooks(), orderBooks);
&& Objects.equals(other.getShippingAddress(), shippingAddress);
}
}

View File

@ -2,7 +2,6 @@ package com.example.backend.orders.service;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@ -14,10 +13,10 @@ import com.example.backend.core.error.NotFoundException;
import com.example.backend.orders.model.OrderEntity;
import com.example.backend.orders.repository.OrderRepository;
import com.example.backend.books.model.BookEntity;
import com.example.backend.books.service.BookService;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.service.UserService;
import com.example.backend.ordersbooks.model.OrderBookEntity;
import com.example.backend.books.service.BookService;
@Service
public class OrderService {
@ -52,24 +51,23 @@ public class OrderService {
}
@Transactional
public OrderEntity create(long userId, OrderEntity entity) {
public OrderEntity create(long userId, OrderEntity entity, Map<Long, Integer> booksIdsCount) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
final UserEntity existsUser = userService.get(userId);
entity.setUser(existsUser);
List<BookEntity> result = bookService.getAll(0L).stream()
.filter(book -> booksIdsCount.containsKey(book.getId()))
.toList();
result.forEach(book -> {
final OrderBookEntity orderBook = new OrderBookEntity(entity, book, booksIdsCount.get(book.getId()));
orderBook.setOrder(entity);
orderBook.setBook(book);
});
return repository.save(entity);
}
@Transactional
public OrderEntity update(long userId, long id, OrderEntity entity) {
userService.get(userId);
final OrderEntity existsEntity = get(userId, id);
existsEntity.setStatus(entity.getStatus());
existsEntity.setShippingAddress(entity.getShippingAddress());
return repository.save(existsEntity);
}
@Transactional
public OrderEntity delete(long userId, long id) {
userService.get(userId);
@ -78,14 +76,6 @@ public class OrderService {
return existsEntity;
}
@Transactional(readOnly = true)
public List<BookEntity> getOrderBooks(long userId, long id) {
userService.get(userId);
return get(userId, id).getOrderBooks().stream()
.map(OrderBookEntity::getBook)
.toList();
}
@Transactional(readOnly = true)
public Double getSum(long userId, long id) {
userService.get(userId);
@ -102,74 +92,10 @@ public class OrderService {
.sum();
}
@Transactional
public List<BookEntity> addOrderBooks(
long userId,
long id,
Map<Long, Integer> booksIdsCount) {
@Transactional(readOnly = true)
public List<OrderBookEntity> getOrderBooks(long userId, long id) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
List<BookEntity> result = bookService.getAll(0L).stream()
.filter(book -> booksIdsCount.containsKey(book.getId()))
.toList();
result.forEach(book -> {
final OrderBookEntity orderBook = new OrderBookEntity(existsOrder, book, booksIdsCount.get(book.getId()));
orderBook.setOrder(existsOrder);
orderBook.setBook(book);
});
repository.save(existsOrder);
return result;
}
@Transactional
public List<BookEntity> changeBooksCount(
long userId,
long id,
Map<Long, Integer> booksIdsCount) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
List<BookEntity> result = existsOrder.getOrderBooks().stream()
.filter(book -> Objects.nonNull(book.getBook()))
.filter(book -> booksIdsCount.containsKey(book.getBook().getId()))
.map(book -> {
Integer newCount = booksIdsCount.getOrDefault(book.getBook().getId(), book.getCount());
book.setCount(newCount);
return book.getBook();
})
.toList();
repository.save(existsOrder);
return result;
}
@Transactional
public List<BookEntity> deleteOrderBooks(
long userId,
long id,
List<Long> booksIds) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
final List<OrderBookEntity> books = existsOrder.getOrderBooks().stream()
.filter(book -> Objects.nonNull(book.getBook()))
.filter(book -> booksIds.contains(book.getBook().getId()))
.toList();
books.forEach(existsOrder::deleteBook);
repository.save(existsOrder);
return books.stream()
.map(OrderBookEntity::getBook)
.toList();
}
@Transactional
public List<BookEntity> deleteAllOrderBooks(long userId, long id) {
userService.get(userId);
final OrderEntity existsOrder = get(userId, id);
final List<OrderBookEntity> books = existsOrder.getOrderBooks().stream()
.filter(book -> Objects.nonNull(book.getBook()))
.toList();
books.forEach(existsOrder::deleteBook);
repository.save(existsOrder);
return books.stream()
.map(OrderBookEntity::getBook)
return get(userId, id).getOrderBooks().stream()
.toList();
}
}

View File

@ -84,7 +84,7 @@ public class UserEntity extends BaseEntity {
@Override
public int hashCode() {
return Objects.hash(id, login, email, password, accessLevel, orders);
return Objects.hash(id, login, email, password, accessLevel);
}
@Override
@ -98,7 +98,6 @@ public class UserEntity extends BaseEntity {
&& Objects.equals(other.getLogin(), login)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password)
&& Objects.equals(other.getAccessLevel(), accessLevel)
&& Objects.equals(other.getOrders(), orders);
&& Objects.equals(other.getAccessLevel(), accessLevel);
}
}

View File

@ -1,6 +1,5 @@
package com.example.backend;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
@ -69,15 +68,18 @@ class OrderServiceTests {
"21.5x14.4x4.1", "Твердый переплёт", 8000, 1020, ""));
user = userService
.create(new UserEntity("Chief", "forum98761@gmail.com", "bth4323", "admin"));
order = orderService.create(user.getId(), new OrderEntity("Выполняется",
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36"));
orderService.create(user.getId(), new OrderEntity("Выдан",
"Томская область, город Мытищи, ул. Балканская, 25"));
orderService.create(user.getId(), new OrderEntity("Готов",
"Челябинская область, город Раменское, пр. Гоголя, 31"));
orderService.addOrderBooks(user.getId(), order.getId(),
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2));
order = orderService
.create(user.getId(), new OrderEntity("Выполняется",
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36"),
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2));
orderService
.create(user.getId(),
new OrderEntity("Выдан", "Томская область, город Мытищи, ул. Балканская, 25"),
Map.of(book1.getId(), 5));
orderService
.create(user.getId(),
new OrderEntity("Готов", "Челябинская область, город Раменское, пр. Гоголя, 31"),
Map.of(book2.getId(), 1, book3.getId(), 1));
}
@AfterEach
@ -104,20 +106,8 @@ class OrderServiceTests {
final OrderEntity nullableOrder = new OrderEntity(null,
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36");
Assertions.assertThrows(DataIntegrityViolationException.class,
() -> orderService.create(user.getId(), nullableOrder));
}
@Transactional
@Test
void updateTest() {
final String test = "TEST";
final String oldStatus = order.getStatus();
final OrderEntity newEntity = orderService.update(user.getId(), order.getId(),
new OrderEntity(test, "Кемеровская область, город Пушкино, бульвар Ломоносова, 36"));
Assertions.assertEquals(3, orderService.getAll(user.getId()).size());
Assertions.assertEquals(newEntity, orderService.get(user.getId(), order.getId()));
Assertions.assertEquals(test, newEntity.getStatus());
Assertions.assertNotEquals(oldStatus, newEntity.getStatus());
() -> orderService.create(user.getId(), nullableOrder,
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2)));
}
@Test
@ -126,7 +116,8 @@ class OrderServiceTests {
Assertions.assertEquals(2, orderService.getAll(user.getId()).size());
final OrderEntity newEntity = orderService.create(user.getId(),
new OrderEntity(order.getStatus(), order.getShippingAddress()));
new OrderEntity(order.getStatus(), order.getShippingAddress()),
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2));
Assertions.assertEquals(3, orderService.getAll(user.getId()).size());
Assertions.assertNotEquals(order.getId(), newEntity.getId());
}
@ -145,38 +136,7 @@ class OrderServiceTests {
@Transactional
@Test
void AddOrderBooksTest() {
final var category = categoryService.create(new CategoryEntity("Детективы"));
final var book = bookService.create(new BookEntity(category, "Портрет Дориана Грея",
"Оскар Уайльд", 209.00, 790, "", "", "2592760",
"Neoclassic", "Эксклюзивная классика", 2016, 320,
"17.9x11.4x1.6", "Мягкий переплёт", 254000, 200, ""));
void getOrderBooksTest() {
Assertions.assertEquals(3, orderService.getOrderBooks(user.getId(), order.getId()).size());
orderService.addOrderBooks(user.getId(), order.getId(), Map.of(book.getId(), 5));
Assertions.assertEquals(4, orderService.getOrderBooks(user.getId(), order.getId()).size());
}
@Transactional
@Test
void changeBooksCountTest() {
Assertions.assertEquals(6, orderService.getFullCount(user.getId(), order.getId()));
orderService.changeBooksCount(user.getId(), order.getId(), Map.of(book2.getId(), 4, book3.getId(), 1));
Assertions.assertEquals(8, orderService.getFullCount(user.getId(), order.getId()));
}
@Transactional
@Test
void deleteOrderBooksTest() {
Assertions.assertEquals(3, orderService.getOrderBooks(user.getId(), order.getId()).size());
orderService.deleteOrderBooks(user.getId(), order.getId(), List.of(book1.getId(), book3.getId()));
Assertions.assertEquals(1, orderService.getOrderBooks(user.getId(), order.getId()).size());
}
@Transactional
@Test
void deleteAllOrderBooksTest() {
Assertions.assertEquals(3, orderService.getOrderBooks(user.getId(), order.getId()).size());
orderService.deleteAllOrderBooks(user.getId(), order.getId());
Assertions.assertEquals(0, orderService.getOrderBooks(user.getId(), order.getId()).size());
}
}