This commit is contained in:
Леонид Малафеев 2024-05-24 02:47:47 +04:00
parent 0c1b6680b0
commit 90bd53cd06
22 changed files with 248 additions and 279 deletions

BIN
.vs/Ip/v17/.wsuo Normal file

Binary file not shown.

3
.vs/ProjectSettings.json Normal file
View File

@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

View File

@ -0,0 +1,7 @@
{
"ExpandedNodes": [
""
],
"SelectedNode": "\\D:\\ulstu\\Ip",
"PreviewInSolutionExplorer": false
}

BIN
.vs/slnx.sqlite Normal file

Binary file not shown.

View File

@ -65,21 +65,36 @@ public class DemoApplication implements CommandLineRunner {
final var user1 = userService.create(new UserEntity("user1", Constants.DEFAULT_PASSWORD));
IntStream.range(2, 6)
IntStream.range(2, 15)
.forEach(value -> userService.create(
new UserEntity("user".concat(String.valueOf(value)), Constants.DEFAULT_PASSWORD)));
log.info("Create default order values");
IntStream.range(2, 15)
.forEach(value -> brandService.create(
new BrandEntity("Toyota " + value)));
IntStream.range(2, 15)
.forEach(value -> packService.create(
new PackEntity("Drift " + value)));
log.info("Create default car values");
carService.create(new CarEntity("Автомобиль Ламба", "Крутое авто для парня", brand1, 5000));
carService.create(new CarEntity("Автомобиль Ферра", "Супер мощное авто 90 л.с.", brand2, 6000));
carService.create(new CarEntity("Супер Пушка", "Гоночный автомобиль", brand3, 2000));
carService.create(new CarEntity("Дрифт Гонка", "Дрифт автомобиль", brand1, 1000));
carService.create(new CarEntity("абоба", "абоба", brand1, 9999));
carService.create(new CarEntity("абоба", "абоба", brand1, 9999));
carService.create(new CarEntity("абоба", "абоба", brand1, 9999));
carService.create(new CarEntity("абоба", "абоба", brand1, 9999));
carService.create(new CarEntity("абоба", "абоба", brand1, 9999));
carService.create(new CarEntity("абоба", "абоба", brand1, 9999));
var cars = carService.getAll();
for (CarEntity carEntity : cars) {
carService.addCarPacks(carEntity.getId(), pack1.getId());
carService.addCarPacks(carEntity.getId(), pack2.getId());
}
log.info("DONE");
}
}

View File

@ -1,5 +1,8 @@
package com.example.demo.brands.api;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
import java.util.Map;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@ -9,7 +12,7 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.demo.core.configuration.Constants;
import com.example.demo.brands.model.BrandEntity;
import com.example.demo.brands.service.BrandService;
@ -22,6 +25,7 @@ public class BrandController {
public static final String URL = Constants.ADMIN_PREFIX + "/brand";
private static final String BRAND_VIEW = "brand";
private static final String BRAND_EDIT_VIEW = "brand-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String BRAND_ATTRIBUTE = "brand";
private final BrandService brandService;
@ -41,29 +45,33 @@ public class BrandController {
}
@GetMapping
public String getAll(Model model) {
model.addAttribute(
"items",
brandService.getAll().stream()
.map(this::toDto)
.toList());
public String getAll(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
brandService.getAll(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return BRAND_VIEW;
}
@GetMapping("/edit/")
public String create(Model model) {
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
model.addAttribute(BRAND_ATTRIBUTE, new BrandDto());
model.addAttribute(PAGE_ATTRIBUTE, page);
return BRAND_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = BRAND_ATTRIBUTE) @Valid BrandDto brand,
BindingResult bindingResult,
Model model) {
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return BRAND_EDIT_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
brandService.create(toEntity(brand));
return Constants.REDIRECT_VIEW + URL;
}
@ -71,33 +79,42 @@ public class BrandController {
@GetMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(BRAND_ATTRIBUTE, toDto(brandService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return BRAND_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = BRAND_ATTRIBUTE) @Valid BrandDto brand,
BindingResult bindingResult,
Model model) {
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return BRAND_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
brandService.update(id, toEntity(brand));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
brandService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}

View File

@ -3,10 +3,11 @@ package com.example.demo.brands.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.brands.model.BrandEntity;
public interface BrandRepository extends CrudRepository<BrandEntity, Long> {
public interface BrandRepository
extends CrudRepository<BrandEntity, Long>, PagingAndSortingRepository<BrandEntity, Long> {
Optional<BrandEntity> findByNameIgnoreCase(String name);
}

View File

@ -2,7 +2,9 @@ package com.example.demo.brands.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -29,6 +31,11 @@ public class BrandService {
}
}
@Transactional(readOnly = true)
public Page<BrandEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public List<BrandEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();

View File

@ -35,6 +35,7 @@ public class CarAdminController {
public static final String URL = Constants.ADMIN_PREFIX + "/car";
private static final String CAR_VIEW = "car-admin";
private static final String CAR_EDIT_VIEW = "car-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String CAR_ATTRIBUTE = "car";
private final CarService carService;
@ -74,12 +75,11 @@ public class CarAdminController {
}
@GetMapping
public String getAll(Model model) {
model.addAttribute(
"items",
carService.getAll().stream()
.map(this::toDto)
.toList());
public String getAll(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
carService.getAll(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return CAR_VIEW;
}
@ -92,28 +92,34 @@ public class CarAdminController {
}
@GetMapping("/edit/")
public String create(Model model) {
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
model.addAttribute(CAR_ATTRIBUTE, new CarDto());
model.addAttribute("brands", brandService.getAll().stream().map(this::toBrandDto).toList());
model.addAttribute("packsCheck", packService.getAll().stream().map(this::toPackDto).toList());
model.addAttribute(PAGE_ATTRIBUTE, page);
return CAR_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = CAR_ATTRIBUTE) @Valid CarDto car,
BindingResult bindingResult,
Model model) {
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return CAR_EDIT_VIEW;
}
carService.create(toEntity(car));
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
return Constants.REDIRECT_VIEW + URL;
}
@GetMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
@ -121,16 +127,20 @@ public class CarAdminController {
model.addAttribute(CAR_ATTRIBUTE, toDto(carService.get(id)));
model.addAttribute("brands", brandService.getAll().stream().map(this::toBrandDto).toList());
model.addAttribute("packsCheck", packService.getAll().stream().map(this::toPackDto).toList());
model.addAttribute(PAGE_ATTRIBUTE, page);
return CAR_EDIT_VIEW;
}
@PostMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = CAR_ATTRIBUTE) @Valid CarDto car,
BindingResult bindingResult,
Model model) {
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return CAR_EDIT_VIEW;
}
if (id <= 0) {
@ -138,14 +148,18 @@ public class CarAdminController {
}
model.addAttribute("brands", brandService.getAll().stream().map(this::toBrandDto).toList());
model.addAttribute("packsCheck", packService.getAll().stream().map(this::toPackDto).toList());
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
carService.update(id, toEntity(car));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
carService.delete(id);
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
return Constants.REDIRECT_VIEW + URL;
}
}

View File

@ -3,7 +3,7 @@ package com.example.demo.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final int DEFUALT_PAGE_SIZE = 4;
public static final int DEFUALT_PAGE_SIZE = 8;
public static final String REDIRECT_VIEW = "redirect:";

View File

@ -9,6 +9,11 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.core.api.PageAttributesMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.packs.model.PackEntity;
@ -22,6 +27,7 @@ public class PackController {
public static final String URL = Constants.ADMIN_PREFIX + "/pack";
private static final String PACK_VIEW = "pack";
private static final String PACK_EDIT_VIEW = "pack-edit";
private static final String PAGE_ATTRIBUTE = "page";
private static final String PACK_ATTRIBUTE = "pack";
private final PackService packService;
@ -41,29 +47,32 @@ public class PackController {
}
@GetMapping
public String getAll(Model model) {
model.addAttribute(
"items",
packService.getAll().stream()
.map(this::toDto)
.toList());
public String getAll(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
packService.getAll(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
model.addAllAttributes(attributes);
model.addAttribute(PAGE_ATTRIBUTE, page);
return PACK_VIEW;
}
@GetMapping("/edit/")
public String create(Model model) {
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
model.addAttribute(PACK_ATTRIBUTE, new PackDto());
model.addAttribute(PAGE_ATTRIBUTE, page);
return PACK_EDIT_VIEW;
}
@PostMapping("/edit/")
public String create(
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
@ModelAttribute(name = PACK_ATTRIBUTE) @Valid PackDto pack,
BindingResult bindingResult,
Model model) {
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return PACK_EDIT_VIEW;
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
packService.create(toEntity(pack));
return Constants.REDIRECT_VIEW + URL;
}
@ -71,11 +80,13 @@ public class PackController {
@GetMapping("/edit/{id}")
public String update(
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
Model model) {
if (id <= 0) {
throw new IllegalArgumentException();
}
model.addAttribute(PACK_ATTRIBUTE, toDto(packService.get(id)));
model.addAttribute(PAGE_ATTRIBUTE, page);
return PACK_EDIT_VIEW;
}
@ -83,21 +94,28 @@ public class PackController {
public String update(
@PathVariable(name = "id") Long id,
@ModelAttribute(name = PACK_ATTRIBUTE) @Valid PackDto pack,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
BindingResult bindingResult,
Model model) {
Model model,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute(PAGE_ATTRIBUTE, page);
return PACK_EDIT_VIEW;
}
if (id <= 0) {
throw new IllegalArgumentException();
}
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
packService.update(id, toEntity(pack));
return Constants.REDIRECT_VIEW + URL;
}
@PostMapping("/delete/{id}")
public String delete(
@PathVariable(name = "id") Long id) {
@PathVariable(name = "id") Long id,
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
packService.delete(id);
return Constants.REDIRECT_VIEW + URL;
}

View File

@ -3,9 +3,10 @@ package com.example.demo.packs.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.packs.model.PackEntity;
public interface PackRepository extends CrudRepository<PackEntity, Long> {
public interface PackRepository extends CrudRepository<PackEntity, Long>, PagingAndSortingRepository<PackEntity, Long> {
Optional<PackEntity> findByNameIgnoreCase(String name);
}

View File

@ -2,7 +2,9 @@ package com.example.demo.packs.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -34,6 +36,11 @@ public class PackService {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<PackEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public List<PackEntity> getAllById(List<Long> listIds) {
return StreamSupport.stream(repository.findAllById(listIds).spliterator(), false).toList();

View File

@ -1,3 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart2" viewBox="0 0 16 16">
<path d="M0 2.5A.5.5 0 0 1 .5 2H2a.5.5 0 0 1 .485.379L2.89 4H14.5a.5.5 0 0 1 .485.621l-1.5 6A.5.5 0 0 1 13 11H4a.5.5 0 0 1-.485-.379L1.61 3H.5a.5.5 0 0 1-.5-.5zM3.14 5l1.25 5h8.22l1.25-5H3.14zM5 13a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0zm9-1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0z"/>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
class="bi bi-car-front-fill" viewBox="0 0 16 16">
<path
d="M2.52 3.515A2.5 2.5 0 0 1 4.82 2h6.362c1 0 1.904.596 2.298 1.515l.792 1.848c.075.175.21.319.38.404.5.25.855.715.965 1.262l.335 1.679q.05.242.049.49v.413c0 .814-.39 1.543-1 1.997V13.5a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1-.5-.5v-1.338c-1.292.048-2.745.088-4 .088s-2.708-.04-4-.088V13.5a.5.5 0 0 1-.5.5h-2a.5.5 0 0 1-.5-.5v-1.892c-.61-.454-1-1.183-1-1.997v-.413a2.5 2.5 0 0 1 .049-.49l.335-1.68c.11-.546.465-1.012.964-1.261a.8.8 0 0 0 .381-.404l.792-1.848ZM3 10a1 1 0 1 0 0-2 1 1 0 0 0 0 2m10 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2M6 8a1 1 0 0 0 0 2h4a1 1 0 1 0 0-2zM2.906 5.189a.51.51 0 0 0 .497.731c.91-.073 3.35-.17 4.597-.17s3.688.097 4.597.17a.51.51 0 0 0 .497-.731l-.956-1.913A.5.5 0 0 0 11.691 3H4.309a.5.5 0 0 0-.447.276L2.906 5.19Z" />
</svg>

Before

Width:  |  Height:  |  Size: 463 B

After

Width:  |  Height:  |  Size: 890 B

View File

@ -43,6 +43,10 @@
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/brand'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>

View File

@ -47,6 +47,10 @@
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/car'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>

View File

@ -3,6 +3,22 @@
<head>
<title>Редакторовать списки автомобилей</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.checkbox-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
/* Две колонки одинаковой ширины */
gap: 2px;
/* Отступ между колонками */
}
.form-check {
margin-bottom: 0.5px;
/* Отступ между чекбоксами по вертикали */
}
</style>
</head>
<body>
@ -38,12 +54,14 @@
</div>
<div class="mb-2">
<label class="form-label">Пакет</label>
<div class="form-check" th:each="pack : ${packsCheck}">
<input class="form-check-input" th:field="*{packs}" th:value="${pack.id}" type="checkbox"
th:for="${id}">
<label class="form-check-label" th:field="*{packs}" for="" th:for="${id}">
[[${pack.name}]]
</label>
<div class="checkbox-container">
<div class="form-check" th:each="pack : ${packsCheck}">
<input class="form-check-input" th:field="*{packs}" th:value="${pack.id}" type="checkbox"
th:id="'pack_' + ${pack.id}">
<label class="form-check-label" th:field="*{packs}" th:for="'pack_' + ${pack.id}">
[[${pack.name}]]
</label>
</div>
</div>
</div>
<div class="mb-3 d-flex flex-row">

View File

@ -5,7 +5,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">Автосалон</title>
<script type="text/javascript" src="/webjars/bootstrap/5.3.3/dist/js/bootstrap.bundle.min.js"></script>
@ -18,7 +18,7 @@
<nav class="navbar navbar-expand-md my-navbar" style="justify-content: center;">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="bi bi-cart2 d-inline-block align-top me-1 logo" style="color: black;"></i>
<i class="bi bi-car-front-fill d-inline-block align-top me-1 logo" style="color: black;"></i>
</a>
<th:block sec:authorize="isAuthenticated()" th:with="userName=${#authentication.name}">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#main-navbar"

View File

@ -43,6 +43,10 @@
</tbody>
</table>
</th:block>
<th:block th:replace="~{ pagination :: pagination (
url=${'admin/pack'},
totalPages=${totalPages},
currentPage=${currentPage}) }" />
</th:block>
</main>
</body>

View File

@ -0,0 +1,75 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.cars.service.*;
import com.example.demo.cars.model.*;
import com.example.demo.brands.model.*;
import com.example.demo.brands.service.*;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
class CarServiceTests {
@Autowired
private CarService carService;
@Autowired
private BrandService brandService;
private final BrandEntity brand1;
public CarServiceTests() {
brand1 = brandService.create(new BrandEntity("aboba"));
}
@BeforeEach
void createData() {
// Создаем тестовые данные перед каждым тестом
carService.create(new CarEntity("Toyota", "Camry", brand1, 25000));
carService.create(new CarEntity("Honda", "Civic", brand1, 22000));
}
@AfterEach
void removeData() {
// Удаляем тестовые данные после каждого теста
carService.getAll().forEach(car -> carService.delete(car.getId()));
}
@Test
void getTest() {
// Тест получения существующей машины
CarEntity car = carService.getAll().get(0);
Assertions.assertEquals(car, carService.get(car.getId()));
}
@Test
void createTest() {
// Тест создания новой машины
CarEntity newCar = new CarEntity("BMW", "X5", brand1, 60000);
carService.create(newCar);
Assertions.assertTrue(carService.getAll().contains(newCar));
}
@Test
void updateTest() {
// Тест обновления данных о машине
CarEntity car = carService.getAll().get(0);
car.setDescription("Test Description");
carService.update(car.getId(), car);
CarEntity updatedCar = carService.get(car.getId());
Assertions.assertEquals("Test Description", updatedCar.getDescription());
}
@Test
void deleteTest() {
// Тест удаления машины
CarEntity car = carService.getAll().get(0);
carService.delete(car.getId());
Assertions.assertFalse(carService.getAll().contains(car));
}
}

View File

@ -1,83 +0,0 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
class TypeServiceTests {
/*
* @Autowired
* private TypeService typeService;
*
* private TypeEntity type;
*
* @BeforeEach
* void createData() {
* removeData();
*
* type = typeService.create(new TypeEntity("Ноутбук"));
* typeService.create(new TypeEntity("Телефон"));
* typeService.create(new TypeEntity("Игровая приставка"));
* }
*
* @AfterEach
* void removeData() {
* typeService.getAll().forEach(item -> typeService.delete(item.getId()));
* }
*
* @Test
* void getTest() {
* Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
* }
*
* @Test
* void createTest() {
* Assertions.assertEquals(3, typeService.getAll().size());
* Assertions.assertEquals(type, typeService.get(type.getId()));
* }
*
* @Test
* void createNotUniqueTest() {
* final TypeEntity nonUniqueType = new TypeEntity("Ноутбук");
* Assertions.assertThrows(IllegalArgumentException.class, () ->
* typeService.create(nonUniqueType));
* }
*
* @Test
* void createNullableTest() {
* final TypeEntity nullableType = new TypeEntity(null);
* Assertions.assertThrows(DataIntegrityViolationException.class, () ->
* typeService.create(nullableType));
* }
*
* @Test
* void updateTest() {
* final String test = "TEST";
* final String oldName = type.getName();
* final TypeEntity newEntity = typeService.update(type.getId(), new
* TypeEntity(test));
* Assertions.assertEquals(3, typeService.getAll().size());
* Assertions.assertEquals(newEntity, typeService.get(type.getId()));
* Assertions.assertEquals(test, newEntity.getName());
* Assertions.assertNotEquals(oldName, newEntity.getName());
* }
*
* @Test
* void deleteTest() {
* typeService.delete(type.getId());
* Assertions.assertEquals(2, typeService.getAll().size());
*
* final TypeEntity newEntity = typeService.create(new
* TypeEntity(type.getName()));
* Assertions.assertEquals(3, typeService.getAll().size());
* Assertions.assertNotEquals(type.getId(), newEntity.getId());
* }
*/
}

View File

@ -1,145 +0,0 @@
package com.example.demo;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.persistence.EntityManager;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserOrderServiceTest {
/*
* @Autowired
* private EntityManager entityManager;
*
* @Autowired
* private TypeService typeService;
*
* @Autowired
* private SubscriptionService subscriptionService;
*
* @Autowired
* private OrderService orderService;
*
* @Autowired
* private UserService userService;
*
* private TypeEntity type1;
* private TypeEntity type2;
* private TypeEntity type3;
*
* private UserEntity user1;
* private UserEntity user2;
*
* @BeforeEach
* void createData() {
* removeData();
*
* type1 = typeService.create(new TypeEntity("Ноутбук"));
* type2 = typeService.create(new TypeEntity("Телефон"));
* type3 = typeService.create(new TypeEntity("Игровая приставка"));
*
* subscriptionService.create(new SubscriptionEntity("Подписка 1"));
* subscriptionService.create(new SubscriptionEntity("Подписка 2"));
* subscriptionService.create(new SubscriptionEntity("Подписка 3"));
*
* user1 = userService.create(new UserEntity("user1",
* Constants.DEFAULT_PASSWORD));
* user2 = userService.create(new UserEntity("user2",
* Constants.DEFAULT_PASSWORD));
*
* final var orders = List.of(
* new OrderEntity(type1, 49999.00, 20),
* new OrderEntity(type1, 129999.00, 3),
* new OrderEntity(type2, 15450.50, 30),
* new OrderEntity(type2, 69900.50, 10),
* new OrderEntity(type2, 150000.00, 6),
* new OrderEntity(type3, 75000.00, 6),
* new OrderEntity(type3, 67800.00, 3));
* orders.forEach(order -> orderService.create(user1.getId(), order));
* }
*
* @AfterEach
* void removeData() {
* userService.getAll().forEach(item -> userService.delete(item.getId()));
* typeService.getAll().forEach(item -> typeService.delete(item.getId()));
* subscriptionService.getAll().forEach(item ->
* subscriptionService.delete(item.getId()));
* }
*
* @Test
*
* @Order(1)
* void createTest() {
* Assertions.assertEquals(7, orderService.getAll(user1.getId(), 0).size());
* Assertions.assertEquals(0, orderService.getAll(user2.getId(), 0).size());
* }
*
* @Test
*
* @Order(2)
* void orderFilterTest() {
* Assertions.assertEquals(2, orderService.getAll(user1.getId(),
* type1.getId()).size());
* Assertions.assertEquals(3, orderService.getAll(user1.getId(),
* type2.getId()).size());
* Assertions.assertEquals(2, orderService.getAll(user1.getId(),
* type3.getId()).size());
* }
*
* @Test
*
* @Order(3)
* void subscriptionsTest() {
* Assertions.assertEquals(3,
* userService.getUserSubscriptions(user1.getId()).size());
*
* final UserSubscriptionWithStatus subscription =
* userService.getUserSubscriptions(user1.getId()).get(0);
* subscription.setActive(false);
* userService.saveUserSubscriptions(user1.getId(), Set.of(subscription));
* Assertions.assertEquals(2,
* userService.getUserSubscriptions(user1.getId()).stream()
* .filter(UserSubscriptionWithStatus::isActive)
* .count());
*
* subscription.setActive(true);
* userService.saveUserSubscriptions(user1.getId(), Set.of(subscription));
* Assertions.assertEquals(3,
* userService.getUserSubscriptions(user1.getId()).stream()
* .filter(UserSubscriptionWithStatus::isActive)
* .count());
* }
*
* @Test
*
* @Order(6)
* void userCascadeDeleteTest() {
* userService.delete(user1.getId());
* final var orders = entityManager.createQuery(
* "select count(o) from OrderEntity o where o.user.id = :userId");
* orders.setParameter("userId", user1.getId());
* Assertions.assertEquals(0, orders.getFirstResult());
* final var subscriptions = entityManager.createQuery(
* "select count(us) from UserSubscriptionEntity us where us.user.id = :userId"
* );
* subscriptions.setParameter("userId", user1.getId());
* Assertions.assertEquals(0, subscriptions.getFirstResult());
*
* }
*/
}