начало 4 лабы

This commit is contained in:
Inohara 2023-04-03 13:35:16 +04:00
parent 128fd2ff2b
commit 9876a17856
41 changed files with 31151 additions and 1123 deletions

View File

@ -12,13 +12,18 @@ repositories {
mavenCentral()
}
jar{
enabled = false
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.postgresql:postgresql:'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

View File

@ -0,0 +1,13 @@
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.supply.Order;
public class OrderNotFoundException extends RuntimeException{
public OrderNotFoundException(Long id){
super(String.format("Order with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,6 @@
package com.example.demo.supply.Order;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderRepository extends JpaRepository<Orders, Long> {
}

View File

@ -1,37 +1,31 @@
package com.example.demo.supply.services;
package com.example.demo.supply.Order;
import com.example.demo.supply.models.Orders;
import com.example.demo.supply.models.Product;
import com.example.demo.supply.models.Supplier;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.Query;
import com.example.demo.supply.Product.Product;
import com.example.demo.supply.Supplier.Supplier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class OrderService {
@PersistenceContext
private EntityManager em;
private final OrderRepository orderRepository;
public OrderService(OrderRepository orderRepository){
this.orderRepository = orderRepository;
}
@Transactional
public Orders addOrder(Supplier supplier){
if (supplier == null || em.find(Supplier.class, supplier.getId()) == null) {
throw new IllegalArgumentException("invalid supplier");
}
final Orders order = new Orders(new Date(System.currentTimeMillis()));
order.setSupplier(supplier);
em.persist(order);
return order;
return orderRepository.save(order);
}
//поставщики, у которых есть заказ на конкретный товар или несколько товаров
@Transactional
public List<Supplier> suppliers(List<Product> products){
@ -48,53 +42,40 @@ public class OrderService {
return result;
}
// @Transactional
// public List<Supplier> suppliers(List<Product> products){
// return em.createQuery("SELECT o.supplier FROM Orders o WHERE o.products = :products ", Supplier.class)
// .setParameter("products", products).getResultList();
// }
@Transactional
public Orders addProduct(Long id, Product product) {
if (product == null) {
throw new IllegalArgumentException("empty product");
}
final Orders currentOrder = findOrder(id);
currentOrder.addProduct(product);
return em.merge(currentOrder);
return orderRepository.save(currentOrder);
}
@Transactional(readOnly = true)
public Orders findOrder(Long id) {
final Orders order = em.find(Orders.class, id);
if (order == null) {
throw new EntityNotFoundException(String.format("Order with id [%s] is not found", id));
}
return order;
final Optional<Orders> order = orderRepository.findById(id);
return order.orElseThrow(() -> new OrderNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Orders> findAllOrders() {
return em.createQuery("select o from Orders o", Orders.class).getResultList();
return orderRepository.findAll();
}
@Transactional
public Orders updateOrder(Long id, Date date) {
final Orders currentOrder = findOrder(id);
currentOrder.setDateOfOrder(date);
return em.merge(currentOrder);
return orderRepository.save(currentOrder);
}
@Transactional
public Orders deleteOrder(Long id) {
final Orders currentOrder = findOrder(id);
em.remove(currentOrder);
orderRepository.delete(currentOrder);
return currentOrder;
}
@Transactional
public void deleteAll(){
em.createQuery("delete from Orders ").executeUpdate();
orderRepository.deleteAll();
}
}

View File

@ -1,5 +1,7 @@
package com.example.demo.supply.models;
package com.example.demo.supply.Order;
import com.example.demo.supply.Product.Product;
import com.example.demo.supply.Supplier.Supplier;
import jakarta.persistence.*;
import java.sql.Date;

View File

@ -1,6 +1,8 @@
package com.example.demo.supply.models;
package com.example.demo.supply.Product;
import com.example.demo.supply.Order.Orders;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
@ -13,7 +15,9 @@ public class Product {
private long id;
@Column(nullable = false)
@NotBlank(message = "name cant be null or empty")
private String name;
@NotBlank(message = "cost cant be < 0")
@Column(nullable = false)
private double cost;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "products")

View File

@ -0,0 +1,45 @@
package com.example.demo.supply.Product;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin
@RequestMapping("/product")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/{id}")
public ProductDto getProduct(@PathVariable Long id) {
return new ProductDto(productService.findProduct(id));
}
@GetMapping("/")
public List<ProductDto> getProducts() {
return productService.findAllProducts().stream().map(ProductDto::new).toList();
}
@PostMapping("/")
public ProductDto createProduct(@RequestParam String name,
@RequestParam float cost) {
return new ProductDto(productService.addProduct(name, cost));
}
@PatchMapping("/{id}")
public ProductDto updateProduct(@PathVariable Long id,
@RequestParam String name,
@RequestParam float cost) {
return new ProductDto(productService.updateProduct(id, name, cost));
}
@DeleteMapping("/{id}")
public ProductDto deleteProduct(@PathVariable Long id) {
return new ProductDto(productService.deleteProduct(id));
}
}

View File

@ -0,0 +1,31 @@
package com.example.demo.supply.Product;
import com.example.demo.supply.Order.Orders;
import java.util.List;
public class ProductDto {
private long id;
private String name;
private double cost;
private List<Orders> orders;
public ProductDto(Product product) {
this.name = product.getName();
this.cost = product.getCost();
this.orders = product.getOrders();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public double getCost() {
return cost;
}
public List<Orders> getOrders() {
return orders;
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.supply.Product;
public class ProductNotFoundException extends RuntimeException{
public ProductNotFoundException(Long id){
super(String.format("Product with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,6 @@
package com.example.demo.supply.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}

View File

@ -0,0 +1,58 @@
package com.example.demo.supply.Product;
import com.example.demo.util.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
private final ProductRepository productRepository;
private final ValidatorUtil validatorUtil;
public ProductService(ProductRepository productRepository,
ValidatorUtil validatorUtil){
this.productRepository = productRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Product addProduct(String name, double cost){
final Product product = new Product(name, cost);
validatorUtil.validate(product);
return productRepository.save(product);
}
@Transactional(readOnly = true)
public Product findProduct(Long id) {
final Optional<Product> product = productRepository.findById(id);
return product.orElseThrow(() -> new ProductNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Product> findAllProducts() {
return productRepository.findAll();
}
@Transactional
public Product updateProduct(Long id, String name, float cost) {
final Product currentProduct = findProduct(id);
currentProduct.setName(name);
currentProduct.setCost(cost);
validatorUtil.validate(currentProduct);
return productRepository.save(currentProduct);
}
@Transactional
public Product deleteProduct(Long id) {
final Product product = findProduct(id);
productRepository.delete(product);
return product;
}
@Transactional
public void deleteAll(){
productRepository.deleteAll();
}
}

View File

@ -1,5 +1,6 @@
package com.example.demo.supply.models;
package com.example.demo.supply.Supplier;
import com.example.demo.supply.Order.Orders;
import jakarta.persistence.*;
import java.util.ArrayList;

View File

@ -1,7 +1,5 @@
package com.example.demo.supply.controllers;
package com.example.demo.supply.Supplier;
import com.example.demo.supply.models.Supplier;
import com.example.demo.supply.services.SupplierService;
import org.springframework.web.bind.annotation.*;
import java.util.List;

View File

@ -0,0 +1,29 @@
package com.example.demo.supply.Supplier;
import com.example.demo.supply.Order.Orders;
import java.util.List;
public class SupplierDto {
private Long id;
private String name;
private int license;
private List<Orders> orders;
public SupplierDto(Supplier supplier){
this.name = supplier.getName();
this.license = supplier.getLicense();
this.orders = supplier.getOrders();
}
public Long getId() { return id; }
public String getName() {
return name;
}
public int getLicense() {
return license;
}
public List<Orders> getOrders() {
return orders;
}
}

View File

@ -0,0 +1,8 @@
package com.example.demo.supply.Supplier;
public class SupplierNotFoundException extends RuntimeException{
public SupplierNotFoundException(Long id){
super(String.format("Supplier with id [%s] is not found", id));
}
}

View File

@ -0,0 +1,6 @@
package com.example.demo.supply.Supplier;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SupplierRepository extends JpaRepository<Supplier, Long> {
}

View File

@ -0,0 +1,53 @@
package com.example.demo.supply.Supplier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class SupplierService {
private final SupplierRepository supplierRepository;
public SupplierService(SupplierRepository supplierRepository){
this.supplierRepository = supplierRepository;
}
@Transactional
public Supplier addSupplier(String name, int license){
final Supplier supplier = new Supplier(name, license);
return supplierRepository.save(supplier);
}
@Transactional(readOnly = true)
public Supplier findSupplier(Long id) {
final Optional<Supplier> supplier = supplierRepository.findById(id);
return supplier.orElseThrow(() -> new SupplierNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Supplier> findAllSuppliers() {
return supplierRepository.findAll();
}
@Transactional
public Supplier updateSupplier(Long id, String name, int license) {
final Supplier currentSupplier = findSupplier(id);
currentSupplier.setName(name);
currentSupplier.setLicense(license);
return supplierRepository.save(currentSupplier);
}
@Transactional
public Supplier deleteSupplier(Long id) {
final Supplier currentSupplier = findSupplier(id);
supplierRepository.delete(currentSupplier);
return currentSupplier;
}
@Transactional
public void deleteAll(){
supplierRepository.deleteAll();
}
}

View File

@ -1,47 +0,0 @@
package com.example.demo.supply.controllers;
import com.example.demo.supply.models.Product;
import com.example.demo.supply.services.ProductService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin
@RequestMapping("/product")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return productService.findProduct(id);
}
@GetMapping("/")
public List<Product> getProduct() {
return productService.findAllProducts();
}
@PostMapping("/")
public Product createProduct(@RequestParam() String name,
@RequestParam() float cost) {
return productService.addProduct(name, cost);
}
@PatchMapping("/{id}")
public Product updateProduct(@PathVariable Long id,
@RequestParam() String name,
@RequestParam() float cost) {
return productService.updateProduct(id, name, cost);
}
@DeleteMapping("/{id}")
public Product deleteProduct(@PathVariable Long id) {
return productService.deleteProduct(id);
}
}

View File

@ -1,64 +0,0 @@
package com.example.demo.supply.services;
import com.example.demo.supply.models.Product;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class ProductService {
@PersistenceContext
private EntityManager em;
@Transactional
public Product addProduct(String name, double cost){
if(!StringUtils.hasText(name) || cost <= 0)
throw new IllegalArgumentException("Invalid name and/or cost");
final Product product = new Product(name, cost);
em.persist(product);
return product;
}
@Transactional(readOnly = true)
public Product findProduct(Long id) {
final Product product = em.find(Product.class, id);
if (product == null) {
throw new EntityNotFoundException(String.format("Product with id [%s] is not found", id));
}
return product;
}
@Transactional(readOnly = true)
public List<Product> findAllProducts() {
return em.createQuery("select p from Product p", Product.class).getResultList();
}
@Transactional
public Product updateProduct(Long id, String name, float cost) {
if (!StringUtils.hasText(name) || cost <= 0)
throw new IllegalArgumentException("Invalid name and/or cost");
final Product currentProduct = findProduct(id);
currentProduct.setName(name);
currentProduct.setCost(cost);
return em.merge(currentProduct);
}
@Transactional
public Product deleteProduct(Long id) {
final Product currentProduct = findProduct(id);
em.remove(currentProduct);
return currentProduct;
}
@Transactional
public void deleteAll(){
em.createQuery("delete from Product").executeUpdate();
}
}

View File

@ -1,64 +0,0 @@
package com.example.demo.supply.services;
import com.example.demo.supply.models.Supplier;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class SupplierService {
@PersistenceContext
private EntityManager em;
@Transactional
public Supplier addSupplier(String name, int license){
if(!StringUtils.hasText(name) || license < 0)
throw new IllegalArgumentException("Invalid name and/or license");
final Supplier supplier = new Supplier(name, license);
em.persist(supplier);
return supplier;
}
@Transactional(readOnly = true)
public Supplier findSupplier(Long id) {
final Supplier supplier = em.find(Supplier.class, id);
if (supplier == null) {
throw new EntityNotFoundException(String.format("Supplier with id [%s] is not found", id));
}
return supplier;
}
@Transactional(readOnly = true)
public List<Supplier> findAllSuppliers() {
return em.createQuery("select s from Supplier s", Supplier.class).getResultList();
}
@Transactional
public Supplier updateSupplier(Long id, String name, int license) {
if (!StringUtils.hasText(name) || license < 0)
throw new IllegalArgumentException("Invalid name and/or license");
final Supplier currentSupplier = findSupplier(id);
currentSupplier.setName(name);
currentSupplier.setLicense(license);
return em.merge(currentSupplier);
}
@Transactional
public Supplier deleteSupplier(Long id) {
final Supplier currentSupplier = findSupplier(id);
em.remove(currentSupplier);
return currentSupplier;
}
@Transactional
public void deleteAll(){
em.createQuery("delete from Supplier ").executeUpdate();
}
}

View File

@ -0,0 +1,37 @@
package com.example.demo.util;
import com.example.demo.supply.Product.ProductNotFoundException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
ProductNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,9 @@
package com.example.demo.util;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,29 @@
package com.example.demo.util;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -1,3 +1,5 @@
spring.main.banner-mode=off
server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa

View File

@ -1,11 +1,9 @@
package com.example.demo;
import com.example.demo.supply.models.Orders;
import com.example.demo.supply.models.Product;
import com.example.demo.supply.models.Supplier;
import com.example.demo.supply.services.OrderService;
import com.example.demo.supply.services.ProductService;
import com.example.demo.supply.services.SupplierService;
import com.example.demo.supply.Order.Orders;
import com.example.demo.supply.Supplier.Supplier;
import com.example.demo.supply.Order.OrderService;
import com.example.demo.supply.Supplier.SupplierService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@ -16,66 +14,5 @@ import java.util.List;
@SpringBootTest
public class Tests {
@Autowired
private ProductService productService;
@Autowired
private OrderService orderService;
@Autowired
private SupplierService supplierService;
@Test
public void testOrder(){
productService.deleteAll();
orderService.deleteAll();
supplierService.deleteAll();
final Product product1 = productService.addProduct("Huawei Band 3", 2000.13);
final Product product2 = productService.addProduct("Samsung A2", 22000.56);
final Supplier supplier = supplierService.addSupplier("SuperSupplier", 325453);
Orders order = orderService.addOrder(supplierService.findSupplier(supplier.getId()));
order = orderService.addProduct(order.getId(), product1);
order = orderService.addProduct(order.getId(), product2);
final Orders order2 = orderService.findOrder(order.getId());
Assertions.assertEquals(order, order2);
productService.deleteAll();
orderService.deleteAll();
supplierService.deleteAll();
}
@Test
public void test(){
productService.deleteAll();
orderService.deleteAll();
supplierService.deleteAll();
/
final Product product1 = productService.addProduct("Huawei Band 3", 2000.13);
final Product product2 = productService.addProduct("Samsung A2", 22000.56);
final Product product3 = productService.addProduct("Redmond f3", 2000.13);
final Product product4 = productService.addProduct("Asus red9", 22000.56);
final Supplier supplier1 = supplierService.addSupplier("SuperSupplier1", 325453);
final Supplier supplier2 = supplierService.addSupplier("SuperSupplier2", 545455);
final Supplier supplier3 = supplierService.addSupplier("SuperSupplier3", 122122);
Orders order1 = orderService.addOrder(supplierService.findSupplier(supplier1.getId()));
orderService.addProduct(order1.getId(), product1);
orderService.addProduct(order1.getId(), product2);
Orders order2 = orderService.addOrder(supplierService.findSupplier(supplier2.getId()));
orderService.addProduct(order2.getId(), product3);
Orders order3 = orderService.addOrder(supplierService.findSupplier(supplier1.getId()));
orderService.addProduct(order3.getId(), product3);
orderService.addProduct(order3.getId(), product4);
List<Product> products = new ArrayList<>();
products.add(productService.findProduct(product3.getId()));
List<Supplier> suppliers = orderService.suppliers(products);
Assertions.assertEquals(suppliers.size(), 2);
productService.deleteAll();
orderService.deleteAll();
supplierService.deleteAll();
}
//
}

View File

@ -1,8 +1,5 @@
package com.example.demo;
import com.example.demo.supply.models.Product;
import com.example.demo.supply.services.ProductService;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -13,44 +10,44 @@ import java.util.List;
@SpringBootTest
public class TestsProduct {
@Autowired
private ProductService productService;
@Test
void testProduct(){
productService.deleteAll();
final Product product = productService.addProduct("Huawei Band 3", 2000.13);
Assertions.assertNotNull(product.getId());
}
@Test
void testProductRead(){
productService.deleteAll();
final Product product = productService.addProduct("Huawei Band 3", 2000.13);
final Product findProduct = productService.findProduct(product.getId());
Assertions.assertEquals(product, findProduct);
}
@Test
void testProductReadNotFound(){
productService.deleteAll();
Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
}
@Test
void testProductReadAll(){
productService.deleteAll();
productService.addProduct("Samsung A3", 22000.4);
productService.addProduct("Huawei Band 3", 2000.13);
final List<Product> products = productService.findAllProducts();
Assertions.assertEquals(products.size(), 2);
}
@Test
void testProductReadAllEmpty(){
productService.deleteAll();
final List<Product> products = productService.findAllProducts();
Assertions.assertEquals(products.size(), 0);
}
// @Autowired
// private ProductService productService;
//
//
// @Test
// void testProduct(){
// productService.deleteAll();
// final Product product = productService.addProduct("Huawei Band 3", 2000.13);
// Assertions.assertNotNull(product.getId());
// }
//
// @Test
// void testProductRead(){
// productService.deleteAll();
// final Product product = productService.addProduct("Huawei Band 3", 2000.13);
// final Product findProduct = productService.findProduct(product.getId());
// Assertions.assertEquals(product, findProduct);
// }
//
// @Test
// void testProductReadNotFound(){
// productService.deleteAll();
// Assertions.assertThrows(EntityNotFoundException.class, () -> productService.findProduct(-1L));
// }
//
// @Test
// void testProductReadAll(){
// productService.deleteAll();
// productService.addProduct("Samsung A3", 22000.4);
// productService.addProduct("Huawei Band 3", 2000.13);
// final List<Product> products = productService.findAllProducts();
// Assertions.assertEquals(products.size(), 2);
// }
//
// @Test
// void testProductReadAllEmpty(){
// productService.deleteAll();
// final List<Product> products = productService.findAllProducts();
// Assertions.assertEquals(products.size(), 0);
// }
}

View File

@ -1,9 +1,8 @@
package com.example.demo;
import com.example.demo.supply.models.Supplier;
import com.example.demo.supply.services.OrderService;
import com.example.demo.supply.services.ProductService;
import com.example.demo.supply.services.SupplierService;
import com.example.demo.supply.Supplier.Supplier;
import com.example.demo.supply.Order.OrderService;
import com.example.demo.supply.Supplier.SupplierService;
import jakarta.persistence.EntityNotFoundException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -14,47 +13,47 @@ import java.util.List;
@SpringBootTest
public class TestsSupplier {
@Autowired
private SupplierService supplierService;
@Autowired
private OrderService orderService;
@Autowired
private ProductService productService;
@Test
void testSupplier(){
supplierService.deleteAll();
final Supplier supplier = supplierService.addSupplier("SuperSup", 359342);
Assertions.assertNotNull(supplier.getId());
}
@Test
void testSupplierRead(){
supplierService.deleteAll();
final Supplier supplier = supplierService.addSupplier("Huawei", 4357695);
final Supplier findSupplier = supplierService.findSupplier(supplier.getId());
Assertions.assertEquals(supplier, findSupplier);
}
@Test
void testSupplierReadNotFound(){
supplierService.deleteAll();
Assertions.assertThrows(EntityNotFoundException.class, () -> supplierService.findSupplier(-1L));
}
@Test
void testSupplierReadAll(){
supplierService.deleteAll();
supplierService.addSupplier("Samsung", 3485456);
supplierService.addSupplier("Huawei", 45736964);
final List<Supplier> suppliers = supplierService.findAllSuppliers();
Assertions.assertEquals(suppliers.size(), 2);
}
@Test
void testSupplierReadAllEmpty(){
supplierService.deleteAll();
final List<Supplier> suppliers = supplierService.findAllSuppliers();
Assertions.assertEquals(suppliers.size(), 0);
}
// @Autowired
// private SupplierService supplierService;
// @Autowired
// private OrderService orderService;
// @Autowired
// private ProductService productService;
//
// @Test
// void testSupplier(){
// supplierService.deleteAll();
// final Supplier supplier = supplierService.addSupplier("SuperSup", 359342);
// Assertions.assertNotNull(supplier.getId());
// }
//
// @Test
// void testSupplierRead(){
// supplierService.deleteAll();
// final Supplier supplier = supplierService.addSupplier("Huawei", 4357695);
// final Supplier findSupplier = supplierService.findSupplier(supplier.getId());
// Assertions.assertEquals(supplier, findSupplier);
// }
//
// @Test
// void testSupplierReadNotFound(){
// supplierService.deleteAll();
// Assertions.assertThrows(EntityNotFoundException.class, () -> supplierService.findSupplier(-1L));
// }
//
// @Test
// void testSupplierReadAll(){
// supplierService.deleteAll();
// supplierService.addSupplier("Samsung", 3485456);
// supplierService.addSupplier("Huawei", 45736964);
// final List<Supplier> suppliers = supplierService.findAllSuppliers();
// Assertions.assertEquals(suppliers.size(), 2);
// }
//
// @Test
// void testSupplierReadAllEmpty(){
// supplierService.deleteAll();
// final List<Supplier> suppliers = supplierService.findAllSuppliers();
// Assertions.assertEquals(suppliers.size(), 0);
// }
}

View File

@ -1,44 +1,61 @@
<!DOCTYPE html>
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>App</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form class="mx-2 d-flex flex-column align-items-center text-center">
<div>
Первый объект
<input id="first" class="form-control" type='number' value='0' />
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REST Client Example</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<select class="form-select" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">Изделия</option>
<option value="2">Поставщики</option>
<option value="3">Three</option>
</select>
<form id="form">
<div class="row mt-3">
<div class="col-sm-6">
<label for="lastName" class="form-label">Last name</label>
<input type="text" class="form-control" id="lastName" required>
</div>
<div class="col-sm-6">
<label for="firstName" class="form-label">First name</label>
<input type="text" class="form-control" id="firstName" required>
</div>
</div>
<div>
Операция
<select class="form-select" id="operation">
<option value="1">+</option>
<option value="2">-</option>
<option value="3">*</option>
<option value="4">/</option>
</select>
</div>
<div>
Второй объект
<input id="second" class="form-control" type='number' value='0' />
</div>
<div>
<button type="button" class="btn btn-primary my-2" id="intButton">Integer</button>
</div>
<div>
<button type="button" class="btn btn-primary mb-2" id="strButton">String</button>
</div>
<div>
Результат:
<p id="result"> </p>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First name</th>
<th scope="col">Last name</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<script type="module" src="./index.js"></script>
</body>
</div>
</body>
<script>
</script>
</html>

View File

@ -1,46 +1,74 @@
const intButton = document.getElementById("intButton");
const strButton = document.getElementById("strButton");
const first = document.getElementById("first");
const second = document.getElementById("second");
const operation = document.getElementById("operation");
const result = document.getElementById("result");
intButton.onclick = () => {
method("int");
};
strButton.onclick = () => {
method("str");
};
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const lastNameInput = document.getElementById("lastName");
const firstNameInput = document.getElementById("firstName");
const testErrorBtn = document.getElementById("testError");
const testNormalBtn = document.getElementById("testNormal");
function method(parametr) {
switch (parseInt(operation.value)) {
case 1:
get("summa", parametr)
break;
case 2:
get("min", parametr)
break;
case 3:
get("multi", parametr)
break;
case 4:
get("div", parametr)
break;
};
}
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/student");
const data = await response.json();
data.forEach(student => {
table.innerHTML +=
`<tr>
<th scope="row">${student.id}</th>
<td>${student.firstName}</td>
<td>${student.lastName}</td>
</tr>`;
})
}
function checkNum(res) {
if (res.indexOf(".") != -1)
return parseInt(res)
else
return res
}
const create = async function (firstName, lastName) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + /student?firstName=${firstName}&lastName=${lastName}, requestParams);
return await response.json();
}
function get(address, type) {
console.log("Тип " + type)
fetch(`http://localhost:8080/${address}?first=${first.value}&second=${second.value}&type=${type}`)
.then(response => response.text())
.then(res => result.innerHTML = res);
}
const test = async function (testObject) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(testObject),
};
const response = await fetch(host + "/test", requestParams);
if (response.status === 200) {
const data = await response.json();
alert(TestDto=[id=${data.id}, name=${data.name}, data=${data.data}]);
}
if (response.status === 400) {
const data = await response.text();
alert(data);
}
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create(firstNameInput.value, lastNameInput.value).then((result) => {
getData();
firstNameInput.value = "";
lastNameInput.value = "";
alert(Student[id=${result.id}, firstName=${result.firstName}, lastName=${result.lastName}]);
});
});
testErrorBtn.addEventListener("click", function () {
test({});
});
testNormalBtn.addEventListener("click", function () {
test({id: 10, name: "test"});
});
getData();
});

1321
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{
"name": "interface_project",
"name": "front",
"private": true,
"version": "0.0.0",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "./node_modules/.bin/vite",
@ -17,4 +17,4 @@
"bootstrap": "5.2.1",
"@fortawesome/fontawesome-free": "6.2.0"
}
}
}

23
frontReact/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
frontReact/README.md Normal file
View File

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

29612
frontReact/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
frontReact/package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "front",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.0-alpha2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/js/bootstrap.bundle.min.js" integrity="sha384-qKXV1j0HvMUeCBQ+QVp7JcfGl760yU08IQ+GpUo5hlbpg51QRiuqHAJz8+BrxE/N" crossorigin="anonymous"></script>
<title>Front for spring</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@ -0,0 +1,24 @@
import React from 'react';
function Navigation(){
return(
<div className="navigation">
<ul class="nav justify-content-center">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
</div>
);
}
export default nav;

View File

@ -0,0 +1,83 @@
import React, {useState} from 'react';
const productModel ={
name: '',
cost: ''
}
export default function ProductPage(){
const [product, setProduct] = useState(productModel)
const [products, setProducts] = useState([])
const addProduct = (e) => {
e.preventDefault()
setProducts((prevState) => [...prevState, product])
setProduct(productModel)
}
return(
<div className="container">
<form id="form" onSubmit={addProduct}>
<div className="row mt-3">
<div className="col-sm-6">
<label for="lastName" className="form-label">Наименование</label>
<input type="text" className="form-control" id="productName" required
onChange={(e) => setProduct((prevState => (
{
...prevState, name: e.target.value
}
)))} value={product.name} />
</div>
<div className="col-sm-6">
<label for="firstName" className="form-label">Цена</label>
<input type="text" className="form-control" id="productCost" required
onChange={(e) => setProduct((prevState => (
{
...prevState, cost: e.target.value
}
)))} value={product.cost}/>
</div>
</div>
<div className="row mt-3">
<div className="d-grid col-sm-4 mx-auto">
<button type="submit" className="btn btn-success">Добавить</button>
</div>
<div className="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button type="reset" className="btn btn-danger">Очистить инпуты</button>
</div>
<div className="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" className="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div className="row table-responsive">
<table className="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Наименование</th>
<th scope="col">Цена</th>
<th scope="col">Действие</th>
</tr>
</thead>
<tbody id="tbody">
{products.map((product) =>
<tr>
<td>{products.length}</td>
<td>{product.name}</td>
<td>{product.cost}</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
)
}

13
frontReact/src/index.css Normal file
View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

11
frontReact/src/index.js Normal file
View File

@ -0,0 +1,11 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import ProductPage from './ProductPage';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ProductPage />
</React.StrictMode>
);