Compare commits

..

8 Commits

89 changed files with 8658 additions and 575 deletions

View File

@ -14,6 +14,13 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
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.hibernate.validator:hibernate-validator'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

BIN
backend/lab/data.mv.db Normal file

Binary file not shown.

58
backend/lab/data.trace.db Normal file
View File

@ -0,0 +1,58 @@
2023-04-25 12:33:02 database: wrong user or password; user: "USER"
org.h2.message.DbException: Неверное имя пользователя или пароль
Wrong user name or password [28000-210]
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.message.DbException.get(DbException.java:192)
at org.h2.engine.Engine.openSession(Engine.java:154)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:338)
at org.h2.jdbc.JdbcConnection.<init>(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

View File

@ -0,0 +1,30 @@
package com.example.lab.AllTypeCalc.configuration;
import com.example.lab.AllTypeCalc.domain.CalculationInt;
import com.example.lab.AllTypeCalc.domain.CalculationStr;
import com.example.lab.AllTypeCalc.domain.CalculationArr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
public class CalcConfig {
private final Logger log = LoggerFactory.getLogger(com.example.lab.AllTypeCalc.configuration.CalcConfig.class);
@Bean(value = "int")
public CalculationInt createCalculationInt(){
log.info("Call createCalculationInt()");
return new CalculationInt();
}
@Bean(value = "str")
public CalculationStr createCalculationStr() {
log.info("Call createCalculationStr()");
return new CalculationStr();
}
@Bean (value = "arr")
public CalculationArr createCalculationArr() {
log.info("Call createCalculationArr()");
return new CalculationArr();
}
}

View File

@ -0,0 +1,43 @@
package com.example.lab.AllTypeCalc.controller;
import com.example.lab.AllTypeCalc.service.CalcService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalcController {
private final CalcService calcService;
public CalcController(CalcService calcService) {
this.calcService = calcService;
}
@GetMapping("/GetSum")
public Object getSum(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetSum(obj1, obj2, typeInp);
}
@GetMapping("/GetMinus")
public Object getMinus(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetMinus(obj1, obj2, typeInp);
}
@GetMapping("/GetMult")
public Object getMult(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetMult(obj1, obj2, typeInp);
}
@GetMapping("/GetDiv")
public Object getDiv(@RequestParam(value = "obj1", defaultValue = "null") Object obj1,
@RequestParam(value = "obj2", defaultValue = "null") Object obj2,
@RequestParam(value = "typeInp", defaultValue = "str") String typeInp) {
return calcService.GetDiv(obj1, obj2, typeInp);
}
}

View File

@ -0,0 +1,97 @@
package com.example.lab.AllTypeCalc.domain;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component(value = "arr")
public class CalculationArr implements ICalculation<String[]> {
@Override
public String[] GetSum(String[] firstInp, String[] secondInp) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] = Integer.toString(Integer.parseInt(longArr[i]) + Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
@Override
public String[] GetMinus(String[] firstInp, String[] secondInp) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] = Integer.toString(Integer.parseInt(longArr[i]) - Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
@Override
public String[] GetMult(String firstInp[], String secondInp[]) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] = Integer.toString(Integer.parseInt(longArr[i]) * Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
@Override
public String[] GetDiv(String[] firstInp, String[] secondInp) {
String[] resArr;
String[] longArr;
String[] shortArr;
if (secondInp.length > firstInp.length) {
longArr = secondInp.clone();
shortArr = firstInp.clone();
} else {
longArr = firstInp.clone();
shortArr = secondInp.clone();
}
resArr = new String[longArr.length];
for (int i = 0; i < shortArr.length; i++) {
resArr[i] =Integer.toString(Integer.parseInt(longArr[i]) / Integer.parseInt(shortArr[i]));
}
for (int i = shortArr.length; i < longArr.length; i++) {
resArr[i] = longArr[i];
}
return resArr;
}
}

View File

@ -0,0 +1,33 @@
package com.example.lab.AllTypeCalc.domain;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import org.springframework.stereotype.Component;
@Component(value = "int")
public class CalculationInt implements ICalculation<Integer> {
@Override
public Integer GetSum(Integer firstInp, Integer secondInp) {
return firstInp+secondInp;
}
@Override
public Integer GetMinus(Integer firstInp, Integer secondInp) {
return firstInp - secondInp;
}
@Override
public Integer GetMult(Integer firstInp, Integer secondInp) {
return firstInp*secondInp;
}
@Override
public Integer GetDiv(Integer firstInp, Integer secondInp) {
if (secondInp == 0){
return 0;
}
else{
return (firstInp/secondInp);
}
}
}

View File

@ -0,0 +1,54 @@
package com.example.lab.AllTypeCalc.domain;
import com.example.lab.AllTypeCalc.domain.ICalculation;
import org.springframework.stereotype.Component;
@Component(value = "str")
public class CalculationStr implements ICalculation<String> {
@Override
public String GetSum(String firstInp, String secondInp) {
return (firstInp+secondInp);
}
@Override
public String GetMinus(String firstInp, String secondInp) {
StringBuilder bufStr = new StringBuilder();
if (firstInp.equals(secondInp)){
return "0";
}
else {
for (int i = 0; i < firstInp.length(); i++) {
boolean check = true;
for (int k = 0; k < secondInp.length(); k++) {
if (firstInp.charAt(i) == secondInp.charAt(k)) {
check = false;
break;
}
}
if (check){
bufStr.append(firstInp.charAt(i));}
}
}
return bufStr.toString();
}
@Override
public String GetMult(String firstInp, String secondInp) {
int multInt = secondInp.length();
StringBuilder multResult = new StringBuilder();
for (int i = 0; i < multInt; i++){
multResult.append(firstInp);
}
return multResult.toString();
}
@Override
public String GetDiv(String firstInp, String secondInp) {
if (secondInp.length() !=0) {
double divRes = 1.0 * firstInp.length() / secondInp.length();
return Double.toString(divRes);
}
else return "error";
}
}

View File

@ -0,0 +1,8 @@
package com.example.lab.AllTypeCalc.domain;
public interface ICalculation <V> {
V GetSum(V firstInp, V secondInp);
V GetMinus (V firstInp, V secondInp);
V GetMult (V firstInp, V secondInp);
V GetDiv(V firstInp, V secondInp);
}

View File

@ -0,0 +1,83 @@
package com.example.lab.AllTypeCalc.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import com.example.lab.AllTypeCalc.domain.CalculationInt;
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);
public CalcService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public Object GetSum(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if(type.equals("str")){
return calculator.GetSum(firstInp.toString(),secondInp.toString());
}
if(type.equals("int")) {
return calculator.GetSum(Integer.parseInt(firstInp.toString()), Integer.parseInt(secondInp.toString()) );
}
if(type.equals("arr")){
return calculator.GetSum(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public Object GetMinus(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if(type.equals("str")){
return calculator.GetMinus(firstInp.toString(),secondInp.toString());
}
if (type.equals("int")){
return calculator.GetMinus(Integer.parseInt(firstInp.toString()), Integer.parseInt(secondInp.toString()));
}
if(type.equals("arr")){
return calculator.GetMinus(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public Object GetMult(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if(type.equals("str")){
return calculator.GetMult(firstInp.toString(), secondInp.toString());
}
if (type.equals("int")){
return calculator.GetMult(Integer.parseInt(firstInp.toString()),
Integer.parseInt(secondInp.toString()));
}
if (type.equals("arr")){
return calculator.GetMult(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public Object GetDiv(Object firstInp, Object secondInp, String type) {
final ICalculation calculator = (ICalculation) applicationContext.getBean(type);
if (type.equals("str")){
return calculator.GetDiv(firstInp.toString(), secondInp.toString());
}
if (type.equals("int")){
return calculator.GetDiv(
Integer.parseInt(firstInp.toString()),
Integer.parseInt(secondInp.toString()));
}
if(type.equals("arr")){
return calculator.GetDiv(cleanToArr(firstInp) , cleanToArr(secondInp));
}
return "error";
}
public String[] cleanToArr(Object arr){
return Arrays.stream(arr.toString()
.split("[\\(\\)\\,\\.\\[\\] \\!\\?\\:\\;]"))
.filter(e -> e.trim().length()>0)
.toArray(String[]::new);
}
}

View File

@ -0,0 +1,44 @@
package com.example.lab.DataBase.Controllers;
import com.example.lab.DataBase.DTOs.CartDTO;
import com.example.lab.DataBase.DTOs.CustomerDTO;
import com.example.lab.DataBase.Services.CartService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/cart")
public class CartController {
private final CartService cartService;
public CartController(CartService cartService){
this.cartService = cartService;
}
@GetMapping("/{id}")
public CartDTO getCart(@PathVariable Long id){
return new CartDTO(cartService.getCart(id));
}
@GetMapping
public List<CartDTO> getCarts(){
return cartService.getAllCarts().stream()
.map(CartDTO::new)
.toList();
}
@PutMapping("/{add}")
public void addProduct( @RequestParam("productId") Long productId,
@RequestParam("cartId") Long cartId){
cartService.addProduct(cartId, productId);
}
@PutMapping("/{delete}")
public void deleteProduct( @RequestParam("productId") Long productId,
@RequestParam("cartId") Long cartId){
cartService.deleteProduct(cartId, productId);
}
}

View File

@ -0,0 +1,69 @@
package com.example.lab.DataBase.Controllers;
import com.example.lab.DataBase.DTOs.CountProductDTO;
import com.example.lab.DataBase.Models.Cart;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.Services.CartService;
import com.example.lab.DataBase.Services.CountProductService;
import com.example.lab.DataBase.Services.ProductService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/countProduct")
public class CountProdController {
private final CountProductService countProductService;
private final CartService cartService;
private final ProductService productService;
public CountProdController(CountProductService countProductService, CartService cartService, ProductService productService){
this.countProductService = countProductService;
this.cartService = cartService;
this.productService = productService;
}
@GetMapping("/{id}")
public List<CountProductDTO> getProductsForCart(@PathVariable Long id){
return countProductService.getProductsForCart(id).stream().map(CountProductDTO::new).toList();
}
@PostMapping
public CountProductDTO deliverProduct(@RequestParam("cartId") Long cartId,
@RequestParam("productId") Long productId){
if (countProductService.getCountProduct(productId, cartId) != null){
return new CountProductDTO(countProductService.incrementProduct(productId, cartId));
}
else {
Product product = productService.getProduct(productId);
Cart cart = cartService.getCart(cartId);
return new CountProductDTO(countProductService.addCountProduct(product, cart));
}
}
@PutMapping("/{id}")
public CountProductDTO incrementProduct(@PathVariable Long id){
var countProd = countProductService.getCountProductById(id);
if (countProd != null){
return new CountProductDTO(countProductService.incrementProductById(id));
}
else {
return null;
}
}
@DeleteMapping
public CountProductDTO reduceProduct(@RequestParam("id") Long id){
var countProd = countProductService.getCountProductById(id);
if (countProd != null){
if (countProd.getAmount() == 1){
countProductService.deleteCountProductById(id);
return null;
}
else return new CountProductDTO(countProductService.decrementProductById(id));
}
else{
return null;
}
}
}

View File

@ -0,0 +1,56 @@
package com.example.lab.DataBase.Controllers;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.DTOs.CustomerDTO;
import com.example.lab.DataBase.Services.CustomerService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService){
this.customerService = customerService;
}
@GetMapping("/{id}")
public CustomerDTO getCustomer(@PathVariable Long id){
return new CustomerDTO(customerService.getCustomer(id));
}
@GetMapping
public List<CustomerDTO> getCustomers(){
return customerService.getAllCustomers().stream()
.map(CustomerDTO::new)
.toList();
}
@PostMapping
public CustomerDTO createCustomer(@RequestParam("customerLastName") String customerLastName,
@RequestParam("customerFirstName") String customerFirstName,
@RequestParam("customerAddress") String customerAddress){
final Customer customer = customerService.addCustomer(customerLastName, customerFirstName, customerAddress);
return new CustomerDTO(customer);
}
@PutMapping("/{id}")
public CustomerDTO updateCustomer(@RequestParam("customerLastName") String customerLastName,
@RequestParam("customerFirstName") String customerFirstName,
@RequestParam("customerAddress") String customerAddress,
@PathVariable Long id){
return new CustomerDTO(customerService.updateCustomer(id, customerLastName, customerFirstName, customerAddress));
}
@DeleteMapping("/{id}")
public CustomerDTO deleteCustomer(@PathVariable Long id){
return new CustomerDTO(customerService.deleteCustomer(id));
}
@DeleteMapping()
public void deleteAllCustomers(){
customerService.deleteAllCustomers();
}
}

View File

@ -0,0 +1,57 @@
package com.example.lab.DataBase.Controllers;
import com.example.lab.DataBase.DTOs.ProductCategoryDTO;
import com.example.lab.DataBase.Models.ProductCategory;
import com.example.lab.DataBase.Services.ProductCategoryService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/productCategory")
public class ProductCategoryController {
private final ProductCategoryService productCategoryService;
public ProductCategoryController(ProductCategoryService productCategoryService){
this.productCategoryService = productCategoryService;
}
@GetMapping("/{id}")
public ProductCategoryDTO getProductCategory(@PathVariable Long id){
return new ProductCategoryDTO(productCategoryService.getProductCategory(id));
}
@GetMapping
public List<ProductCategoryDTO> getProductCategories(){
return productCategoryService.getAllProductCategorys().stream()
.map(ProductCategoryDTO::new)
.toList();
}
@PostMapping
public ProductCategoryDTO createProductCategory(@RequestParam("name") String name){
final ProductCategory productCategory = productCategoryService.
addProductCategory(name);
return new ProductCategoryDTO(productCategory);
}
@PutMapping("/{id}")
public ProductCategoryDTO updateProduct(@RequestParam("name") String name,
@PathVariable Long id){
return new ProductCategoryDTO(productCategoryService.updateProductCategory
(id, name));
}
@DeleteMapping("/{id}")
public ProductCategoryDTO deleteProductCategory(@PathVariable Long id){
return new ProductCategoryDTO(productCategoryService.deleteProductCategory(id));
}
@DeleteMapping()
public void deleteAllProductCategories(){
productCategoryService.deleteAllProductCategories();
}
}

View File

@ -0,0 +1,62 @@
package com.example.lab.DataBase.Controllers;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.DTOs.ProductDTO;
import com.example.lab.DataBase.Models.ProductCategory;
import com.example.lab.DataBase.Services.ProductCategoryService;
import com.example.lab.DataBase.Services.ProductService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/product")
public class ProductController {
private final ProductService productService;
private final ProductCategoryService productCategoryService;
public ProductController(ProductService productService, ProductCategoryService productCategoryService){
this.productService = productService;
this.productCategoryService = productCategoryService;
}
@GetMapping("/{id}")
public ProductDTO getProduct(@PathVariable Long id){
return new ProductDTO(productService.getProduct(id));
}
@GetMapping
public List<ProductDTO> getProducts(){
return productService.getAllProducts().stream()
.map(ProductDTO::new)
.toList();
}
@PostMapping
public ProductDTO createProduct(@RequestParam("productName") String name,
@RequestParam("price") String price,
@RequestParam("productCategoryId") long productCategoryId){
final Product product = productService.addProduct(name, Float.parseFloat(price) ,
productCategoryService.getProductCategory(productCategoryId));
return new ProductDTO(product);
}
@PutMapping("/{id}")
public ProductDTO updateProduct(@RequestParam("productName") String name,
@RequestParam("price") float price,
@PathVariable Long id){
return new ProductDTO(productService.updateProduct(id, name, price));
}
@DeleteMapping("/{id}")
public ProductDTO deleteProduct(@PathVariable Long id){
return new ProductDTO(productService.deleteProduct(id));
}
@DeleteMapping()
public void deleteAllProducts(){
productService.deleteAllProducts();
}
}

View File

@ -0,0 +1,29 @@
package com.example.lab.DataBase.DTOs;
import java.util.List;
import com.example.lab.DataBase.Models.Cart;
public class CartDTO {
public Long id;
public String customer;
public CartDTO(Cart cart){
this.id = cart.getId();
this.customer = cart.getCustomer().getLastName() + " " + cart.getCustomer().getFirstName();
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
}

View File

@ -0,0 +1,34 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.CountProduct;
import jakarta.persistence.Column;
public class CountProductDTO {
private Long id;
public String name;
public Integer amount;
public float price;
public CountProductDTO(CountProduct countProduct){
this.id = countProduct.getId();
this.name = countProduct.getProduct().getName();
this.amount = countProduct.getAmount();
this.price = this.amount * countProduct.getProduct().getPrice();
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount){
this.amount = amount;
}
}

View File

@ -0,0 +1,49 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.Customer;
import jakarta.persistence.Column;
public class CustomerDTO {
public Long id;
public String firstName;
public String lastName;
public String customerAddress;
public CustomerDTO(Customer customer){
this.id = customer.getId();
this.lastName = customer.getLastName();
this.firstName = customer.getFirstName();
this.customerAddress = customer.getCustomerAddress();
}
public Long getId(){
return id;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getCustomerAddress(){
return customerAddress;
}
public void setId(Long id){
this.id = id;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setCustomerAddress(String customerAddress){
this.customerAddress = customerAddress;
}
}

View File

@ -0,0 +1,29 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.Models.ProductCategory;
public class ProductCategoryDTO {
public Long id;
public String name;
public ProductCategoryDTO(ProductCategory productCategory){
this.id = productCategory.getId();
this.name = productCategory.getName();
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
}

View File

@ -0,0 +1,42 @@
package com.example.lab.DataBase.DTOs;
import com.example.lab.DataBase.Models.Product;
public class ProductDTO {
public Long id;
public String name;
public float price;
public Long productCategoryId;
public String categoryName;
public ProductDTO(Product product){
this.id = product.getId();
this.name = product.getName();
this.price = product.getPrice();
this.productCategoryId = product.getProductCategory().getId();
this.categoryName = product.getProductCategory().getName();
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price){
this.price = price;
}
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Exceptions;
public class CartNotFoundException extends RuntimeException{
public CartNotFoundException(Long id){
super(String.format("Cart with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Exceptions;
public class CountProductNotFoundException extends RuntimeException{
public CountProductNotFoundException(int count){
super(String.format("Product with count: %s hasn't been found", count));
}
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Exceptions;
public class CustomerNotFoundException extends RuntimeException{
public CustomerNotFoundException(Long id){
super(String.format("Customer with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Exceptions;
public class ProductCategoryNotFoundException extends RuntimeException{
public ProductCategoryNotFoundException(Long id){
super(String.format("Product category with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Exceptions;
public class ProductNotFoundException extends RuntimeException{
public ProductNotFoundException(Long id){
super(String.format("Product with id: %s hasn't been found", id));
}
}

View File

@ -0,0 +1,75 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import java.util.*;
@Entity
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany
private List<CountProduct> countProducts;
@OneToOne
private Customer customer;
public Cart(){}
public Cart(Customer customer) {
this.countProducts = new ArrayList<>();
this.customer = customer;
}
@PreRemove
public void deleteThis(){
//deleteAllProducts();
this.getCustomer().setCart(null);
}
public void addCountProduct(CountProduct countProduct){
countProducts.add(countProduct);
if (countProduct.getCart() != this) {
countProduct.setCart(this);
}
}
public void deleteCountProduct(CountProduct countProduct){
countProducts.remove(countProduct);
if (countProduct.getCart() == this) {
countProduct.setCart(null);
}
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
if(customer.getCart()!=this){
customer.setCart(this);
}
}
public Long getId() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Cart cart = (Cart) obj;
return Objects.equals(id, cart.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,96 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.*;
@Entity
public class CountProduct {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private Integer amount;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="cart_fk")
private Cart cart;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="product_fk")
private Product product;
public CountProduct(){}
public CountProduct(Cart cart, Product product) {
this.cart = cart;
this.product = product;
this.amount = 1;
this.cart.addCountProduct(this);
this.product.addCountProduct(this);
}
public void setProduct(Product product) {
this.product = product;
if (product != null && !product.getCountProducts().contains(this)){
product.addCountProduct(this);
}
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Product getProduct() {
return product;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public void incrementAmount(){
this.amount++;
}
public void decrementAmount(){
this.amount--;
}
@PreRemove
public void deleteThis(){
if(this.product !=null) this.product.deleteCountProduct(this);
if(this.cart !=null) this.cart.deleteCountProduct(this);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
CountProduct countProducts = (CountProduct) obj;
return Objects.equals(id, countProducts.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,80 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.Objects;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "Customer's first name can't be empty")
private String firstName;
@Column
@NotBlank(message = "Customer's last name can't be empty")
private String lastName;
@Column
@NotBlank(message = "Customer's address can't be empty")
private String customerAddress;
@OneToOne(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.ALL)
private Cart cart;
public Customer(){}
public Customer(String lastName, String firstName, String customerAddress) {
this.lastName = lastName;
this.firstName = firstName;
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;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Customer customer = (Customer) obj;
return Objects.equals(id, customer.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,110 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "Product's name can't be empty")
private String name;
@Column
private float price;
@OneToMany
private List<CountProduct> countProducts;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "productCategory_fk")
private ProductCategory productCategory;
public Product(){}
public Product(String name, float price, ProductCategory productCategory){
this.name = name;
this.price = price;
this.productCategory = productCategory;
this.countProducts = new ArrayList<>();
}
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;
}
@PreRemove
public void deleteThis(){
//deleteAllCarts();
this.productCategory.getProducts().remove(this);
}
public List<CountProduct> getCountProducts(){
return countProducts;
}
public void addCountProduct(CountProduct countProduct){
countProducts.add(countProduct);
if (countProduct.getProduct() != this) {
countProduct.setProduct(this);
}
}
public void deleteCountProduct(CountProduct countProduct){
countProducts.remove(countProduct);
if (countProduct.getProduct() == this) {
countProduct.setProduct(null);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Product product = (Product) obj;
return Objects.equals(id, product.id);
}
@Override
public int hashCode(){
return Objects.hashCode(id);
}
}

View File

@ -0,0 +1,68 @@
package com.example.lab.DataBase.Models;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.*;
@Entity
public class ProductCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "Product category name can't be empty")
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "productCategory", cascade = CascadeType.ALL)
private List<Product> 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<Product>();
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Product> 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);
}
}

View File

@ -0,0 +1,8 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CartRepository extends JpaRepository<Cart, Long> {
}

View File

@ -0,0 +1,12 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.CountProduct;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.Collection;
public interface CountProductRepository extends JpaRepository<CountProduct, Long> {
@Query("SELECT p FROM CountProduct p WHERE p.cart.id = ?1")
Collection<CountProduct> findAllProductsByCartId(Long cartId);
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.ProductCategory;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Long> {
}

View File

@ -0,0 +1,7 @@
package com.example.lab.DataBase.Repositories;
import com.example.lab.DataBase.Models.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}

View File

@ -0,0 +1,93 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.Models.Product;
import com.example.lab.DataBase.Repositories.CustomerRepository;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.example.lab.DataBase.Models.Cart;
import com.example.lab.DataBase.Repositories.CartRepository;
import com.example.lab.DataBase.Exceptions.CartNotFoundException;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import com.example.lab.DataBase.util.Validation.ValidationException;
import java.util.List;
@Service
public class CartService {
private final ProductService productService;
private final CountProductService countProductService;
private final CartRepository cartRepository;
private final ValidatorUtil validatorUtil;
public CartService(ProductService productService, CountProductService countProductService,
CartRepository cartRepository, ValidatorUtil validatorUtil){
this.productService = productService;
this.countProductService = countProductService;
this.cartRepository = cartRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Cart addCart(Customer customer){
Cart cart = new Cart(customer);
validatorUtil.validate(cart);
return cartRepository.save(cart);
}
@Transactional()
public Cart getCart(Long id){
return cartRepository.findById(id).orElseThrow(() -> new CartNotFoundException(id));
}
@Transactional
public List<Cart> getAllCarts(){
return cartRepository.findAll();
}
@Transactional
public Cart deleteCart(Long id){
Cart cart = getCart(id);
cartRepository.delete(cart);
return cart;
}
@Transactional
public void deleteAllCarts(){
cartRepository.deleteAll();
}
@Transactional
public Product addProduct(Long cartId, Long productId){
Product product = productService.getProduct(productId);
Cart cart = getCart(cartId);
var countProduct = countProductService.getCountProduct(productId, cartId);
if(countProduct == null) countProduct = countProductService.addCountProduct(product, cart);
countProduct.incrementAmount();
cartRepository.save(cart);
return product;
}
@Transactional
public Product deleteProduct(Long cartId, Long productId){
Product product = productService.getProduct(productId);
Cart cart = getCart(cartId);
var countProduct = countProductService.getCountProduct(productId, cartId);
if(countProduct == null) return null;
countProductService.deleteCountProduct(productId,cartId);
cartRepository.save(cart);
return product;
}
@Transactional
public Product reduceProduct(Long cartId, Long productId){
Product product = productService.getProduct(productId);
Cart cart = getCart(cartId);
var countProduct = countProductService.getCountProduct(productId, cartId);
if(countProduct == null) return null;
var resProd = countProductService.decrementProduct(productId, cartId);
cartRepository.save(cart);
return product;
}
}

View File

@ -0,0 +1,99 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.Models.*;
import com.example.lab.DataBase.Repositories.CountProductRepository;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.example.lab.DataBase.Models.Product;
import java.util.List;
@Service
public class CountProductService {
private final CountProductRepository countProductRepository;
private final ValidatorUtil validatorUtil;
public CountProductService(CountProductRepository countProductRepository,
ValidatorUtil validatorUtil){
this.countProductRepository= countProductRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public CountProduct addCountProduct(Product product,
Cart cart){
CountProduct countProduct = new CountProduct(cart, product);
validatorUtil.validate(countProduct);
return countProductRepository.save(countProduct);
}
@Transactional
public CountProduct getCountProduct(long productId, long cartId){
var count = getAllCountProducts();
var countProduct = count.stream().filter(x -> x.getProduct().getId() == productId && x.getCart().getId() == cartId ).findFirst();
if(countProduct.isEmpty()) return null;
else return countProduct.get();
}
@Transactional
public CountProduct getCountProductById(long id){
return countProductRepository.findById(id).orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional
public CountProduct incrementProduct (long productId, long cartId){
CountProduct countProduct = getCountProduct(productId, cartId);
countProduct.incrementAmount();
return countProductRepository.save(countProduct);
}
@Transactional
public CountProduct incrementProductById(long id){
CountProduct countProduct = getCountProductById(id);
countProduct.incrementAmount();
return countProductRepository.save(countProduct);
}
@Transactional
public CountProduct decrementProduct (long productId, long cartId){
CountProduct countProduct = getCountProduct(productId, cartId);
countProduct.decrementAmount();
return countProductRepository.save(countProduct);
}
@Transactional
public CountProduct decrementProductById (Long id){
CountProduct countProduct = getCountProductById(id);
countProduct.decrementAmount();
return countProductRepository.save(countProduct);
}
@Transactional
public CountProduct deleteCountProduct(long productId, long cartId){
CountProduct countProduct = getCountProduct(productId,cartId);
countProductRepository.delete(countProduct);
return countProduct;
}
@Transactional
public CountProduct deleteCountProductById(long id){
CountProduct countProduct = getCountProductById(id);
countProductRepository.delete(countProduct);
return countProduct;
}
@Transactional
public void deleteAll(){
countProductRepository.deleteAll();
}
@Transactional
public List<CountProduct> getAllCountProducts(){
return countProductRepository.findAll();
}
@Transactional
public List<CountProduct> getProductsForCart(Long cartId) { return countProductRepository.findAllProductsByCartId(cartId).stream().toList();}
}

View File

@ -0,0 +1,65 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.Repositories.CustomerRepository;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import com.example.lab.DataBase.util.Validation.ValidationException;
import java.util.List;
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
private final CartService cartService;
private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository, CartService cartService,
ValidatorUtil validatorUtil){
this.customerRepository = customerRepository;
this.cartService = cartService;
this.validatorUtil = validatorUtil;
}
@Transactional
public Customer addCustomer(String customerFirstName, String customerLastName, String customerAddress){
Customer customer = new Customer(customerLastName, customerFirstName, customerAddress);
validatorUtil.validate(customer);
var cus = customerRepository.save(customer);
cartService.addCart(cus);
return cus;
}
@Transactional()
public Customer getCustomer(Long id){
return customerRepository.findById(id).orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional
public List<Customer> getAllCustomers(){
return customerRepository.findAll();
}
@Transactional
public Customer updateCustomer(Long id, String customerLastName, String customerFirstName, String customerAddress){
final Customer customer = getCustomer(id);
customer.setLastName(customerLastName);
customer.setFirstName(customerFirstName);
customer.setCustomerAddress(customerAddress);
validatorUtil.validate(customer);
return customerRepository.save(customer);
}
@Transactional
public Customer deleteCustomer(Long id){
Customer customer = getCustomer(id);
customerRepository.delete(customer);
return customer;
}
@Transactional
public void deleteAllCustomers(){
customerRepository.deleteAll();
}
}

View File

@ -0,0 +1,58 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.ProductCategoryNotFoundException;
import com.example.lab.DataBase.Repositories.ProductCategoryRepository;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.ProductCategory;
import java.util.List;
@Service
public class ProductCategoryService {
private final ProductCategoryRepository productCategoryRepository;
private final ValidatorUtil validatorUtil;
public ProductCategoryService(ProductCategoryRepository productCategoryRepository,
ValidatorUtil validatorUtil){
this.productCategoryRepository = productCategoryRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public ProductCategory addProductCategory(String name){
ProductCategory productCategory = new ProductCategory(name);
validatorUtil.validate(productCategory);
return productCategoryRepository.save(productCategory);
}
@Transactional()
public ProductCategory getProductCategory(Long id){
return productCategoryRepository.findById(id).orElseThrow(() -> new ProductCategoryNotFoundException(id));
}
@Transactional
public List<ProductCategory> getAllProductCategorys(){
return productCategoryRepository.findAll();
}
@Transactional
public ProductCategory updateProductCategory(Long id, String productCategoryName){
final ProductCategory productCategory = getProductCategory(id);
productCategory.setName(productCategoryName);
validatorUtil.validate(productCategory);
return productCategoryRepository.save(productCategory);
}
@Transactional
public ProductCategory deleteProductCategory(Long id){
final ProductCategory productCategory = getProductCategory(id);
productCategoryRepository.delete(productCategory);
return productCategory;
}
@Transactional
public void deleteAllProductCategories(){
productCategoryRepository.deleteAll();
}
}

View File

@ -0,0 +1,62 @@
package com.example.lab.DataBase.Services;
import com.example.lab.DataBase.Exceptions.ProductNotFoundException;
import com.example.lab.DataBase.Models.Customer;
import com.example.lab.DataBase.Models.ProductCategory;
import com.example.lab.DataBase.Repositories.ProductRepository;
import com.example.lab.DataBase.util.Validation.ValidatorUtil;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.example.lab.DataBase.Models.Product;
import java.util.List;
@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, float price, ProductCategory productCategory){
Product product = new Product(name, price, productCategory);
validatorUtil.validate(product);
return productRepository.save(product);
}
@Transactional()
public Product getProduct(Long id){
return productRepository.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
}
@Transactional
public List<Product> getAllProducts(){
return productRepository.findAll();
}
@Transactional
public Product updateProduct(Long id, String name, float price){
final Product product = getProduct(id);
product.setName(name);
product.setPrice(price);
validatorUtil.validate(product);
return productRepository.save(product);
}
@Transactional
public Product deleteProduct(Long id){
final Product product = getProduct(id);
productRepository.delete(product);
return product;
}
@Transactional
public void deleteAllProducts(){
productRepository.deleteAll();
}
}

View File

@ -0,0 +1,44 @@
package com.example.lab.DataBase.util.Error;
import java.util.stream.Collectors;
import com.example.lab.DataBase.Exceptions.CountProductNotFoundException;
import com.example.lab.DataBase.Exceptions.ProductCategoryNotFoundException;
import com.example.lab.DataBase.Exceptions.CustomerNotFoundException;
import com.example.lab.DataBase.Exceptions.ProductNotFoundException;
import com.example.lab.DataBase.Exceptions.CartNotFoundException;
import com.example.lab.DataBase.util.Validation.ValidationException;
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;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
CustomerNotFoundException.class,
ProductCategoryNotFoundException.class,
ProductNotFoundException.class,
CountProductNotFoundException.class,
CartNotFoundException.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.lab.DataBase.util.Validation;
import java.util.Set;
public class ValidationException extends RuntimeException{
public ValidationException(Set<String> errors){
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,30 @@
package com.example.lab.DataBase.util.Validation;
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,77 +1,16 @@
package com.example.lab;
import com.example.lab.AllTypeCalc.controller.CalcController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class LabApplication {
public static void main(String[] args) {
SpringApplication.run(LabApplication.class, args);
}
@GetMapping("/calculateSquare")
public String calculateSquare(@RequestParam int num,
@RequestParam int step) {
double res;
res = Math.pow(num,step);
return ("Результат: " + Double.toString(res));
}
@GetMapping("/calculateFactorial")
public String calculateFactorial(@RequestParam int num) {
long res = 1;
for (int i = 1; i <= num; i++) {
res = res * i;
}
return ("Результат: " + Long.toString(res));
}
public int getFibonacciValue(int n) {
if (n <= 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
return getFibonacciValue(n - 1) + getFibonacciValue(n - 2);
}
}
@GetMapping("/calculateFibbN")
public String calculateFibbN(@RequestParam int num) {
int result = 0;
result = getFibonacciValue(num);
return ("Результат: " + Integer.toString(result));
}
public static boolean checkSimple(int i){
if (i<=1)
return false;
else if (i <=3)
return true;
else if (i%2==0 || i %3 ==0)
return false;
int n = 5;
while (n*n <=i){
if (i % n ==0 || i % (n+2) == 0)
return false;
n=n+6;
}
return true;
}
@GetMapping("/calculateLastSimple")
public String calculateSimple(@RequestParam int num){
int result = 0;
for (int i=2;i<=num;i++){
if(checkSimple(i))
result = i;
}
return ("Результат: " + Integer.toString(result));
}
}

View File

@ -0,0 +1,13 @@
package com.example.lab;
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

@ -1 +1,11 @@
spring.main.banner-mode=off
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +1,117 @@
package com.example.lab;
import com.example.lab.DataBase.Models.*;
import com.example.lab.DataBase.Services.CartService;
import com.example.lab.DataBase.Services.CustomerService;
import com.example.lab.DataBase.Services.ProductCategoryService;
import com.example.lab.DataBase.Services.ProductService;
import com.example.lab.DataBase.Services.CountProductService;
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;
@Autowired
CountProductService countProductService;
@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");
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(){
countProductService.deleteAll();
productService.deleteAllProducts();
cartService.deleteAllCarts();
customerService.deleteAllCustomers();
productCategoryService.deleteAllProductCategories();
}
}

View File

@ -1,13 +1,67 @@
package com.example.lab;
import com.example.lab.AllTypeCalc.service.CalcService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LabApplicationTests {
@Autowired
CalcService calcService;
@Test
void contextLoads() {
void testIntSum() {
final Object result = calcService.GetSum(1, 2, "int");
Assertions.assertEquals("3", result.toString());
}
@Test
void testStringSum() {
final Object result = calcService.GetSum("ab", "bc", "str");
Assertions.assertEquals("abbc", result.toString());
}
@Test
void testIntMinus() {
final Object result = calcService.GetMinus(5, 4, "int");
Assertions.assertEquals("1", result.toString());
}
@Test
void testStringMinus() {
final Object result = calcService.GetMinus("abc", "bc", "str");
Assertions.assertEquals("a", result.toString());
}
@Test
void testIntMult() {
final Object result = calcService.GetMult(4, 4, "int");
Assertions.assertEquals("16", result.toString());
}
@Test
void testStringMult() {
final Object result = calcService.GetMult("ab", "bc", "str");
Assertions.assertEquals("abab", result.toString());
}
@Test
void testIntDiv() {
final Object result = calcService.GetDiv(12, 6, "int");
Assertions.assertEquals("2", result.toString());
}
@Test
void testStringDiv() {
final Object result = calcService.GetDiv("ab", "bc", "str");
Assertions.assertEquals("1.0", result.toString());
}
@Test
void testCalculatorErrorWired() {
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> calcService.GetSum("1", "1", "integer"));
}
}

View File

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=user
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop

BIN
front/images/arrow.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

BIN
front/images/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

BIN
front/images/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

BIN
front/images/logo_color.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -1,27 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Интернет программирование</title>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet"/>
<script src="scripts.js"></script>
</head>
<body class="ms-3">
<h3 class="mt-2">Вычисления</h3>
<div class="d-flex form-group">
<label class="m-2" for="textFieldNum">Число 1:</label>
<input type="number" class="form-control w-25" id="textFieldNum" placeholder="Введите число...">
<label class="m-2" for="textFieldNum2">Число 2:</label>
<input type="number" class="form-control w-25" id="textFieldNum2" placeholder="Введите число...">
</div>
<div>
<button id = "1" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Степень</button>
<button id = "2" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Факториал</button>
<button id = "3" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Фибоначчи</button>
<button id = "4" class="btn btn-primary w-auto mt-2 ms-3" onclick="Okclick(this.id)">Простое число</button>
</div>
<a id="res"></a>
</body>
<html lang="ru" class="h-100">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
<title>4th lab</title>
</head>
<body class="h-100 bg-light m-0">
<article class="h-100">
<div id="app" class="h-100"></div>
<script type="module" src="/src/main.jsx"></script>
</article>
</body>
</html>

4691
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,19 +1,26 @@
{
"name": "thistore",
"name": "test",
"version": "1.0.0",
"description": "Internet Programming labs",
"main": "MainPage.html",
"type": "module",
"scripts": {
"start": "http-server -p 3000 ./",
"test": "echo \"Error: no test specified\" && exit 1"
"dev": "vite",
"start": "npm-run-all --parallel dev",
"build": "vite build",
"preview": "vite preview"
},
"author": "Nevaeva Ksenia",
"license": "ISC",
"dependencies": {
"bootstrap": "5.2.1",
"@fortawesome/fontawesome-free": "6.2.0"
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4",
"axios": "^1.1.3",
"bootstrap": "^5.2.2",
"@fortawesome/fontawesome-free": "^6.2.1"
},
"devDependencies": {
"http-server": "14.1.1"
"@types/react": "^18.0.24",
"@types/react-dom": "^18.0.8",
"vite": "^3.2.3",
"@vitejs/plugin-react": "^2.2.0",
"npm-run-all": "^4.1.5"
}
}
}

View File

@ -1,26 +0,0 @@
function Okclick(clicked) {
var num = document.getElementById("textFieldNum").value
var num2 = document.getElementById("textFieldNum2").value
var id = clicked;
var argument = "";
if(id == "1"){
argument = ("calculateSquare?num=" + num +"&step=" + num2);
}
else if (id == "2"){
argument = ("calculateFactorial?num=" + num);
}
else if( id == "3"){
argument = ("calculateFibbN?num=" + num);
}
else if (id == "4"){
argument = ("calculateLastSimple?num=" + num);
}
fetch ("http://127.0.0.1:8080/" + argument)
.then(response => response.text())
.then((response) => {
console.log(response)
document.getElementById("res").innerHTML = response
})
}

45
front/src/App.jsx Normal file
View File

@ -0,0 +1,45 @@
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Header from './components/common/Header';
import CustomerPage from './components/pages/customerPage';
import ProductPage from './components/pages/productPage';
import ProductCategoryPage from './components/pages/productCategoryPage';
import CartsPage from './components/pages/cartsPage';
import CartPage from './components/pages/cartPage';
import './style.css';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const routes = [
{ index: true, element: <CustomerPage/> },
{ path: 'customer', element: <CustomerPage/>, label:'Покупатели'},
{ path: 'carts', element: <CartsPage/>, label: 'Корзины' },
{ path: 'product', element: <ProductPage/>, label: 'Товары' },
{ path: 'productCategory', element: <ProductCategoryPage/>, label: 'Категории товаров'},
{ path: 'cart', element: <CartPage/>},
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
console.info('render links');
return (
<>
<Header links={links} />
<div className="container-fluid">
<Outlet />
</div>
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

9
front/src/Main.jsx Normal file
View File

@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('app')).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

View File

@ -0,0 +1,103 @@
import { useState, useEffect } from "react";
import Modal from './Modal';
import DataService from '../../services/DataService';
import Toolbar from './Toolbar';
import Table from './CartsTable';
export default function CartTable(props){
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.getAllUrl, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
if (!isEdit) {
DataService.create(props.url, "?customerLastName=" + props.data.lastName
+ "&customerFirstName=" + props.data.firstName
+ "&customerAddress=" + props.data.customerAddress).then(() => loadItems());
} else {
DataService.update(props.getUrl + props.data.id, "?customerLastName=" + props.data.lastName
+ "&customerFirstName=" + props.data.firstName
+ "&customerAddress=" + props.data.customerAddress).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Создание');
setModalConfirm('Создать');
setModalVisible(true);
props.onAdd();
}
function handleEdit() {
if (selectedItems.length === 0) {
return;
}
edit(selectedItems[0]);
}
function edit(editedId) {
DataService.read(props.getUrl + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование пользователя');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.getUrl + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return(
<>
<Table
headers={props.headers}
items={items}
selectable={false}/>
</>
)
}

View File

@ -0,0 +1,73 @@
import { useState } from 'react';
import styles from './Table.module.css';
export default function Table(props) {
const [tableUpdate, setTableUpdate] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
function isSelected(id) {
if (!props.selectable) {
return false;
}
return selectedItems.includes(id);
}
function click(id) {
if (!props.selectable) {
return;
}
if (isSelected(id)) {
var index = selectedItems.indexOf(id);
if (index !== -1) {
selectedItems.splice(index, 1);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
} else {
selectedItems.push(id);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
props.onClick(selectedItems);
}
function dblClick(id) {
if (!props.selectable) {
return;
}
props.onDblClick(id);
}
return (
<table className={`table table-success table-hover ${styles.table} ${props.selectable ? styles.selectable : '' } `}>
<thead>
<tr>
<th scope="col">#</th>
{
props.headers.map(header =>
<th key={header.name} scope="col">
{header.label}
</th>
)
}
</tr>
</thead>
<tbody>
{
props.items.map((item, index) =>
<tr key={item.id}
className={isSelected(item.id) ? styles.selected : ''}
onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}>
<th scope="row"><a href={"/cart?id=" + item.id}>{index + 1}</a></th>
{
props.headers.map(header =>
<td key={item.id + header.name}>{item[header.name]}</td>
)
}
</tr>
)
}
</tbody >
</table >
);
}

View File

@ -0,0 +1,102 @@
import { useState, useEffect } from "react";
import Modal from './Modal';
import DataService from '../../services/DataService';
import Toolbar from './ToolbarOnlyAdd'
import Table from './TableProduct';
export default function CustomerTable(props){
const [items, setItems] = useState([]);
const [cartId, setCartId] = useState(0);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var cartId = urlParams.get('id');
console.log(cartId);
setCartId(cartId);
DataService.readAll(props.getAllUrl + cartId, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
DataService.create(props.getUrl, "?cartId=" + cartId
+ "&productId=" + props.data.productId).then(() => loadItems());
}
function handleAdd() {
setEdit(false);
setModalHeader('Регистрация');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
function edit(editedId) {
DataService.read(props.getUrl + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование пользователя');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function add(prodId){
console.log(prodId);
DataService.update(props.url, prodId).then((results) => loadItems());
}
function remove(prodId) {
DataService.delete(props.getUrl + "?id=" + prodId).then((results) => loadItems());
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return(
<>
<h2>Корзина {cartId}</h2>
<Toolbar onAdd={handleAdd}/>
<Table
headers={props.headers}
items={items}
selectable={false}
add={add}
remove={remove}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
)
}

View File

@ -0,0 +1,117 @@
import { useState, useEffect } from "react";
import Modal from './Modal';
import DataService from '../../services/DataService';
import Toolbar from './Toolbar';
import Table from './Table';
export default function CustomerTable(props){
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.getAllUrl, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
if (!isEdit) {
DataService.create(props.url, "?customerLastName=" + props.data.lastName
+ "&customerFirstName=" + props.data.firstName
+ "&customerAddress=" + props.data.customerAddress).then(() => loadItems());
} else {
DataService.update(props.getUrl + props.data.id, "?customerLastName=" + props.data.lastName
+ "&customerFirstName=" + props.data.firstName
+ "&customerAddress=" + props.data.customerAddress).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Регистрация');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
function handleEdit() {
if (selectedItems.length === 0) {
return;
}
edit(selectedItems[0]);
}
function edit(editedId) {
DataService.read(props.getUrl + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование пользователя');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.getUrl + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return(
<>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}/>
<Table
headers={props.headers}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
)
}

View File

@ -0,0 +1,38 @@
import { NavLink } from 'react-router-dom';
import './style.css';
export default function Header(props) {
return (
<header className="d-flex flex-row">
<div id="leftPart" className="d-flex flex-row">
<div className="logo mt-2 mb-2 ms-3 me-1">
<a href="/">
<img src="images/logo.png" width="60" height="60px" />
</a>
</div>
<div id="siteName" className="mt-0">
ThiStore
</div>
<div id="mainPage" className="mt-2 ms-3 text-nowrap">
</div>
</div>
<nav className="navbar navbar-expand-md">
<div className="container-fluid" id="navigationMenu">
<button className="navbar-toggler mt-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="navbar-collapse collapse justify-content-end" id="navbarNav">
<ul className="navbar-nav d-flex flex-row">
{
props.links.map(route=>
<div id="listItemsMy" key ={route.path} className="nav-item d-flex text-nowrap"><NavLink className="nav-link d-inline" to ={route.path}>{route.label}</NavLink></div>
)
}
</ul>
</div>
</div>
</nav>
</header>
);
}

View File

@ -0,0 +1,46 @@
import React from "react";
export default function Modal(props) {
const formRef = React.createRef();
function hide() {
props.onHide();
}
function done(e) {
e.preventDefault();
if (formRef.current.checkValidity()) {
props.onDone();
hide();
} else {
formRef.current.reportValidity();
}
}
return (
<div className="modal fade show" tabIndex="-1" aria-hidden="true"
style={{ display: props.visible ? 'block' : 'none' }}>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h1 className="modal-title fs-5" id="exampleModalLabel">{props.header}</h1>
<button className="btn-close" type="button" aria-label="Close"
onClick={hide}></button>
</div>
<div className="modal-body">
<form ref={formRef} onSubmit={done}>
{props.children}
</form>
</div>
<div className="modal-footer">
<button className="btn btn-secondary" type="button" onClick={hide}>Закрыть</button>
<button className="btn btn-primary" type="button" onClick={done}>
{props.confirm}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,113 @@
import { useState, useEffect } from "react";
import Modal from './Modal';
import DataService from '../../services/DataService';
import Toolbar from './Toolbar';
import Table from './Table';
export default function ProductCategoryTable(props){
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.getAllUrl, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
if (!isEdit) {
DataService.create(props.url, "?name=" + props.data.name).then(() => loadItems());
} else {
DataService.update(props.getUrl + props.data.id, "?name=" + props.data.name).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Добавления категории');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
function handleEdit() {
if (selectedItems.length === 0) {
return;
}
edit(selectedItems[0]);
}
function edit(editedId) {
DataService.read(props.getUrl + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование пользователя');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.getUrl + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return(
<>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}/>
<Table
headers={props.headers}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
)
}

View File

@ -0,0 +1,114 @@
import { useState, useEffect } from "react";
import Modal from './Modal';
import DataService from '../../services/DataService';
import Toolbar from './Toolbar';
import Table from './Table';
export default function ProductTable(props){
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState('');
const [modalConfirm, setModalConfirm] = useState('');
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
let selectedItems = [];
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.getAllUrl, props.transformer)
.then(data => setItems(data));
}
function saveItem() {
console.log("Createing product");
if (!isEdit) {
DataService.create(props.url, "?productName=" + props.data.name + "&price=" + props.data.price + "&productCategoryId=" + props.data.productCategoryId).then(() => loadItems());
} else {
DataService.update(props.getUrl + props.data.id, "?productName=" + props.data.name + "&price=" + props.data.price + "&productCategoryId=" + props.data.productCategoryId).then(() => loadItems());
}
}
function handleAdd() {
setEdit(false);
setModalHeader('Добавления товара');
setModalConfirm('Добавить');
setModalVisible(true);
props.onAdd();
}
function handleEdit() {
if (selectedItems.length === 0) {
return;
}
edit(selectedItems[0]);
}
function edit(editedId) {
DataService.read(props.getUrl + editedId, props.transformer)
.then(data => {
setEdit(true);
setModalHeader('Редактирование пользователя');
setModalConfirm('Сохранить');
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove() {
if (selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(props.getUrl + item));
});
Promise.all(promises).then((results) => {
selectedItems.length = 0;
loadItems();
});
}
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
edit(tableSelectedItem);
}
function handleModalHide() {
setModalVisible(false);
}
function handleModalDone() {
saveItem();
}
return(
<>
<Toolbar
onAdd={handleAdd}
onEdit={handleEdit}
onRemove={handleRemove}/>
<Table
headers={props.headers}
items={items}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}>
{props.children}
</Modal>
</>
)
}

View File

@ -0,0 +1,73 @@
import { useState } from 'react';
import styles from './Table.module.css';
export default function Table(props) {
const [tableUpdate, setTableUpdate] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
function isSelected(id) {
if (!props.selectable) {
return false;
}
return selectedItems.includes(id);
}
function click(id) {
if (!props.selectable) {
return;
}
if (isSelected(id)) {
var index = selectedItems.indexOf(id);
if (index !== -1) {
selectedItems.splice(index, 1);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
} else {
selectedItems.push(id);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
props.onClick(selectedItems);
}
function dblClick(id) {
if (!props.selectable) {
return;
}
props.onDblClick(id);
}
return (
<table className={`table table-success table-hover ${styles.table} ${props.selectable ? styles.selectable : '' } `}>
<thead>
<tr>
<th scope="col">#</th>
{
props.headers.map(header =>
<th key={header.name} scope="col">
{header.label}
</th>
)
}
</tr>
</thead>
<tbody>
{
props.items.map((item, index) =>
<tr key={item.id}
className={isSelected(item.id) ? styles.selected : ''}
onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}>
<th scope="row">{index + 1}</th>
{
props.headers.map(header =>
<td key={item.id + header.name}>{item[header.name]}</td>
)
}
</tr>
)
}
</tbody >
</table >
);
}

View File

@ -0,0 +1,12 @@
.table tbody tr {
user-select: none;
}
.selectable tbody tr:hover {
cursor: pointer;
}
.selected {
background-color: #0d6efd;
opacity: 80%;
}

View File

@ -0,0 +1,90 @@
import { useState } from 'react';
import styles from './Table.module.css';
export default function Table(props) {
const [tableUpdate, setTableUpdate] = useState(false);
const [selectedItems, setSelectedItems] = useState([]);
function isSelected(id) {
if (!props.selectable) {
return false;
}
return selectedItems.includes(id);
}
function click(id) {
if (!props.selectable) {
return;
}
if (isSelected(id)) {
var index = selectedItems.indexOf(id);
if (index !== -1) {
selectedItems.splice(index, 1);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
} else {
selectedItems.push(id);
setSelectedItems(selectedItems);
setTableUpdate(!tableUpdate);
}
props.onClick(selectedItems);
}
function dblClick(id) {
if (!props.selectable) {
return;
}
props.onDblClick(id);
}
function add(prodId){
props.add(prodId);
}
function remove(prodId){
props.remove(prodId);
}
return (
<table className={`table table-success table-hover ${styles.table} ${props.selectable ? styles.selectable : '' } `}>
<thead>
<tr>
<th scope="col">#</th>
{
props.headers.map(header =>
<th key={header.name} scope="col">
{header.label}
</th>
)
}
<th></th>
</tr>
</thead>
<tbody>
{
props.items.map((item, index) =>
<tr key={item.id}
className={isSelected(item.id) ? styles.selected : ''}
onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}>
<th scope="row">{index + 1}</th>
{
props.headers.map(header =>
<td key={item.id + header.name}>{item[header.name]}</td>
)
}
<td>
<button type="button" className='btn btn-success mx-2' onClick={(e) => add(item.id, e)}>
+
</button>
<button type="button" className='btn btn-danger mx-2' onClick={(e) => remove(item.id, e)}>
-
</button>
</td>
</tr>
)
}
</tbody >
</table >
);
}

View File

@ -0,0 +1,29 @@
import styles from './Toolbar.module.css';
export default function Toolbar(props) {
function add() {
props.onAdd();
}
function edit() {
props.onEdit();
}
function remove() {
props.onRemove();
}
return (
<div className="btn-group mt-2" role="group">
<button type="button" className={`btn btn-success ${styles.btn}`} onClick={add}>
Добавить
</button>
<button type="button" className={`btn btn-warning ${styles.btn}`} onClick={edit} >
Изменить
</button >
<button type="button" className={`btn btn-danger ${styles.btn}`} onClick={remove}>
Удалить
</button >
</div >
);
}

View File

@ -0,0 +1,3 @@
.btn {
min-width: 140px;
}

View File

@ -0,0 +1,15 @@
import styles from './Toolbar.module.css';
export default function Toolbar(props) {
function add() {
props.onAdd();
}
return (
<div className="btn-group mt-2" role="group">
<button type="button" className={`btn btn-success ${styles.btn}`} onClick={add}>
Добавить
</button>
</div >
);
}

View File

@ -0,0 +1,473 @@
.mainHtml{
background-color: #ffb84b !important;
}
.hide{
display: none;
}
.active{
display: block;
}
.active img {
height: auto;
}
header {
height: fit-content;
background-image: linear-gradient(to right, #ff8400 , #ffc156);
align-items: center;
}
img.center {
display: block;
margin: 0 auto;
}
div.colorBG{
background-color: #ffb84b;
}
.firstPart div {
display: flex;
}
.firstPart figcaption {
color: white;
text-align: center;
}
#salePrice{
font-family: 'Agency FB Bold', arial;
margin-top: -10px;
}
.adIphone {
color: white;
font-family: 'Antipasto Pro', sans-serif;
font-size: 28px;
}
#saleText{
color: red;
font-size: 35px;
}
#specialText{
font-size: 40px;
color: red;
}
.adIphone figure img{
text-align: justify-all;
}
.menu {
flex-grow: 1;
}
.menu a,
.menu .active {
font-family: 'Antipasto Pro', sans-serif;
display: block;
padding: 8px 10px;
color: white;
font-size: 22px;
text-decoration: none;
}
.menu .active {
color: #fff;
background-color: #ff3d00;
border-radius: 8px;
}
#siteName{
color: white;
font-family: 'Agency FB Bold', arial;
font-size: 36px;
}
#mainPage{
font-size: 27px;
}
#mainPage a{
font-family: 'Antipasto Pro', sans-serif;
color: white;
text-decoration: none;
}
div.colorBG{
background-color: #ffb84b;
}
.firstPart{
background-image: url(images/banner.png);
background-repeat: no-repeat;
background-size: 107%;
}
.firstPart figure {
margin-inline-start: 10px;
margin-block-start: 10px;
}
footer {
background-image: linear-gradient(to right, #ff8400 , #ffc156);
}
.socialMedia{
margin-right: 5px;
margin-left: auto;
}
.socialMedia figcaption{
font-family: 'Antipasto Pro', sans-serif;
}
.copyright {
margin-right: 10px;
flex-basis: 98%;
text-align: right;
color: white;
font-family: 'Agency FB', arial;
}
#weInSocial {
color: white;
}
.aboutUsFooter{
font-family: 'Antipasto Pro', sans-serif;
}
.aboutUsFooter a{
text-decoration: none;
color: white;
}
.aboutUsFooter li{
list-style-type: none;
margin: 7px 0;
}
.aboutUsText figcaption {
color: #ff8400;
font-family: 'Antipasto Pro', sans-serif;
font-size: 46px;
}
#loremIpsumText{
color: black;
font-size: 20px;
margin-right: 15%;
margin-left: 15%;
}
#leftColumn{
flex-direction: column;
}
#middleColumn{
flex-direction: column;
}
#rightColumn{
text-align: center;
display: flex;
flex-direction: column;
}
.item{
text-align: center;
font-family: Segoe UI;
font-weight: bold;
font-size: 18px;
}
.item figcaption{
color: black;
}
#Items {
columns: 3;
column-gap: 1em;
}
* {box-sizing: border-box;}
form {
position: relative;
width: 400px;
margin-top: 20px;
margin-left: auto;
margin-right: auto;
background-image: linear-gradient(to right, #ff8400 , #ffc156);
}
input, button {
border: none;
outline: none;
background: transparent;
}
input {
height: 42px;
}
.searchbutton{
height: 42px;
width: 42px;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
button .searchbutton:before {
font-family: FontAwesome;
font-size: 16px;
color: #F9F0DA;
}
.orders{
width: 1000px;
display: block;
float: none;
height: 350px;
background: #ffc156;
border: 1px solid #C1C1C1;
overflow: auto;
}
#activeOrders {
font-family: 'Antipasto Pro', sans-serif;
text-align: center;
font-size: 20px;
margin-top: 10px;
color: #c06300;
}
#listOfInf{
background-color: #ffc156;
height: 150px;
width: 900px;
vertical-align: center;
margin-top: 15px;
display: flex;
}
#listOfInf li{
color: #c06300;
list-style-type: none;
font-family: 'Antipasto Pro', sans-serif;
margin: 9px 0;
}
.orderItem{
display: flex;
}
.nameItem{
margin-top: 20px;
color: white;
font-family: 'Antipasto Pro', sans-serif;
margin-left: 0px;
}
.priceItem {
color: white;
font-family: 'Antipasto Pro', sans-serif;
margin-bottom: 30px;
margin-top: auto;
margin-right: 100px;
margin-left: auto;
}
.deleteItem button{
color: white;
width: auto;
height: 25px;
font-family: 'Antipasto Pro', sans-serif;
font-size: 16px;
position: relative;
left: 10%;
top: 73%;
transform: translate(-70%, 0);
background: #ff8400;
}
.ordersCart{
margin-left: auto;
margin-right: auto;
margin-bottom: 30px;
margin-top: 30px;
width: 1000px;
display: block;
float: none;
height: auto;
background: #ffc156;
border: 1px solid #C1C1C1;
overflow: auto;
}
.orderItems button{
color: white;
width: auto;
height: 40px;
font-family: 'Antipasto Pro', sans-serif;
font-size: 36px;
position: relative;
left: 85%;
top: 73%;
transform: translate(-70%, 0);
background: #ff8400;
margin-bottom: 50px;
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
color: white;
font-family: 'Antipasto Pro', sans-serif;
}
@media (max-width: 550px){
.nameItem{
font-size: 12px;
}
.deleteItem{
font-size: 12px;
}
.priceItem{
font-size: 12px;
}
.orderItem img{
height: 120px;
width: auto;
}
.orderItems button {
font-size: 16px;
}
}
@media(max-width: 500px){
header{
flex-direction: column;
}
#mainPage{
margin-top: 0px;
}
#leftPart a{
font-size: 12px;
text-align: left;
margin-top: 0;
padding-top: 0;
}
.logo img{
margin-top: 10px;
width: 35px;
height: 35px;
margin-top: 10px;
margin-bottom: 10px;
}
#siteName{
font-size: 14px;
margin-top: 24px !important;
}
#profile li{
font-size: 6px !important;
}
#profile ul{
padding-left: 6px;
}
#activeOrders{
font-size: 8px !important;
}
footer{
font-size: 8px !important;
}
.socialMedia img{
width: 20px;
height: 20px;
}
#Items {
columns: 1;
}
#textIphone{
font-size: 10px;
}
#specialText{
font-size: 12px;
}
#saleText{
font-size: 12px;
}
#salePrice{
font-size: 12px;
padding-top: 10px;
}
}
@media(max-width: 700px){
.firstPart img{
width:80px !important;
height: auto;
}
.firstPart figcaption{
font-size: 8px;
}
#textIphone{
font-size: 12px;
}
#specialText{
font-size: 14px;
}
#saleText{
font-size: 16px;
}
#salePrice{
font-size: 14px;
}
}
@media(max-width: 600px){
.firstPart img{
width:60px !important;
height: auto;
}
.firstPart figcaption{
font-size: 6px;
}
}
@media(max-width: 800px){
#profile li{
font-size: 12px;
}
#activeOrders{
font-size: 12px;
}
#avatar{
width: 110px;
}
#profile ul{
padding-left: 6px;
}
.socialMedia img{
width: 35px;
height: 35px;
}
.firstPart img{
width:90px;
height: auto;
}
.firstPart figcaption{
font-size: 10px;
}
footer{
font-size: 12px;
}
.navbar-toggler{
margin-top: 10px !important;
}
#Items {
columns: 1;
}
}
@media(max-width: 900px){
.firstPart img{
width:100px;
height: auto;
}
.firstPart figcaption{
font-size: 12px;
}
}

View File

@ -0,0 +1,84 @@
import CountProduct from '../../models/countProduct';
import Product from '../../models/product';
import CountProductTable from '../common/CountProductTable'
import DataService from '../../services/DataService';
import { useState, useEffect} from "react";
import '../common/style.css';
export default function CartPage(){
const url = 'countProduct/';
const getUrl = 'countProduct';
const getProductUrl = 'product'
const transformer = (data) => new CountProduct(data);
const transformerProd = (data) => new Product(data);
const catalogCountProductHeaders = [
{name: 'name', label: 'Название' },
{name: 'amount', label: 'Количество' },
{name: 'price', label: 'Цена' },
];
const [data, setData] = useState(new CountProduct());
const [productOptions, setProductOptions] = useState([]);
function handleOnAdd() {
setData(new CountProduct());
}
function handleOnEdit(data) {
setData(new CountProduct(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
useEffect(() => {
loadOptions();
}, []);
async function loadOptions(){
loadProdOptions(await DataService.readAll(getProductUrl, transformerProd));
}
function loadProdOptions(dataProduct){
const products = [];
dataProduct.forEach((value) => {
products.push({
key: value.name,
value: value.id,
})
})
console.log(products);
setProductOptions(products);
}
return(
<article className="h-100 mt-0 mb-0 d-flex flex-column justify-content-between">
<CountProductTable headers={catalogCountProductHeaders}
getAllUrl={url}
url={url}
getUrl={getUrl}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<label className="form-label" forhtml="productId"></label>
<select className="form-select" id="productId" value={data.productCategoryId} onChange={handleFormChange} required>
{
productOptions.map((option) => {
return(
<option key={option.value} value={option.value}>
{option.key}
</option>
)
}
)
}
</select>
</CountProductTable>
</article>
)
}

View File

@ -0,0 +1,41 @@
import Cart from "../../models/cart"
import CartTable from '../common/CartTable'
import { useState, useEffect} from "react";
import '../common/style.css';
export default function CartsPage(){
const url = 'cart';
const getUrl = 'cart/';
const transformer = (data) => new Cart(data);
const catalogCartHeaders = [
{name: 'customer', label: 'Покупатель' },
];
const [data, setData] = useState(new Cart());
function handleOnAdd() {
setData(new Cart());
}
function handleOnEdit(data) {
setData(new Cart(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return(
<article className="h-100 mt-0 mb-0 d-flex flex-column justify-content-between">
<CartTable headers={catalogCartHeaders}
getAllUrl={url}
url={url}
getUrl={getUrl}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
</CartTable>
</article>
)
}

View File

@ -0,0 +1,53 @@
import Customer from "../../models/customer"
import CustomerTable from '../common/CustomerTable'
import { useState, useEffect} from "react";
export default function CustomerPage(){
const url = 'customer';
const getUrl = 'customer/';
const transformer = (data) => new Customer(data);
const catalogCustomerHeaders = [
{ name: 'lastName', label: 'Фамилия' },
{name: 'firstName', label: 'Имя'},
{name: 'customerAddress', label: 'Адрес'}
];
const [data, setData] = useState(new Customer());
function handleOnAdd() {
setData(new Customer());
}
function handleOnEdit(data) {
setData(new Customer(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return(
<article className="h-100 mt-0 mb-0 d-flex flex-column justify-content-between">
<CustomerTable headers={catalogCustomerHeaders}
getAllUrl={url}
url={url}
getUrl={getUrl}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="col-md-4">
<label className="form-label" forhtml="lastName">Фамилия</label>
<input className="form-control" type="text" id="lastName" value={data.lastName} onChange={handleFormChange} required="required"/>
</div>
<div className="col-md-4">
<label className="form-label" forhtml="firstName">Имя</label>
<input className="form-control" type="text" value={data.firstName} onChange={handleFormChange} id="firstName" required="required"/>
</div>
<div className="col-md-4">
<label className="form-label" forhtml="customerAddress">Адрес</label>
<input className="form-control" type="text" id="customerAddress" value={data.customerAddress} onChange={handleFormChange} required="required"/>
</div>
</CustomerTable>
</article>
)
}

View File

@ -0,0 +1,43 @@
import ProductCategory from "../../models/productCategory"
import ProductCategoryTable from '../common/productCategoryTable'
import { useState, useEffect} from "react";
export default function ProductCategoryPage(){
const url = 'productCategory';
const getUrl = 'productCategory/';
const transformer = (data) => new ProductCategory(data);
const catalogCustomerHeaders = [
{ name: 'name', label: 'Название категории' },
];
const [data, setData] = useState(new ProductCategory());
function handleOnAdd() {
setData(new ProductCategory());
}
function handleOnEdit(data) {
setData(new ProductCategory(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return(
<article className="h-100 mt-0 mb-0 d-flex flex-column justify-content-between">
<ProductCategoryTable headers={catalogCustomerHeaders}
getAllUrl={url}
url={url}
getUrl={getUrl}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="col-md-4">
<label className="form-label" forhtml="name">Название категории</label>
<input className="form-control" type="text" id="name" value={data.name} onChange={handleFormChange} required="required"/>
</div>
</ProductCategoryTable>
</article>
)
}

View File

@ -0,0 +1,91 @@
import Product from "../../models/product"
import ProductCategory from "../../models/productCategory"
import DataService from '../../services/DataService';
import ProductTable from '../common/productTable'
import { useState, useEffect} from "react";
export default function ProductPage(){
const url = 'product';
const getUrl = 'product/';
const getCatUrl = 'productCategory';
const transformer = (data) => new Product(data);
const transformerCat = (data) => new ProductCategory(data);
const catalogProductHeaders = [
{ name: 'name', label: 'Название товара' },
{ name: 'price', label: 'Цена' },
{ name: 'categoryName', label: 'Категория товара' }
];
const [data, setData] = useState(new Product());
const [productCategoryOptions, setProductCategoryOptions] = useState([]);
function handleOnAdd() {
setData(new Product());
}
function handleOnEdit(data) {
setData(new Product(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
//подтягиваем список категорий в селект
useEffect(() => {
loadOptions();
}, []);
async function loadOptions(){
loadCatOptions(await DataService.readAll(getCatUrl, transformerCat));
}
function loadCatOptions(dataProductCategory){
const productCategories = [];
dataProductCategory.forEach((value) => {
productCategories.push({
key: value.name,
value: value.id,
})
})
console.log(productCategories);
setProductCategoryOptions(productCategories);
}
return(
<article className="h-100 mt-0 mb-0 d-flex flex-column justify-content-between">
<ProductTable headers={catalogProductHeaders}
getAllUrl={url}
url={url}
getUrl={getUrl}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="col-md-4">
<label className="form-label" forhtml="name">Название</label>
<input className="form-control" type="text" id="name" value={data.name} onChange={handleFormChange} required="required"/>
</div>
<div className="col-md-4">
<label className="form-label" forhtml="price">Цена</label>
<input className="form-control" type="text" id="price" value={data.price} onChange={handleFormChange} required="required"/>
</div>
<label className="form-label" forhtml="productCategoryId"></label>
<select className="form-select" id="productCategoryId" value={data.productCategoryId} onChange={handleFormChange} required>
{
productCategoryOptions.map((option) => {
return(
<option key={option.value} value={option.value}>
{option.key}
</option>
)
}
)
}
</select>
</ProductTable>
</article>
)
}

6
front/src/models/cart.js Normal file
View File

@ -0,0 +1,6 @@
export default class Cart {
constructor(data) {
this.id = data?.id;
this.customer = data?.customer || '';
}
}

View File

@ -0,0 +1,8 @@
export default class CountProduct {
constructor(data) {
this.id = data?.id;
this.name = data?.name || '';
this.amount = data?.amount || '';
this.price = data?.price || '';
}
}

View File

@ -0,0 +1,8 @@
export default class Customer {
constructor(data) {
this.id = data?.id;
this.lastName = data?.lastName || '';
this.firstName = data?.firstName || '';
this.customerAddress = data?.customerAddress || '';
}
}

View File

@ -0,0 +1,9 @@
export default class Product {
constructor(data) {
this.id = data?.id;
this.name = data?.name || '';
this.price = data?.price || '';
this.productCategoryId = data?.productCategoryId || '';
this.categoryName = data?.categoryName || '';
}
}

View File

@ -0,0 +1,6 @@
export default class Product {
constructor(data) {
this.id = data?.id;
this.name = data?.name || '';
}
}

View File

@ -0,0 +1,45 @@
import axios from 'axios';
function toJSON(data) {
const jsonObj = {};
const fields = Object.getOwnPropertyNames(data);
for (const field of fields) {
if (data[field] === undefined) {
continue;
}
jsonObj[field] = data[field];
}
return jsonObj;
}
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080/';
static async readAll(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
return response.data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
console.log("Create " + this.dataUrlPrefix + url + data);
const response = await axios.post(this.dataUrlPrefix + url + data);
return true;
}
static async update(url, data) {
console.log("UPD")
const response = await axios.put(this.dataUrlPrefix + url + data);
console.log("Done upd")
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

473
front/src/style.css Normal file
View File

@ -0,0 +1,473 @@
.mainHtml{
background-color: #ffb84b !important;
}
.hide{
display: none;
}
.active{
display: block;
}
.active img {
height: auto;
}
header {
height: fit-content;
background-image: linear-gradient(to right, #ff8400 , #ffc156);
align-items: center;
}
img.center {
display: block;
margin: 0 auto;
}
div.colorBG{
background-color: #ffb84b;
}
.firstPart div {
display: flex;
}
.firstPart figcaption {
color: white;
text-align: center;
}
#salePrice{
font-family: 'Agency FB Bold', arial;
margin-top: -10px;
}
.adIphone {
color: white;
font-family: 'Antipasto Pro', sans-serif;
font-size: 28px;
}
#saleText{
color: red;
font-size: 35px;
}
#specialText{
font-size: 40px;
color: red;
}
.adIphone figure img{
text-align: justify-all;
}
.menu {
flex-grow: 1;
}
.menu a,
.menu .active {
font-family: 'Antipasto Pro', sans-serif;
display: block;
padding: 8px 10px;
color: white;
font-size: 22px;
text-decoration: none;
}
.menu .active {
color: #fff;
background-color: #ff3d00;
border-radius: 8px;
}
#siteName{
color: white;
font-family: 'Agency FB Bold', arial;
font-size: 36px;
}
#mainPage{
font-size: 27px;
}
#mainPage a{
font-family: 'Antipasto Pro', sans-serif;
color: white;
text-decoration: none;
}
div.colorBG{
background-color: #ffb84b;
}
.firstPart{
background-image: url(images/banner.png);
background-repeat: no-repeat;
background-size: 107%;
}
.firstPart figure {
margin-inline-start: 10px;
margin-block-start: 10px;
}
footer {
background-image: linear-gradient(to right, #ff8400 , #ffc156);
}
.socialMedia{
margin-right: 5px;
margin-left: auto;
}
.socialMedia figcaption{
font-family: 'Antipasto Pro', sans-serif;
}
.copyright {
margin-right: 10px;
flex-basis: 98%;
text-align: right;
color: white;
font-family: 'Agency FB', arial;
}
#weInSocial {
color: white;
}
.aboutUsFooter{
font-family: 'Antipasto Pro', sans-serif;
}
.aboutUsFooter a{
text-decoration: none;
color: white;
}
.aboutUsFooter li{
list-style-type: none;
margin: 7px 0;
}
.aboutUsText figcaption {
color: #ff8400;
font-family: 'Antipasto Pro', sans-serif;
font-size: 46px;
}
#loremIpsumText{
color: black;
font-size: 20px;
margin-right: 15%;
margin-left: 15%;
}
#leftColumn{
flex-direction: column;
}
#middleColumn{
flex-direction: column;
}
#rightColumn{
text-align: center;
display: flex;
flex-direction: column;
}
.item{
text-align: center;
font-family: Segoe UI;
font-weight: bold;
font-size: 18px;
}
.item figcaption{
color: black;
}
#Items {
columns: 3;
column-gap: 1em;
}
* {box-sizing: border-box;}
form {
position: relative;
width: 400px;
margin-top: 20px;
margin-left: auto;
margin-right: auto;
background-image: linear-gradient(to right, #ff8400 , #ffc156);
}
input, button {
border: none;
outline: none;
background: transparent;
}
input {
height: 42px;
}
.searchbutton{
height: 42px;
width: 42px;
position: absolute;
top: 0;
right: 0;
cursor: pointer;
}
button .searchbutton:before {
font-family: FontAwesome;
font-size: 16px;
color: #F9F0DA;
}
.orders{
width: 1000px;
display: block;
float: none;
height: 350px;
background: #ffc156;
border: 1px solid #C1C1C1;
overflow: auto;
}
#activeOrders {
font-family: 'Antipasto Pro', sans-serif;
text-align: center;
font-size: 20px;
margin-top: 10px;
color: #c06300;
}
#listOfInf{
background-color: #ffc156;
height: 150px;
width: 900px;
vertical-align: center;
margin-top: 15px;
display: flex;
}
#listOfInf li{
color: #c06300;
list-style-type: none;
font-family: 'Antipasto Pro', sans-serif;
margin: 9px 0;
}
.orderItem{
display: flex;
}
.nameItem{
margin-top: 20px;
color: white;
font-family: 'Antipasto Pro', sans-serif;
margin-left: 0px;
}
.priceItem {
color: white;
font-family: 'Antipasto Pro', sans-serif;
margin-bottom: 30px;
margin-top: auto;
margin-right: 100px;
margin-left: auto;
}
.deleteItem button{
color: white;
width: auto;
height: 25px;
font-family: 'Antipasto Pro', sans-serif;
font-size: 16px;
position: relative;
left: 10%;
top: 73%;
transform: translate(-70%, 0);
background: #ff8400;
}
.ordersCart{
margin-left: auto;
margin-right: auto;
margin-bottom: 30px;
margin-top: 30px;
width: 1000px;
display: block;
float: none;
height: auto;
background: #ffc156;
border: 1px solid #C1C1C1;
overflow: auto;
}
.orderItems button{
color: white;
width: auto;
height: 40px;
font-family: 'Antipasto Pro', sans-serif;
font-size: 36px;
position: relative;
left: 85%;
top: 73%;
transform: translate(-70%, 0);
background: #ff8400;
margin-bottom: 50px;
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
color: white;
font-family: 'Antipasto Pro', sans-serif;
}
@media (max-width: 550px){
.nameItem{
font-size: 12px;
}
.deleteItem{
font-size: 12px;
}
.priceItem{
font-size: 12px;
}
.orderItem img{
height: 120px;
width: auto;
}
.orderItems button {
font-size: 16px;
}
}
@media(max-width: 500px){
header{
flex-direction: column;
}
#mainPage{
margin-top: 0px;
}
#leftPart a{
font-size: 12px;
text-align: left;
margin-top: 0;
padding-top: 0;
}
.logo img{
margin-top: 10px;
width: 35px;
height: 35px;
margin-top: 10px;
margin-bottom: 10px;
}
#siteName{
font-size: 14px;
margin-top: 24px !important;
}
#profile li{
font-size: 6px !important;
}
#profile ul{
padding-left: 6px;
}
#activeOrders{
font-size: 8px !important;
}
footer{
font-size: 8px !important;
}
.socialMedia img{
width: 20px;
height: 20px;
}
#Items {
columns: 1;
}
#textIphone{
font-size: 10px;
}
#specialText{
font-size: 12px;
}
#saleText{
font-size: 12px;
}
#salePrice{
font-size: 12px;
padding-top: 10px;
}
}
@media(max-width: 700px){
.firstPart img{
width:80px !important;
height: auto;
}
.firstPart figcaption{
font-size: 8px;
}
#textIphone{
font-size: 12px;
}
#specialText{
font-size: 14px;
}
#saleText{
font-size: 16px;
}
#salePrice{
font-size: 14px;
}
}
@media(max-width: 600px){
.firstPart img{
width:60px !important;
height: auto;
}
.firstPart figcaption{
font-size: 6px;
}
}
@media(max-width: 800px){
#profile li{
font-size: 12px;
}
#activeOrders{
font-size: 12px;
}
#avatar{
width: 110px;
}
#profile ul{
padding-left: 6px;
}
.socialMedia img{
width: 35px;
height: 35px;
}
.firstPart img{
width:90px;
height: auto;
}
.firstPart figcaption{
font-size: 10px;
}
footer{
font-size: 12px;
}
.navbar-toggler{
margin-top: 10px !important;
}
#Items {
columns: 1;
}
}
@media(max-width: 900px){
.firstPart img{
width:100px;
height: auto;
}
.firstPart figcaption{
font-size: 12px;
}
}

7
front/vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})