From 69897fcfa4901663e4c9fe60fd2474c38eb52587 Mon Sep 17 00:00:00 2001 From: ksenianeva <95441235+ksenianeva@users.noreply.github.com> Date: Mon, 1 May 2023 23:44:30 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A2=D1=80=D0=B5=D1=82=D1=8C=D1=8F=20=D0=BB?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82=D0=BE=D1=80=D0=BD=D0=B0?= =?UTF-8?q?=D1=8F=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0.=20=D0=94=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D1=8B=20=D1=81=D0=B5=D1=80=D0=B2?= =?UTF-8?q?=D0=B8=D1=81=D1=8B=20=D0=B8=20=D1=82=D0=B5=D1=81=D1=82=D1=8B.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/lab/data.mv.db | Bin 0 -> 45056 bytes backend/lab/data.trace.db | 58 +++++++++ .../lab/AllTypeCalc/service/CalcService.java | 14 ++- .../example/lab/DataBaseLab3/Models/Cart.java | 95 ++++++++++++-- .../lab/DataBaseLab3/Models/Customer.java | 11 ++ .../lab/DataBaseLab3/Models/Product.java | 69 +++++++++- .../DataBaseLab3/Models/ProductCategory.java | 61 ++++++++- .../DataBaseLab3/Services/CartService.java | 85 +++++++++++++ .../Services/CustomerService.java | 2 +- .../Services/ProductCategoryService.java | 59 +++++++++ .../DataBaseLab3/Services/ProductService.java | 72 +++++++++++ .../test/java/com/example/lab/DBTests.java | 118 ++++++++++++++++++ 12 files changed, 626 insertions(+), 18 deletions(-) create mode 100644 backend/lab/data.mv.db create mode 100644 backend/lab/data.trace.db create mode 100644 backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CartService.java create mode 100644 backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductCategoryService.java create mode 100644 backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductService.java create mode 100644 backend/lab/src/test/java/com/example/lab/DBTests.java diff --git a/backend/lab/data.mv.db b/backend/lab/data.mv.db new file mode 100644 index 0000000000000000000000000000000000000000..76bc92a9669afee2f5aacd3c6d637d66b68cc7a5 GIT binary patch literal 45056 zcmeHQU2Gi3ecwAC#WigvvS`bZk;LnhWQpm8-Ot(G16ufaJc<-~Bz1R`C8H>@AG0!H zl1ES{St?LOZGgTsZ|zIbv;_(j4N??IU;0#_Zknflp$|@47|4UsJ{1L;6zF^ZvopK5 zx3_ydGE^u_b09c7yYum%-+b-N@4xe3uBsJxx9fdawW-_Q`3+oEWLd6wA3WIquo^fO zZx=iJRi)w`VyB1ws$!Wa&;rLmdL`%{?m0b3HysFhtzsQx|Ypz0uS9#xShSN8FvURA3cIQQ^Q23w1KNSj>1nNIW?m7l_(7AnQ56^GUgwD>sj~~se@_ zJL%Ju0UvrLk)}>PyIptD={YZlPr%c34&v(;4qgxMcMtG>=g`@|?|41Xp}0?@_8fN? z&oj}eN6~18)Tdg>fCG;-E%}HEMq}Au4D;;ay@Rz-o-c&{2m5|^t$S}?8T6{}kf&8v zjLL`jan%YO)lg-<^3d6>8n%NR*;L*NgT;w3U6I?7QV1G+t`0pfs72%#6{m=BQTK|v zUqq;gyn&M_Ti|LLHSl#&-&|V_?iWh8}hd=pH){aT9ul9A0gP9YUtvMGd=) zDkGV76q9un*CPD{`jOJ_D2nMBM&-f&gZrRR106^4OdBzOtrz2_#eE4RA$>`4v03SQ z-h%^Y-+Np&gFj@F1{#ypN=d3f?g?R8-_}E673jiDSd|Iug}qvLf<&(-!YQMKgUmzW zkZmP|lhs%_oeAfrg>ztZA(&DmiBvG~P~kF=^a+qMGL)2X8OS9@AwZoV=NUmlIAr~0 zgq*>IbJ*ZFqK>I#I-nK~i7o?AiH1aY0zcKW6EzLsS*e<~hru-BnhuOmUfmqPQi;Vy zOk96laZw~LPKz5hOd>9dM{rWtk$C+Poi@}&!%V;naRFXK9Tc~qyb{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5x7pg9QH%A0~v<&V0~6ekQtOkH!B7eNJc>?^nklsY9mb z02KA^S0jps9u|TIC>q5xfwJz?>6Ee=I;X_$lhpl>ITIwc8N?^4M{36H>}5(FLGPpiXrGs0YrZA&LP5 w2h;%fFH{KU&uBZY3jkQ~-;0a@(JdbcConnection.java:122) + at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288) + at org.h2.server.web.WebServer.getConnection(WebServer.java:807) + at org.h2.server.web.WebApp.login(WebApp.java:1033) + at org.h2.server.web.WebApp.process(WebApp.java:226) + at org.h2.server.web.WebApp.processRequest(WebApp.java:176) + at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129) + at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166) + at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731) + at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) + at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) + at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) + at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) + at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) + at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) + at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) + at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) + at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) + at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) + at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177) + at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) + at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) + at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119) + at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) + at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) + at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) + at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400) + at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) + at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859) + at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734) + at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) + at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) + at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) + at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) + at java.base/java.lang.Thread.run(Thread.java:833) +Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль +Wrong user name or password [28000-210] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:529) + at org.h2.message.DbException.getJdbcSQLException(DbException.java:496) + ... 50 more diff --git a/backend/lab/src/main/java/com/example/lab/AllTypeCalc/service/CalcService.java b/backend/lab/src/main/java/com/example/lab/AllTypeCalc/service/CalcService.java index 675d70f..18808af 100644 --- a/backend/lab/src/main/java/com/example/lab/AllTypeCalc/service/CalcService.java +++ b/backend/lab/src/main/java/com/example/lab/AllTypeCalc/service/CalcService.java @@ -11,7 +11,6 @@ import com.example.lab.AllTypeCalc.domain.ICalculation; import java.util.Arrays; @Service - public class CalcService { private final ApplicationContext applicationContext; private final Logger log = LoggerFactory.getLogger(CalculationInt.class); @@ -19,7 +18,6 @@ public class CalcService { this.applicationContext = applicationContext; } - public Object GetSum(Object firstInp, Object secondInp, String type) { final ICalculation calculator = (ICalculation) applicationContext.getBean(type); if(type.equals("str")){ @@ -52,7 +50,8 @@ public class CalcService { return calculator.GetMult(firstInp.toString(), secondInp.toString()); } if (type.equals("int")){ - return calculator.GetMult(Integer.parseInt(firstInp.toString()), Integer.parseInt(secondInp.toString())); + return calculator.GetMult(Integer.parseInt(firstInp.toString()), + Integer.parseInt(secondInp.toString())); } if (type.equals("arr")){ return calculator.GetMult(cleanToArr(firstInp) , cleanToArr(secondInp)); @@ -65,7 +64,9 @@ public class CalcService { return calculator.GetDiv(firstInp.toString(), secondInp.toString()); } if (type.equals("int")){ - return calculator.GetDiv(Integer.parseInt(firstInp.toString()), Integer.parseInt(secondInp.toString())); + return calculator.GetDiv( + Integer.parseInt(firstInp.toString()), + Integer.parseInt(secondInp.toString())); } if(type.equals("arr")){ return calculator.GetDiv(cleanToArr(firstInp) , cleanToArr(secondInp)); @@ -74,6 +75,9 @@ public class CalcService { } public String[] cleanToArr(Object arr){ - return Arrays.stream(arr.toString().split("[\\(\\)\\,\\.\\[\\] \\!\\?\\:\\;]")).filter(e -> e.trim().length()>0).toArray(String[]::new); + return Arrays.stream(arr.toString() + .split("[\\(\\)\\,\\.\\[\\] \\!\\?\\:\\;]")) + .filter(e -> e.trim().length()>0) + .toArray(String[]::new); } } diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Cart.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Cart.java index f072d7f..f90bd57 100644 --- a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Cart.java +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Cart.java @@ -1,10 +1,9 @@ package com.example.lab.DataBaseLab3.Models; import jakarta.persistence.*; +import jakarta.persistence.criteria.CriteriaBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; +import java.util.*; @Entity public class Cart { @@ -13,13 +12,91 @@ public class Cart { @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @OneToOne(fetch = FetchType.EAGER, mappedBy = "cart", cascade = CascadeType.ALL) - private Customer customer; - @ManyToMany(fetch = FetchType.EAGER, mappedBy = "products", cascade = CascadeType.ALL) - private List products; - public Cart() { - this.products = new ArrayList<>(); + @OneToOne + private Customer customer; + @ManyToMany(fetch = FetchType.EAGER, mappedBy = "carts", cascade = CascadeType.ALL ) + private List products; //can't count there because of "integer not @entity" + @ElementCollection(fetch = FetchType.EAGER) + @CollectionTable(name = "cart_products_count", + joinColumns = {@JoinColumn(name = "cart_id", referencedColumnName = "id")}) + @MapKeyColumn(name = "product") + @Column(name = "amount") + private Map countProducts; //count amount of products + + public Cart(){} + + public Cart(Customer customer) { + this.countProducts = new HashMap<>(); + this.customer = customer; + } + + public List getProducts() { + return products; + } + + public Map getCountProducts(){ + return countProducts; + } + + //изменяет ее значение если есть такой товар на +1 + public void addProduct(Product product){ + if(!countProducts.containsKey(product) || !products.contains(product)){ + this.countProducts.put(product, 1); + this.products.add(product); + } + else{ + countProducts.put(product, countProducts.get(product) + 1); + } + if (!product.getCarts().contains(this)){ + product.addCart(this); + } + } + + public void deleteProduct(Product product){ + products.remove(product); + if (product.getCarts().contains(this)) { + product.removeCart(this); + } + countProducts.remove(product); + } + + public void reduceProduct(Product product){ + if (!countProducts.containsKey(product)) return; + if(countProducts.get(product)==1){ + //delete the last one + deleteProduct(product); + } + else{ + countProducts.put(product, countProducts.get(product) - 1); + } + } + @PreRemove + public void deleteThis(){ + deleteAllProducts(); + this.getCustomer().setCart(null); + } + + + public void deleteAllProducts(){ + ArrayList products = new ArrayList<>(this.products); + this.countProducts.clear(); + this.products.clear(); + for (var product: + products) { + if (product.getCarts().contains(this)) product.removeCart(this); + } + } + + public Customer getCustomer() { + return customer; + } + + public void setCustomer(Customer customer) { + this.customer = customer; + if(customer.getCart()!=this){ + customer.setCart(this); + } } public Long getId() { diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Customer.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Customer.java index 36e4145..533ba72 100644 --- a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Customer.java +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Customer.java @@ -26,6 +26,17 @@ public class Customer { this.customerAddress = customerAddress; } + public Cart getCart() { + return cart; + } + + public void setCart(Cart cart) { + this.cart = cart; + if(cart != null && cart.getCustomer()!=this){ + cart.setCustomer(this); + } + } + public Long getId() { return id; } diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Product.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Product.java index 2ebc73e..b96f8f0 100644 --- a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Product.java +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/Product.java @@ -2,6 +2,8 @@ package com.example.lab.DataBaseLab3.Models; import jakarta.persistence.*; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Objects; @@ -13,7 +15,11 @@ public class Product { private String name; private float price; - @ManyToMany(fetch = FetchType.EAGER, mappedBy = "carts", cascade = CascadeType.ALL) + + @ManyToMany(fetch = FetchType.EAGER) + @JoinTable(name = "products_carts", + joinColumns = @JoinColumn(name = "product_fk"), + inverseJoinColumns = @JoinColumn(name = "cart_fk")) private List carts; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "productCategory_fk") @@ -21,21 +27,80 @@ public class Product { public Product(){} - public Product(String name, float price){ + public Product(String name, float price, ProductCategory productCategory){ this.name = name; this.price = price; + this.productCategory = productCategory; + } + + public ProductCategory getProductCategory() { + return productCategory; + } + + public void setProductCategory(ProductCategory productCategory) { + this.productCategory = productCategory; + if(productCategory == null){ + return; + } + if (!productCategory.getProducts().contains(this)){ + productCategory.AddProduct(this); + } } public Long getId() { return id; } + + public void setName(String name) { + this.name = name; + } + public String getName() { return name; } + + public void setPrice(float price) { + this.price = price; + } + public float getPrice() { return price; } + + public void addCart(Cart cart) { + carts.add(cart); + if (!cart.getProducts().contains(this)) { + cart.addProduct(this); + } + + } + @PreRemove + public void deleteThis(){ + deleteAllCarts(); + this.productCategory.getProducts().remove(this); + } + + public void deleteAllCarts(){ + ArrayList carts = new ArrayList<>(this.carts); + this.carts.clear(); + for (var cart: + carts) { + cart.deleteProduct(this); + } + } + + public void removeCart(Cart cart) { + carts.remove(cart); + if (cart.getProducts().contains(this)) { + cart.deleteAllProducts(); + } + } + + public List getCarts() { + return carts; + } + @Override public boolean equals(Object obj) { if (this == obj) return true; diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/ProductCategory.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/ProductCategory.java index ed33e50..19bca1c 100644 --- a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/ProductCategory.java +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Models/ProductCategory.java @@ -1,5 +1,64 @@ package com.example.lab.DataBaseLab3.Models; -public class ProductCategory { +import jakarta.persistence.*; +import java.util.*; +@Entity +public class ProductCategory { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String name; + @OneToMany(fetch = FetchType.EAGER, mappedBy = "productCategory", cascade = CascadeType.ALL) + private List products; + + public void AddProduct(Product product){ + this.products.add(product); + if (product.getProductCategory() != this){ + product.setProductCategory(this); + } + } + + public void deleteProduct(Product product) { + products.remove(product); + if (product.getProductCategory() == this) { + product.setProductCategory(null); + } + } + public ProductCategory(){} + + public ProductCategory(String name){ + this.name = name; + this.products = new ArrayList(); + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getProducts() { + return products; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + ProductCategory customer = (ProductCategory) obj; + return Objects.equals(id, customer.id); + } + + @Override + public int hashCode(){ + return Objects.hashCode(id); + } } + diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CartService.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CartService.java new file mode 100644 index 0000000..f19d9c7 --- /dev/null +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CartService.java @@ -0,0 +1,85 @@ +package com.example.lab.DataBaseLab3.Services; + +import com.example.lab.DataBaseLab3.Models.Customer; +import com.example.lab.DataBaseLab3.Models.Product; +import jakarta.persistence.*; +import jakarta.transaction.Transactional; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import com.example.lab.DataBaseLab3.Models.Cart; +import java.util.List; + +@Service +public class CartService { + @PersistenceContext + private EntityManager em; + + private final ProductService productService; + + public CartService(ProductService productService){ + this.productService = productService; + } + + @Transactional + public Cart addCart(Customer customer){ + Cart cart = new Cart(customer); + cart.getCustomer().setCart(cart); + em.persist(cart); + return cart; + } + + @Transactional() + public Cart getCart(Long id){ + Cart cart = em.find(Cart.class, id); + if (cart == null){ + throw new EntityNotFoundException(String.format("Error: Cart id %s not found", id)); + } + return cart; + } + + @Transactional + public List getAllCarts(){ + return em.createQuery("from Cart", Cart.class).getResultList(); + } + + @Transactional + public Cart deleteCart(Long id){ + final Cart cart = getCart(id); + em.remove(cart); + return cart; + } + @Transactional + public void deleteAllCarts(){ + for (var cart: + getAllCarts()) { + cart.deleteThis(); + em.remove(cart); + } + } + + @Transactional + public Product addProduct(Long cartId, Long productId){ + Product product = productService.getProduct(productId); + Cart cart = getCart(cartId); + cart.addProduct(product); + em.persist(cart); + return product; + } + + @Transactional + public Product deleteProduct(Long cartId, Long productId){ + Product product = productService.getProduct(productId); + Cart cart = getCart(cartId); + cart.deleteProduct(product); + em.persist(cart); + return product; + } + + @Transactional + public Product reduceProduct(Long cartId, Long productId){ + Product product = productService.getProduct(productId); + Cart cart = getCart(cartId); + cart.reduceProduct(product); + return product; + } +} diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CustomerService.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CustomerService.java index 95fbcf5..bcf4801 100644 --- a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CustomerService.java +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/CustomerService.java @@ -61,6 +61,6 @@ public class CustomerService { } @Transactional public void deleteAllCustomers(){ - em.createQuery("Delete from Customer"); + em.createQuery("Delete from Customer").executeUpdate(); } } \ No newline at end of file diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductCategoryService.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductCategoryService.java new file mode 100644 index 0000000..f70e74e --- /dev/null +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductCategoryService.java @@ -0,0 +1,59 @@ +package com.example.lab.DataBaseLab3.Services; + +import jakarta.persistence.*; +import jakarta.transaction.Transactional; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import com.example.lab.DataBaseLab3.Models.ProductCategory; +import java.util.List; + +@Service +public class ProductCategoryService { + @PersistenceContext + private EntityManager em; + + @Transactional + public ProductCategory addProductCategory(String name){ + if (!StringUtils.hasText(name)){ + throw new IllegalArgumentException("ProductCategory name can't be null"); + } + ProductCategory productCategory = new ProductCategory(name); + em.persist(productCategory); + return productCategory; + } + + @Transactional() + public ProductCategory getProductCategory(Long id){ + ProductCategory productCategory = em.find(ProductCategory.class, id); + if (productCategory == null){ + throw new EntityNotFoundException(String.format("Error: ProductCategory id %s not found", id)); + } + return productCategory; + } + + @Transactional + public List getAllProductCategorys(){ + return em.createQuery("get c from ProductCategory c", ProductCategory.class).getResultList(); + } + + @Transactional + public ProductCategory updateProductCategory(Long id, String productCategoryName){ + if (!StringUtils.hasText(productCategoryName)){ + throw new IllegalArgumentException("ProductCategory name is null"); + } + final ProductCategory productCategory = getProductCategory(id); + productCategory.setName(productCategoryName); + return em.merge(productCategory); + } + + @Transactional + public ProductCategory deleteProductCategory(Long id){ + final ProductCategory productCategory = getProductCategory(id); + em.remove(productCategory); + return productCategory; + } + @Transactional + public void deleteAllProductCategories(){ + em.createQuery("Delete from ProductCategory").executeUpdate(); + } +} \ No newline at end of file diff --git a/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductService.java b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductService.java new file mode 100644 index 0000000..6ebeca6 --- /dev/null +++ b/backend/lab/src/main/java/com/example/lab/DataBaseLab3/Services/ProductService.java @@ -0,0 +1,72 @@ +package com.example.lab.DataBaseLab3.Services; + +import com.example.lab.DataBaseLab3.Models.ProductCategory; +import jakarta.persistence.*; +import jakarta.transaction.Transactional; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import com.example.lab.DataBaseLab3.Models.Product; +import java.util.List; + +@Service +public class ProductService { + @PersistenceContext + private EntityManager em; + + @Transactional + public Product addProduct(String name, float price, ProductCategory productCategory){ + if (!StringUtils.hasText(name)){ + throw new IllegalArgumentException("Product first and last names can't be null"); + } + else if(price <= 0){ + throw new IllegalArgumentException("Product price cant be under 0"); + } + Product product = new Product(name, price, productCategory); + product.getProductCategory().AddProduct(product); + em.persist(product); + return product; + } + + @Transactional() + public Product getProduct(Long id){ + Product product = em.find(Product.class, id); + if (product == null){ + throw new EntityNotFoundException(String.format("Error: Product id %s not found", id)); + } + return product; + } + + @Transactional + public List getAllProducts(){ + return em.createQuery("from Product", Product.class).getResultList(); + } + + @Transactional + public Product updateProduct(Long id, String name, float price){ + if (!StringUtils.hasText(name)){ + throw new IllegalArgumentException("Product name cant be null"); + } + else if(price <= 0){ + throw new IllegalArgumentException("Product price cant be under 0"); + } + final Product product = getProduct(id); + product.setName(name); + product.setPrice(price); + return em.merge(product); + } + + @Transactional + public Product deleteProduct(Long id){ + final Product product = getProduct(id); + em.remove(product); + return product; + } + @Transactional + public void deleteAllProducts(){ + for (var product: + getAllProducts()) { + product.deleteThis(); + em.remove(product); + } + } +} \ No newline at end of file diff --git a/backend/lab/src/test/java/com/example/lab/DBTests.java b/backend/lab/src/test/java/com/example/lab/DBTests.java new file mode 100644 index 0000000..54fba11 --- /dev/null +++ b/backend/lab/src/test/java/com/example/lab/DBTests.java @@ -0,0 +1,118 @@ +package com.example.lab; + +import com.example.lab.DataBaseLab3.Models.Cart; +import com.example.lab.DataBaseLab3.Models.Customer; +import com.example.lab.DataBaseLab3.Models.Product; +import com.example.lab.DataBaseLab3.Models.ProductCategory; +import com.example.lab.DataBaseLab3.Services.CartService; +import com.example.lab.DataBaseLab3.Services.CustomerService; +import com.example.lab.DataBaseLab3.Services.ProductCategoryService; +import com.example.lab.DataBaseLab3.Services.ProductService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class DBTests { + @Autowired + CartService cartService; + @Autowired + CustomerService customerService; + @Autowired + ProductCategoryService productCategoryService; + @Autowired + ProductService productService; + + @Test + void testProductCategory(){ + cleanAll(); + + ProductCategory productCategory = productCategoryService.addProductCategory("exampleCategory"); + Assertions.assertEquals("exampleCategory", productCategory.getName()); + productCategoryService.updateProductCategory(productCategory.getId(), "updExample"); + Assertions.assertEquals("updExample", productCategoryService + .getProductCategory(productCategory.getId()).getName()); + + Assertions.assertEquals("updExample", productCategoryService + .deleteProductCategory(productCategory.getId()).getName()); + + cleanAll(); + } + + @Test + void testProduct() { + cleanAll(); + + ProductCategory productCategory = productCategoryService.addProductCategory("exampleCategory"); + Product product = productService.addProduct("example", (float) 50, productCategory); + + Assertions.assertEquals("example", product.getName()); + Assertions.assertEquals("exampleCategory", product.getProductCategory().getName()); + Assertions.assertEquals("example", productService.getProduct(product.getId()).getName()); + Assertions.assertEquals((float) 50, productService.getProduct(product.getId()).getPrice()); + productService.updateProduct(product.getId(), "newExample", (float) 60); + Assertions.assertEquals("newExample", productService.getProduct(product.getId()).getName()); + Assertions.assertEquals((float) 60, productService.getProduct(product.getId()).getPrice()); + + Assertions.assertEquals("newExample", productService.deleteProduct(product.getId()).getName()); + + cleanAll(); + } + + @Test + void testCustomer(){ + cleanAll(); + + Customer customer = customerService.addCustomer("Ivan", + "Ivanov", "cityExample"); + Cart cart = cartService.addCart(customer); + Assertions.assertEquals("Ivan", customerService + .getCustomer(customer.getId()).getFirstName()); + Assertions.assertEquals("Ivanov", customerService + .getCustomer(customer.getId()).getLastName()); + Assertions.assertEquals("cityExample", customerService + .getCustomer(customer.getId()).getCustomerAddress()); + customerService.updateCustomer(customer.getId(),"Vaskin", + "Vasilii", "newAddress"); + Assertions.assertEquals("Vasilii", customerService + .getCustomer(customer.getId()).getFirstName()); + Assertions.assertEquals("Vaskin", customerService + .getCustomer(customer.getId()).getLastName()); + Assertions.assertEquals("newAddress", customerService + .getCustomer(customer.getId()).getCustomerAddress()); + + Assertions.assertEquals("Vasilii", customerService + .deleteCustomer(customer.getId()).getFirstName()); + + cleanAll(); + } + + @Test + void testCart(){ + cleanAll(); + + ProductCategory productCategory = productCategoryService + .addProductCategory("exampleCategory"); + Product product = productService + .addProduct("exampleProduct", (float)50, productCategory ); + Customer customer = customerService.addCustomer("Ivan", + "Ivanov", "cityExample"); + Cart cart = cartService.addCart(customer); + + Assertions.assertEquals(product,cartService.addProduct(cart.getId(), product.getId())); + + Assertions.assertEquals(cart,cartService.getCart(cart.getId())); + Assertions.assertEquals(product, cartService.reduceProduct(cart.getId(),product.getId())); + Assertions.assertEquals(product, cartService.deleteProduct(cart.getId(),product.getId())); + Assertions.assertEquals(cart,cartService.deleteCart(cart.getId())); + cleanAll(); + } + + public void cleanAll(){ + productService.deleteAllProducts(); + cartService.deleteAllCarts(); + customerService.deleteAllCustomers(); + productCategoryService.deleteAllProductCategories(); + } +}