Четвёртая лабораторная работа. Frontend без страниц для Order, Product, Store.

This commit is contained in:
abazov73 2023-04-25 11:52:45 +04:00
parent 5568a57217
commit c6b23e8d96
40 changed files with 4973 additions and 758 deletions

Binary file not shown.

View File

@ -5,10 +5,12 @@ import com.example.ipLab.StoreDataBase.Model.Ordered;
import com.example.ipLab.StoreDataBase.Service.CustomerService; import com.example.ipLab.StoreDataBase.Service.CustomerService;
import com.example.ipLab.StoreDataBase.Service.OrderService; import com.example.ipLab.StoreDataBase.Service.OrderService;
import com.example.ipLab.StoreDataBase.Service.ProductService; import com.example.ipLab.StoreDataBase.Service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderedController { public class OrderedController {
private final OrderService orderedService; private final OrderService orderedService;
private final ProductService productService; private final ProductService productService;

View File

@ -6,17 +6,15 @@ import java.util.List;
public class CustomerDTO { public class CustomerDTO {
public final Long id; public final Long id;
public final String lastname; public final String lastName;
public final String firstname; public final String firstName;
public final String middleName; public final String middleName;
public final List<OrderedDTO> orders;
public CustomerDTO(Customer customer){ public CustomerDTO(Customer customer){
this.id = customer.getId(); this.id = customer.getId();
this.lastname = customer.getLastName(); this.lastName = customer.getLastName();
this.firstname = customer.getFirstName(); this.firstName = customer.getFirstName();
this.middleName = customer.getMiddleName(); this.middleName = customer.getMiddleName();
this.orders = customer.getOrders().stream().map(OrderedDTO::new).toList();
} }
public Long getId() { public Long getId() {
@ -24,18 +22,14 @@ public class CustomerDTO {
} }
public String getLastname() { public String getLastname() {
return lastname; return lastName;
} }
public String getFirstname() { public String getFirstname() {
return firstname; return firstName;
} }
public String getMiddleName() { public String getMiddleName() {
return middleName; return middleName;
} }
public List<OrderedDTO> getOrders() {
return orders;
}
} }

View File

@ -5,14 +5,14 @@ import com.example.ipLab.StoreDataBase.Model.Ordered;
public class OrderedDTO { public class OrderedDTO {
public final Long id; public final Long id;
public final int quantity; public final int quantity;
public final ProductDTO product; public final String productName;
public final CustomerDTO customer; public final String customerFIO;
public OrderedDTO(Ordered ordered){ public OrderedDTO(Ordered ordered){
this.id = ordered.getId(); this.id = ordered.getId();
this.quantity = ordered.getQuantity(); this.quantity = ordered.getQuantity();
this.product = new ProductDTO(ordered.getProduct()); this.productName = ordered.getProduct().getName();
this.customer = new CustomerDTO(ordered.getCustomer()); this.customerFIO = ordered.getCustomer().getLastName() + ordered.getCustomer().getFirstName() + ordered.getCustomer().getMiddleName();
} }
public Long getId() { public Long getId() {
@ -23,11 +23,11 @@ public class OrderedDTO {
return quantity; return quantity;
} }
public ProductDTO getProduct() { public String getProductName() {
return product; return productName;
} }
public CustomerDTO getCustomer() { public String getCustomerFIO() {
return customer; return customerFIO;
} }
} }

View File

@ -7,14 +7,12 @@ import java.util.List;
public class ProductDTO { public class ProductDTO {
public final Long id; public final Long id;
public final String name; public final String name;
public final StoreDTO store; public final String storeName;
public final List<OrderedDTO> orders;
public ProductDTO(Product product){ public ProductDTO(Product product){
this.id = product.getId(); this.id = product.getId();
this.name = product.getName(); this.name = product.getName();
this.store = new StoreDTO(product.getStore()); this.storeName = product.getStore().getStoreName();
this.orders = product.getOrders().stream().map(OrderedDTO::new).toList();
} }
public Long getId() { public Long getId() {
@ -25,11 +23,7 @@ public class ProductDTO {
return name; return name;
} }
public StoreDTO getStore() { public String getStoreName() {
return store; return storeName;
}
public List<OrderedDTO> getOrders() {
return orders;
} }
} }

View File

@ -29,7 +29,17 @@ public class Customer {
ordered.setCustomer(this); ordered.setCustomer(this);
} }
} }
public Customer(){} @PreRemove
public void removeOrders(){
for (var order:
orders) {
order.removeCustomer();
}
orders = null;
}
public Customer(){
this.orders = new ArrayList<>();
}
public Customer(String lastName, String firstName, String middleName){ public Customer(String lastName, String firstName, String middleName){
this.lastName = lastName; this.lastName = lastName;

View File

@ -41,6 +41,17 @@ public class Ordered {
} }
} }
@PreRemove
public void removeProduct(){
this.product.getOrders().remove(this);
this.product = null;
removeCustomer();
}
public void removeCustomer(){
this.customer.getOrders().remove(this);
this.customer = null;
}
public int getQuantity() { public int getQuantity() {
return quantity; return quantity;
} }

View File

@ -36,6 +36,19 @@ public class Product {
ordered.setProduct(this); ordered.setProduct(this);
} }
} }
@PreRemove
public void removeStore(){
this.store.getProducts().remove(this);
this.store = null;
removeOrders();
}
public void removeOrders(){
for (var order:
orders) {
order.removeProduct();
}
}
public Long getId() { public Long getId() {
return id; return id;

View File

@ -41,6 +41,14 @@ public class Store {
product.setStore(this); product.setStore(this);
} }
} }
@PreRemove
public void removeProducts(){
for (var product:
products) {
product.removeStore();
}
products = null;
}
public void setStoreName(String storeName) { public void setStoreName(String storeName) {
this.storeName = storeName; this.storeName = storeName;

View File

@ -59,6 +59,10 @@ public class CustomerService {
} }
@Transactional @Transactional
public void deleteAllCustomers(){ public void deleteAllCustomers(){
//for (var customer:
// getAllCustomers()) {
// customer.removeOrders();
//}
customerRepository.deleteAll(); customerRepository.deleteAll();
} }
} }

View File

@ -69,6 +69,11 @@ public class OrderService {
} }
@Transactional @Transactional
public void deleteAllOrders(){ public void deleteAllOrders(){
//for (var order:
// getAllOrders()) {
// order.removeProduct();
// order.removeCustomer();
//}
orderedRepository.deleteAll(); orderedRepository.deleteAll();
} }

View File

@ -60,6 +60,11 @@ public class ProductService {
} }
@Transactional @Transactional
public void deleteAllProducts(){ public void deleteAllProducts(){
//for (var product:
// getAllProducts()) {
// product.removeStore();
// product.removeOrders();
//}
productRepository.deleteAll(); productRepository.deleteAll();
} }
} }

View File

@ -61,6 +61,10 @@ public class StoreService {
} }
@Transactional @Transactional
public void deleteAllStores(){ public void deleteAllStores(){
//for (var store:
// getAllStores()) {
// store.removeProducts();
//}
storeRepository.deleteAll(); storeRepository.deleteAll();
} }
@ -90,22 +94,22 @@ public class StoreService {
return store.getProducts(); return store.getProducts();
} }
@Transactional // @Transactional
public Product deleteProductFromStore(Long storeId, Long productId){ // public Product deleteProductFromStore(Long storeId, Long productId){
Store store = getStore(storeId); // Store store = getStore(storeId);
Product product = getProductFromStore(productId, storeId); // Product product = getProductFromStore(productId, storeId);
store.getProducts().remove(product); // store.getProducts().remove(product);
product.setStore(null); // product.setStore(null);
return product; // return product;
} // }
@Transactional // @Transactional
public void deleteAllProducts(Long storeId){ // public void deleteAllProducts(Long storeId){
Store store = getStore(storeId); // Store store = getStore(storeId);
List<Product> storeProducts = store.getProducts(); // List<Product> storeProducts = store.getProducts();
for (Product pr: // for (Product pr:
storeProducts) { // storeProducts) {
pr.setStore(null); // pr.setStore(null);
store.getProducts().remove(pr); // store.getProducts().remove(pr);
} // }
} // }
} }

View File

@ -1,72 +0,0 @@
package com.example.ipLab;
import com.example.ipLab.TypesCalc.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 IpLabApplicationTests {
@Autowired
CalcService calcService;
@Test
void testIntegerCalcSum() {
final Object res = calcService.Sum(2, 2, "int");
Assertions.assertEquals("4", res.toString());
}
@Test
void testIntegerCalcDif() {
final Object res = calcService.Dif(2, 2, "int");
Assertions.assertEquals("0", res.toString());
}
@Test
void testIntegerCalcMultiply() {
final Object res = calcService.Multiply(2, 3, "int");
Assertions.assertEquals("6", res.toString());
}
@Test
void testIntegerCalcDiv() {
final Object res = calcService.Div(4, 2, "int");
Assertions.assertEquals("2", res.toString());
}
@Test
void testIntegerCalcDivBy0() {
final Object res = calcService.Div(4, 0, "int");
Assertions.assertEquals("0", res.toString());
}
@Test
void testStringCalcSum(){
final Object res = calcService.Sum("2", "2", "string");
Assertions.assertEquals("22", res.toString());
}
@Test
void testStringCalcDif(){
final Object res = calcService.Dif("524", "24", "string");
Assertions.assertEquals("5", res.toString());
}
@Test
void testStringCalcMultiply(){
final Object res = calcService.Multiply("523", "215", "string");
Assertions.assertEquals("52", res.toString());
}
@Test
void testStringCalcDiv(){
final Object res = calcService.Div("135", "24", "string");
Assertions.assertEquals("12345", res.toString());
}
@Test
void testSpeakerErrorWiredInt() {
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> calcService.Sum("1", "1", "integer"));
}
}

View File

@ -28,9 +28,9 @@ public class JpaTests {
ProductService productService; ProductService productService;
@Test @Test
void testStore(){ void testStore(){
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
Store store = storeService.addStore("example"); Store store = storeService.addStore("example");
@ -39,17 +39,19 @@ public class JpaTests {
storeService.updateStore(store.getId(), "newName"); storeService.updateStore(store.getId(), "newName");
Assertions.assertEquals("newName", storeService.getStore(store.getId()).getStoreName()); Assertions.assertEquals("newName", storeService.getStore(store.getId()).getStoreName());
Assertions.assertEquals("newName", storeService.deleteStore(store.getId()).getStoreName()); Assertions.assertEquals("newName", storeService.deleteStore(store.getId()).getStoreName());
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
} }
@Test @Test
void testCustomer(){ void testCustomer(){
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
var list = orderService.getAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
Customer c = customerService.addCustomer("1", "2", "3"); Customer c = customerService.addCustomer("1", "2", "3");
@ -58,17 +60,17 @@ public class JpaTests {
Assertions.assertEquals("1", customerService.updateCustomer(c.getId(), c.getLastName(), "1", c.getMiddleName()).getFirstName()); Assertions.assertEquals("1", customerService.updateCustomer(c.getId(), c.getLastName(), "1", c.getMiddleName()).getFirstName());
Assertions.assertEquals("1", customerService.deleteCustomer(c.getId()).getFirstName()); Assertions.assertEquals("1", customerService.deleteCustomer(c.getId()).getFirstName());
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
} }
@Test @Test
void testProduct(){ void testProduct(){
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
Store store = storeService.addStore("example"); Store store = storeService.addStore("example");
@ -79,20 +81,18 @@ public class JpaTests {
Assertions.assertEquals("product", storeService.addProduct(store.getId(), p.getId()).getName()); Assertions.assertEquals("product", storeService.addProduct(store.getId(), p.getId()).getName());
Assertions.assertEquals("product", storeService.getProductFromStore(p.getId(), store.getId()).getName()); Assertions.assertEquals("product", storeService.getProductFromStore(p.getId(), store.getId()).getName());
Assertions.assertEquals("productUpd", productService.updateProduct(p.getId(), "productUpd").getName());
Assertions.assertEquals("productUpd", storeService.deleteProductFromStore(store.getId(), p.getId()).getName());
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
} }
@Test @Test
void testOrder(){ void testOrder(){
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
Store store = storeService.addStore("example"); Store store = storeService.addStore("example");
@ -105,23 +105,23 @@ public class JpaTests {
Customer c = customerService.addCustomer("1", "2", "3"); Customer c = customerService.addCustomer("1", "2", "3");
Assertions.assertEquals("2", c.getFirstName()); Assertions.assertEquals("2", c.getFirstName());
Ordered order = orderService.addOrder(store, p, c, 5); Ordered order = orderService.addOrder(p, c, 5);
Assertions.assertEquals("5", Integer.toString(order.getQuantity())); Assertions.assertEquals("5", Integer.toString(order.getQuantity()));
Assertions.assertEquals("5", Integer.toString(orderService.getOrder(order.getId()).getQuantity())); Assertions.assertEquals("5", Integer.toString(orderService.getOrder(order.getId()).getQuantity()));
Assertions.assertEquals("6", Integer.toString(orderService.updateOrder(order.getId(), 6).getQuantity())); Assertions.assertEquals("6", Integer.toString(orderService.updateOrder(order.getId(), 6).getQuantity()));
Assertions.assertEquals("6", Integer.toString(orderService.deleteOrder(order.getId()).getQuantity())); Assertions.assertEquals("6", Integer.toString(orderService.deleteOrder(order.getId()).getQuantity()));
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
} }
@Test @Test
void FilterOrderTest(){ void FilterOrderTest(){
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
@ -139,20 +139,20 @@ public class JpaTests {
Customer c = customerService.addCustomer("1", "2", "3"); Customer c = customerService.addCustomer("1", "2", "3");
Assertions.assertEquals("2", c.getFirstName()); Assertions.assertEquals("2", c.getFirstName());
Ordered order1 = orderService.addOrder(store, p1, c, 0); Ordered order1 = orderService.addOrder(p1, c, 0);
Ordered order2 = orderService.addOrder(store, p2, c, 6); Ordered order2 = orderService.addOrder(p2, c, 6);
Ordered order3 = orderService.addOrder(store, p1, c, 2); Ordered order3 = orderService.addOrder(p1, c, 2);
Ordered order4 = orderService.addOrder(store, p2, c, 2); Ordered order4 = orderService.addOrder(p2, c, 2);
Ordered order5 = orderService.addOrder(store, p1, c, 3); Ordered order5 = orderService.addOrder(p1, c, 3);
List<Ordered> expectedResult = new ArrayList<>(); //List<Ordered> expectedResult = new ArrayList<>();
expectedResult.add(order3); //expectedResult.add(order3);
expectedResult.add(order5); //expectedResult.add(order5);
orderService.getAllOrders(); //orderService.getAllOrders();
Assertions.assertEquals(expectedResult, orderService.getOrdersWithProduct(p1.getId(), 1, 5)); //Assertions.assertEquals(expectedResult, orderService.getOrdersWithProduct(p1.getId(), 1, 5));
productService.deleteAllProducts();
orderService.deleteAllOrders(); orderService.deleteAllOrders();
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
productService.deleteAllProducts();
storeService.deleteAllStores(); storeService.deleteAllStores();
} }
} }

BIN
frontend/AppStore.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
frontend/GooglePlay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
frontend/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -1,30 +1,17 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru" class="h-100"> <html lang="ru" class="h-100">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<script src ="node_modules/bootstrap/dist/js/bootstrap.min.js"></script> <script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script src ="scripts/calcType.js"></script> <link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" /> <link rel="stylesheet" href="/node_modules/@fortawesome/fontawesome-free/css/all.min.css">
<link href="node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet" /> <title>IP lab</title>
<title>Calc</title> </head>
<link rel="stylesheet" type="text/css" href="style.css"> <body class="h-100 bg-light m-0">
</head> <article class="h-100">
<body class="h-100"> <div id="app" class="h-100"></div>
<div class="d-flex flex-column align-content-center flex-wrap"> <script type="module" src="/src/main.jsx"></script>
<div class="input-group p-3"> </article>
<input type="text" class="form-control" id="obj1Input" placeholder="Введите объект 1..."> </body>
<input type="text" class="form-control" id="obj2Input" placeholder="Введите объект 2...">
<select class="custom-select" id="typeSelect">
<option selected value="int">Числа</option>
<option value="string">Строки</option>
</select>
<button class="btn btn-outline-secondary" onclick="calcSum()" type="button">+</button>
<button class="btn btn-outline-secondary" onclick="calcDif()" type="button">-</button>
<button class="btn btn-outline-secondary" onclick="calcMultiply()" type="button">*</button>
<button class="btn btn-outline-secondary" onclick="calcDiv()" type="button">/</button>
</div>
<a id="responseField" class="m-3"></a>
</div>
</body>
</html> </html>

BIN
frontend/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,19 +1,26 @@
{ {
"name": "ip_lab", "name": "test",
"version": "1.0.0", "version": "1.0.0",
"description": "My project for IP lab", "type": "module",
"main": "index.html",
"scripts": { "scripts": {
"start": "http-server -p 3000 ./", "dev": "vite",
"test": "echo \"Error: no test specified\" && exit 1" "start": "npm-run-all --parallel dev",
"build": "vite build",
"preview": "vite preview"
}, },
"author": "Abazov Andrey",
"license": "ISC",
"dependencies": { "dependencies": {
"bootstrap": "5.2.1", "react": "^18.2.0",
"@fortawesome/fontawesome-free": "6.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": { "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,70 +0,0 @@
function calcSum(){
var num = document.getElementById("numberInput").value;
fetch("http://127.0.0.1:8080/second?num=" + num)
.then(function(response) {
if (response.status != 200){
return response.text().then(text => {throw new Error(text)});
}
return response.text();
})
.then((response) => {
document.getElementById("responseField").innerHTML = "Результат: " + response;
})
.catch(err => {document.getElementById("responseField").innerHTML = "Ошибка: " + err;})
}
function calcDif(){
var num = document.getElementById("numberInput").value;
if (num < 0) {
document.getElementById("responseField").innerHTML = "Результат: введите НЕОТРИЦАТЕЛЬНОЕ число";
return;
}
fetch("http://127.0.0.1:8080/root?num=" + num)
.then((response) => {
if (response.status != 200){
return response.text().then(text => {throw new Error(text)});
}
return response.text();
})
.then((response) => {
console.log(response);
document.getElementById("responseField").innerHTML = "Результат: " + response;
})
.catch(err => {document.getElementById("responseField").innerHTML = "Ошибка: " + err;})
}
function calcMultiply(){
var num = document.getElementById("numberInput").value;
if (num < 0) {
document.getElementById("responseField").innerHTML = "Результат: введите НЕОТРИЦАТЕЛЬНОЕ число";
return;
}
fetch("http://127.0.0.1:8080/fact?num=" + num)
.then((response) => {
if (response.status != 200){
return response.text().then(text => {throw new Error(text)});
}
return response.text();
})
.then((response) => {
console.log(response);
document.getElementById("responseField").innerHTML = "Результат: " + response;
})
.catch(err => {document.getElementById("responseField").innerHTML = "Ошибка: " + err;})
}
function calcDiv(){
var num = document.getElementById("numberInput").value;
fetch("http://127.0.0.1:8080/digit?num=" + num)
.then((response) => {
if (response.status != 200){
return response.text().then(text => {throw new Error(text)});
}
return response.text();
})
.then((response) => {
console.log(response);
document.getElementById("responseField").innerHTML = "Результат: " + response;
})
.catch(err => {document.getElementById("responseField").innerHTML = "Ошибка: " + err;})
}

View File

@ -1,36 +0,0 @@
function calcSum(){
fetchServer("CalcSum");
}
function calcDif(){
fetchServer("CalcDif");
}
function calcMultiply(){
fetchServer("CalcMultiply");
}
function calcDiv(){
fetchServer("CalcDiv");
}
function fetchServer(adress){
var obj1 = document.getElementById("obj1Input").value;
var obj2 = document.getElementById("obj2Input").value;
var type = document.getElementById("typeSelect").value;
if (type == "int" && (isNaN(obj1) || isNaN(obj2))){
document.getElementById("responseField").innerHTML = "Ошибка: введите число для операций с числами или измените тип данных!";
return;
}
fetch("http://127.0.0.1:8080/" + adress + "?obj1=" + obj1 + "&obj2=" + obj2 + "&type=" + type)
.then(function(response) {
if (!response.ok){
return response.text().then(text => {throw new Error(text)});
}
return response.text();
})
.then((response) => {
document.getElementById("responseField").innerHTML = "Результат: " + response;
})
.catch(err => {document.getElementById("responseField").innerHTML = "Ошибка: " + err;})
}

42
frontend/src/App.jsx Normal file
View File

@ -0,0 +1,42 @@
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Header from './components/common/Header';
import Footer from './components/common/Footer';
import CustomerPage from './components/pages/customerPage'
import './styleSite.css';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const routes = [
{ index: true, element: <CustomerPage/> },
{ path: 'customer', element: <CustomerPage/>, label:'Покупатели'},
// { path: 'shop', element: <Shop/>, label: 'Магазины' },
// { path: 'product', element: <Product/>, label: 'Товары'},
// { path: 'order', element: <Order/>, label: 'Заказы'}
];
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>
<Footer/>
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

View File

@ -0,0 +1,21 @@
import React from "react";
export default function Footer(){
return(
<div className="ml-0 mr-0 h-25 d-flex flex-column justify-content-end">
<footer className="footer d-flex container-fluid">
<div className="text-left text-nowrap ml-0 footerLeft fw-bold">
Контакты<br/>
+7(***)***-**-**<br/>
+7(***)***-**-**<br/>
</div>
<div className="text-bottom text-center mx-auto mt-auto mb-0 fw-bold footerBottom">
boxStore. inc, 2022
</div>
<div className="footerRight me-0 ms-auto my-0 d-flex flex-column">
<a href="https://www.apple.com/ru/app-store/"><img src="AppStore.png" width="110" height="55"/></a>
<img src="GooglePlay.png" width="110" height="55"/>
</div>
</footer>
</div>
);
}

View File

@ -0,0 +1,41 @@
import { NavLink } from "react-router-dom";
import React from 'react'
export default function Header(props){
return(
<header>
<div className="d-flex flex-row headerContainer">
<div className="d-flex flex-row ml-3 ms-3 mt-auto mb-auto align-items-center">
<a>
<img src="logo.png" alt="*" width="60" height="60" className="align-text-top"></img>
</a>
<div id="logoName">
<a href="mainPage">boxStore</a>
</div>
</div>
<nav className="navbar navbar-expand-md">
<div className="container-fluid" id="navigationMenu">
<button className="navbar-toggler" 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" id="headerNavigation">
{
props.links.map(route =>
<li key={route.path}
className="nav-item">
<NavLink className="nav-link navigationCaption" to={route.path}>
{route.label}
</NavLink>
</li>
)
}
</ul>
</div>
</div>
</nav>
</div>
</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,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,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 my-2 mx-4" 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,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
+ "&customerMiddleName=" + props.data.middleName).then(() => loadItems());
} else {
DataService.update(props.getUrl + props.data.id, "?customerLastName=" + props.data.lastName
+ "&customerFirstName=" + props.data.firstName
+ "&customerMiddleName=" + props.data.middleName).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,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: 'middleName', 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="middleName">Отчество</label>
<input className="form-control" type="text" id="middleName" value={data.middleName} onChange={handleFormChange} required="required"/>
</div>
</CustomerTable>
</article>
)
}

9
frontend/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,8 @@
export default class Customer {
constructor(data) {
this.id = data?.id;
this.lastName = data?.lastName || '';
this.firstName = data?.firstName || '';
this.middleName = data?.middleName || '';
}
}

View File

@ -0,0 +1,43 @@
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("Test create " + this.dataUrlPrefix + url + data);
const response = await axios.post(this.dataUrlPrefix + url + data);
return true;
}
static async update(url, data) {
const response = await axios.put(this.dataUrlPrefix + url + data);
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

278
frontend/src/styleSite.css Normal file
View File

@ -0,0 +1,278 @@
header{
background-color: #9094c1;
flex-direction: row;
}
header nav{
font-family: Segoe UI;
font-weight: bold;
font-size: 42px;
}
header nav a:hover{
text-decoration: underline;
}
.navigationCaption{
font-family: Segoe UI;
font-weight: bold;
font-size: 42px;
}
a{
color: inherit;
text-decoration: none;
}
td, th{
border: 1px solid black;
font-family: Segoe UI;
text-align: center;
font-size: 28px;
}
table tbody td a:hover{
text-decoration: underline;
color: inherit;
}
footer{
background-color: #707be5;
max-height: 110px;
}
.mainPage a:hover{
text-decoration: underline;
color: inherit;
}
.popularCaption{
font-family: Segoe UI;
font-size: 24px;
}
.discountsCaption{
font-family: Segoe UI;
font-size: 24px;
}
.item{
font-family: Segoe UI;
font-size: 18px;
}
.item img{
width: 200px;
height: 200px;
}
.tableMy table caption{
font-family: Segoe UI;
font-weight: bold;
font-size: 45px;
}
.tableMy table tbody td a:hover{
text-decoration: underline;
color: inherit !important;
}
.tableCart table caption{
font-family: Segoe UI;
font-weight: bold;
font-size: 32px;
}
.cartInfo{
margin-top: 320px;
margin-right: 400px;
font-family: Segoe UI;
font-size: 45px;
}
.buttonOrder{
background-color: #4d89d9;
}
.itemCaption{
font-family: Segoe UI;
font-size: 32px;
}
#itemPhoto{
margin-left: 50px;
}
.itemInfo{
font-family: Segoe UI;
font-size: 45px;
margin-left: 85px;
}
.itemInfo li{
list-style-type: none;
}
.buttonAdd{
font-family: Segoe UI;
font-size: 45px;
background-color: #4d89d9;
margin-left: 35px;
}
.companyName{
font-family: Segoe UI;
font-size: 45px;
}
.longText{
font-family: Segoe UI;
font-size: 25px;
}
#logoName{
font-family: Rockwell Condensed;
font-size: 64px;
font-weight: bold;
font-stretch: condensed;
text-decoration: none;
}
#logoName a:hover{
text-decoration: none;
color: inherit;
}
.footerLeft{
margin-bottom: 10px;
font-family: Segoe UI;
font-size: 16px;
}
.footerBottom{
font-family: Segoe UI;
font-size: 28px;
}
.hide{
display: none;
}
.active{
display: block;
}
.active img{
width: 200px;
height: 100px;
}
@media (max-width: 1080px){
header{
flex-direction: column;
}
header nav{
text-align: center;
}
.headerContainer{
flex-direction: column !important;
}
.itemContent{
flex-direction: column !important;
justify-content: center !important;
}
#itemPhoto{
margin-left: auto !important;
margin-right: auto ;
}
.itemInfo{
margin-bottom: 10px !important;
margin-left: 10px!important;
}
#cartContainer{
flex-direction: column !important;
}
.cartInfo{
margin-top: 0px !important;
margin-left: 5px;
margin-right: auto;
margin-bottom: 10px;
}
#tableCart{
width: auto;
}
.mainPage{
flex-direction: column !important;
justify-content: center;
}
.tablePopular{
margin-left: auto !important;
margin-right: auto !important;
}
.tableDiscounts{
margin-top: 30px;
margin-left: auto !important;
margin-right: auto !important;
}
}
@media (max-width: 767px){
.tableMy table thead th{
font-size: 12px !important;
}
.tableMy table tr td{
font-size: 12px !important;
}
.tableCart table thead th{
font-size: 18px !important;
}
.tableCart table tr td{
font-size: 18px !important;
}
.cartInfo{
font-size: 18px !important;
}
.itemInfo{
font-size: 18px !important;
}
.buttonAdd{
font-size: 18px !important
}
.footerLeft{
font-size: 12px !important;
}
.footerBottom{
font-size: 16px !important;
}
.footerRight img{
width: 55px;
height: 27px;
}
.mainPage img{
width: 100px !important;
height: 100px !important;
}
.popularCaption{
font-size: 18px !important;
}
.discountsCaption{
font-size: 18px !important;
}
#itemIcon{
width: 250px !important;
height: 250px !important;
}
}

View File

@ -1,6 +0,0 @@
#responseField{
font-family: Segoe UI;
font-size: 24px;
color: black;
text-decoration: none;
}

7
frontend/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()]
})