frontend lab4

This commit is contained in:
Nikita Sergeev 2023-04-09 14:32:21 +04:00
parent 5d790b350c
commit edfa23dd7b
34 changed files with 7142 additions and 3126 deletions

View File

@ -23,7 +23,7 @@ jar {
into 'static'
final devHost = 'http://localhost:8080'
final prodHost = ''
filesMatching('index.html') {
filesMatching('DataService.js') {
filter { line -> line.replaceAll(devHost, prodHost) }
}
}

8469
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,31 @@
{
"name": "front",
"private": true,
"version": "1.0.0",
"source": "src/index.html",
"type": "module",
"scripts": {
"start": "parcel --port 3000",
"build": "npm run clean && parcel build",
"dev": "vite",
"fake-server": "json-server --watch data.json -p 8079",
"start": "npm-run-all --parallel dev ",
"preview": "vite preview",
"build": "npm run clean && vite build",
"clean": "rimraf dist"
},
"dependencies": {
"bootstrap": "5.2.3"
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.4",
"axios": "^1.1.3",
"bootstrap": "5.2.3",
"@fortawesome/fontawesome-free": "^6.2.1"
},
"devDependencies": {
"parcel": "2.8.3",
"@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",
"rimraf": "4.4.0"
}
}

1
front/public/favicon.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M96 0C43 0 0 43 0 96V416c0 53 43 96 96 96H384h32c17.7 0 32-14.3 32-32s-14.3-32-32-32V384c17.7 0 32-14.3 32-32V32c0-17.7-14.3-32-32-32H384 96zm0 384H352v64H96c-17.7 0-32-14.3-32-32s14.3-32 32-32zm32-240c0-8.8 7.2-16 16-16H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16zm16 48H336c8.8 0 16 7.2 16 16s-7.2 16-16 16H144c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>

After

Width:  |  Height:  |  Size: 611 B

87
front/src/App.css Normal file
View File

@ -0,0 +1,87 @@
nav {
background-color: #c8afaf;
}
main {
background-color: #8c7b7b;
min-height: 90vh;
}
footer {
background-color: #c8afaf;
color: black;
}
.size {
overflow-x: hidden;
}
.card {
background-color: #8c7b7b;
border-color: #8c7b7b;
}
.card-body {
background-color: #8c7b7b;
}
h1 {
word-wrap: break-word;
}
#banner {
margin: 0px 15px 15px 15px;
padding-top: 15px;
display: flex;
align-items: center;
flex-direction: column;
}
#banner img {
border-radius: 5px;
}
#banner img.show {
width: 100%;
opacity: 1;
transition: opacity 1s, visibility 0s;
}
#banner img.hide {
height: 0;
width: 0;
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 0s 1s;
}
@media (max-width: 767px) {
.btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.btn {
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
border-radius: 4px;
}
}
@media (min-width: 1200px) {
.btn {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333;
border-radius: 6px;
}
}
@media (max-width: 600px) {
.tem {
padding-right: 50px;
}
}

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

@ -0,0 +1,44 @@
import './App.css';
import { useRoutes, Outlet, BrowserRouter } from 'react-router-dom';
import Header from './components/common/Header';
import Footer from "./components/common/Footer";
import CatalogStudents from './components/catalogs/CatalogStudents';
import Menu from './components/catalogs/Menu';
import Basket from './components/catalogs/Basket';
import { useState } from 'react';
function Router(props) {
return useRoutes(props.rootRoute);
}
export default function App() {
const [product,setProduct] = useState([]);
const routes = [
{ index: true, element: <CatalogStudents /> },
{ path: "catalogs/menu", element: <Menu product={product} setProduct={setProduct}/>, label: "Меню" },
{ path: "catalogs/component", element: <CatalogStudents />, label: "Компоненты" },
{ path: "catalogs/basket", element: <Basket product={product} setProduct={setProduct}/>, label: "Корзина" }
];
const links = routes.filter(route => route.hasOwnProperty('label'));
const rootRoute = [
{ path: '/', element: render(links), children: routes }
];
function render(links) {
return (
<>
<Header links={links} />
<div className="container-fluid p-0">
<Outlet />
</div>
<Footer></Footer>
</>
);
}
return (
<BrowserRouter>
<Router rootRoute={ rootRoute } />
</BrowserRouter>
);
}

View File

@ -1,73 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Компоненты</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html">Заказы</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="components.html">Компоненты</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Продукты</a>
</li>
</ul>
</div>
</nav>
<form id="form" novalidate>
<div class="row mt-3">
<div class="col-sm-4">
<label for="componentId" class="form-label">ИД компонента</label>
<input type="text" class="form-control" id="componentId" required>
</div>
<div class="col-sm-4">
<label for="componentName" class="form-label">Название компонента</label>
<input type="text" class="form-control" id="componentName" required>
</div>
<div class="col-sm-4">
<label for="price" class="form-label">Цена</label>
<input type="text" class="form-control" id="price" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Добавить</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success" id="btnUpdate" >Обновить</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button id="btnRemove" class="btn btn-success">Удалить</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table id="table" class="table mt-3">
<thead>
<tr>
<th scope="col">ИД</th>
<th scope="col">Название компонента</th>
<th scope="col">Цена</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="scriptComponent.js"></script>
</html>

View File

@ -0,0 +1,15 @@
import Table from "../common/TableOrder";
export default function Basket(props) {
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<h1 className="my-5 ms-5 fs-1">
<b>Корзина</b>
</h1>
<h2 className="my-5 ms-5 fs-3"></h2>
<div className="ms-5 my-5">Список товаров</div>
<Table product={props.product} setProduct={props.setProduct}></Table>
<p> </p>
<p> </p>
</main>
);
}

View File

@ -0,0 +1,113 @@
import { useState, useEffect } from "react";
import Toolbar from "../common/Toolbar";
import Table from "../common/Table";
import Modal from "../common/Modal";
import DataService from '../../services/DataService';
export default function Catalog(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.getAllUrl, props.data).then(() => loadItems());
} else {
DataService.update(props.url + props.data.id, props.data).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.url + 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.url + 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,269 @@
import { useState, useEffect, Component } from "react";
import Toolbar from "../common/ToolbarProduct";
import Card from "../common/Card";
import ModalProduct from "../common/ModalProduct";
import DataService from "../../services/DataService";
import Table from "../common/Table";
import ToolbarProduct from "../common/Toolbar";
export default function CatalogProduct(props) {
const [items, setItems] = useState([]);
const [modalHeader, setModalHeader] = useState("");
const [modalConfirm, setModalConfirm] = useState("");
const [modalVisible, setModalVisible] = useState(false);
const [isEdit, setEdit] = useState(false);
const [componentProduct, setComponentProduct] = useState({});
useEffect(() => {
loadItems();
}, []);
function loadItems() {
DataService.readAll(props.url, props.transformer).then((data) =>{
setItems(data);
}
);
DataService.readAll(props.url, props.transformer).then((data) =>
setItems(data)
);
}
let selectedItems = [];
async function saveItem() {
if (!isEdit) {
await props.set();
DataService.create(props.url, props.data).then(() => loadItems());
} else {
await props.set();
DataService.update(props.url + "/" + props.data.id, props.data).then(() =>
loadItems()
);
}
}
function handleAdd() {
setEdit(false);
setModalHeader("Добавление элемента");
setModalConfirm("Добавить");
setModalVisible(true);
props.onAdd();
}
function handleEdit(id) {
if (selectedItems.length === 0) {
return;
}
setComponentProduct(
props.componentProduct.filter((x) => x.id == selectedItems[0])[0]
);
}
function edit(editedId) {
DataService.read(props.url+ "/" + editedId, props.transformer).then((data) => {
for(let i = 0; i < data.componentDTOList.length; i++){
props.componentProduct.push(data.componentDTOList[i]);
props.setcomponentProduct(props.componentProduct)
}
setEdit(true);
setModalHeader("Редактирование элемента");
setModalConfirm("Сохранить");
setModalVisible(true);
props.onEdit(data);
});
}
function handleRemove(id, e) {
if (selectedItems.length === 0) {
return;
}
if (confirm("Удалить выбранные элементы?")) {
const promises = [];
selectedItems.forEach((item) => {
props.deleteComponents(item);
});
selectedItems.length = 0;
}
}
function handleModalHide() {
setModalVisible(false);
props.setcomponentProduct([]);
}
function handleModalDone() {
saveItem();
}
async function handleAddComponent() {
if (
props.componentProduct.filter((x) => x.id == componentProduct.id)
.length != 0
) {
await props.updateComponents(componentProduct, isEdit);
setComponentProduct({});
let count = 0;
for (let i = 0; i < props.componentProduct.length; i++) {
count +=
props.componentProduct[i].price * props.componentProduct[i].count;
}
props.data.price = count;
if(isEdit){
await props.setprice(count);
return;
}
return;
}
props.componentProduct.push(componentProduct);
await props.setcomponentProduct(props.componentProduct);
setComponentProduct({});
let count = 0;
for (let i = 0; i < props.componentProduct.length; i++) {
count +=
props.componentProduct[i].price * props.componentProduct[i].count;
}
props.data.price = count;
}
function handleRemoveProduct(id) {
if (confirm("Удалить выбранные элементы?")) {
DataService.delete(props.url + "/" + id).then(() => {
loadItems();
});
}
}
function handleFormChangeComponent(event) {
if (event.target.id === "componentName") {
setComponentProduct({
...componentProduct,
["id"]: event.target.value,
["componentName"]: props.component
.filter((x) => x.id == event.target.value)
.map((x) => x.componentName)[0],
["price"]: props.component
.filter((x) => x.id == event.target.value)
.map((x) => x.price)[0],
});
return;
}
setComponentProduct({
...componentProduct,
[event.target.id]: Number(event.target.value),
});
return;
}
const [imageURL, setImageURL] = useState();
const fileReader = new FileReader();
fileReader.onloadend = () => {
const tempval = fileReader.result;
setImageURL(tempval);
props.setData(tempval);
};
function handleOnChange(event) {
event.preventDefault();
const file = event.target.files[0];
fileReader.readAsDataURL(file);
}
function handleTableClick(tableSelectedItems) {
selectedItems = tableSelectedItems;
}
function handleTableDblClick(tableSelectedItem) {
setComponentProduct(
props.componentProduct.filter((x) => x.id == tableSelectedItem)[0]
);
}
return (
<>
<Toolbar onAdd={handleAdd} />
<Card items={items} onEdit={edit} onRemove={handleRemoveProduct} product={props.product} setProduct={props.setProduct}/>
<ModalProduct
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={handleModalHide}
onDone={handleModalDone}
>
<div className="mb-3">
<label htmlFor="name" className="form-label">
Название продукта
</label>
<input
type="text"
id="name"
className="form-control"
required
value={props.data.name}
onChange={props.handleFormChange}
/>
</div>
<div className="mb-3">
<label htmlFor="price" className="form-label">
Цена
</label>
<input
type="text"
id="price"
className="form-control"
required
value={props.data.price}
onChange={props.handleFormChange}
/>
</div>
<div className="col-mb-3">
<label className="form-label" htmlFor="picture">
Изображение
</label>
<input
className="form-control"
id="picture"
type="file"
accept="image/jpeg, image/png, image/jpg"
value=""
onChange={handleOnChange}
/>
</div>
<div className="mb-3">
<label htmlFor="groupId" className="form-label">
Компонент
</label>
<select
id="componentName"
className="form-select"
required
value={componentProduct.id}
onChange={handleFormChangeComponent}
>
<option disabled value="">
Укажите группу
</option>
{props.component.map((group) => (
<option key={group.id} value={group.id}>
{group.componentName}
</option>
))}
</select>
<label htmlFor="count" className="form-label">
Количество
</label>
<input
type="text"
id="count"
className="form-control"
required
value={componentProduct.count ?? 0}
onChange={handleFormChangeComponent}
/>
</div>
<ToolbarProduct
onAdd={handleAddComponent}
onEdit={handleEdit}
onRemove={handleRemove}
/>
<Table
headers={props.catalogStudHeaders}
items={props.componentProduct}
allItems={props.component}
selectable={true}
onClick={handleTableClick}
onDblClick={handleTableDblClick}
/>
</ModalProduct>
</>
);
}

View File

@ -0,0 +1,52 @@
import { useState, useEffect } from 'react';
import Catalog from './Catalog';
import Component from '../../models/Component';
import DataService from '../../services/DataService';
export default function CatalogStudents(props) {
const getAllUrl = '/component';
const url = '/component/';
const transformer = (data) => new Component(data);
const catalogStudHeaders = [
{ name: 'componentName', label: 'Название компонента' },
{ name: 'price', label: 'Цена' }
];
const [data, setData] = useState(new Component());
function handleOnAdd() {
setData(new Component());
}
function handleOnEdit(data) {
setData(new Component(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value })
}
return (
<main className="flex-shrink-0" style={{ backgroundColor: "white" }}>
<Catalog
headers={catalogStudHeaders}
getAllUrl={getAllUrl}
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}>
<div className="mb-3">
<label htmlFor="componentName" className="form-label">Название компонента</label>
<input type="text" id="componentName" className="form-control" required
value={data.componentName} onChange={handleFormChange}/>
</div>
<div className="mb-3">
<label htmlFor="price" className="form-label">Цена</label>
<input type="text" id="price" className="form-control" required
value={data.price} onChange={handleFormChange}/>
</div>
</Catalog>
</main>
);
}

View File

@ -0,0 +1,112 @@
import { useState, useEffect, Component } from "react";
import CatalogProduct from "./CatalogProduct";
import Product from "../../models/Product";
import Components from "../../models/Component";
import DataService from "../../services/DataService";
export default function Menu(props) {
const url = "/product";
const categoryUrl = "/component";
const transformer = (data) => new Product(data);
const catalogStudHeaders = [
{ name: "componentName", label: "Название компонента" },
{ name: "count", label: "Количество" },
];
const [data, setData] = useState(new Product());
const [component, setComponent] = useState([]);
const [componentProduct, setComponentProduct] = useState([]);
useEffect(() => {
DataService.readAll(categoryUrl, (data) => new Components(data)).then(
(data) => setComponent(data)
);
}, []);
function handleOnAdd() {
setData(new Product());
setComponentProduct([]);
}
function handleOnEdit(data) {
setData(new Product(data));
}
function handleFormChange(event) {
setData({ ...data, [event.target.id]: event.target.value });
}
const [imageURL, setImageURL] = useState();
const fileReader = new FileReader();
fileReader.onloadend = () => {
const tempval = fileReader.result;
setImageURL(tempval);
setData({ ...data, ["picture"]: tempval });
};
function handleOnChange(event) {
event.preventDefault();
const file = event.target.files[0];
fileReader.readAsDataURL(file);
}
function handleUpdateComponents(value, bool) {
if (bool) {
let temp = data.componentDTOList.filter((x) => x.id != value.id);
data.componentDTOList = [];
for (let i = 0; i < temp.length; i++) {
data.componentDTOList.push(temp[i]);
}
data.componentDTOList.push(value);
setData(data);
}
setComponentProduct(
componentProduct.map((obj) => {
if (obj.id == value.id) {
return { ...obj, count: value.count };
} else {
return obj;
}
})
);
}
function setDataa(value) {
setData({ ...data, ["image"]: value });
}
function setComponents() {
data.componentDTOList = [];
for (let i = 0; i < componentProduct.length; i++) {
data.componentDTOList.push(componentProduct[i]);
}
setData(data);
}
function handleDeleteComponents(value) {
setComponentProduct(componentProduct.filter((x) => x.id !== value));
}
function setprice(value){
let count = 0;
for (let i = 0; i < data.componentDTOList.length; i++) {
count +=
data.componentDTOList[i].price * data.componentDTOList[i].count;
}
data.price = count;
}
return (
<main className="flex-shrink-0">
<CatalogProduct
url={url}
transformer={transformer}
data={data}
onAdd={handleOnAdd}
onEdit={handleOnEdit}
handleFormChange={handleFormChange}
handleOnChange={handleOnChange}
component={component}
catalogStudHeaders={catalogStudHeaders}
componentProduct={componentProduct}
setcomponentProduct={setComponentProduct}
updateComponents={handleUpdateComponents}
deleteComponents={handleDeleteComponents}
setData={setDataa}
set={setComponents}
setprice={setprice}
product={props.product}
setProduct={props.setProduct}
/>
</main>
);
}

View File

@ -0,0 +1,73 @@
import DataService from "../../services/DataService";
export default function Card(props) {
function edit(id) {
props.onEdit(id);
}
function remove(id) {
props.onRemove(id);
}
async function mess(id){
let currentProduct = props.product.filter(x => x.id == id.id);
if (currentProduct.length != 0){
let temp = props.product.filter(x => x.id != id.id);
currentProduct[0].count++;
temp.push(currentProduct[0]);
await props.setProduct(temp);
return;
}else{
id.count++;
props.product.push(id);
props.setProduct(props.product);
}
}
return (
<div className="temp row row-cols-1 row-cols-md-3 g-4" id="tbl-items">
{props.items.map((item) => (
<div className="col" key={item.id}>
<div className="card">
<div
className="container"
style={{ width: "100%", height: "350px" }}
>
<img
src={item["image"]}
className="img-fluid rounded mx-auto d-block"
style={{ width: "100%", height: "350px", objectFit: "contain" }}
alt="Бугер"
/>
</div>
<div className="card-body">
<h5 className="card-title text-center fs-1">{item["price"]}</h5>
<a
href="#"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
onClick={(e) => remove(item.id, e)}
>
Удалить
</a>
<a
href="#"
type="button"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
data-bs-toggle="modal"
data-bs-target="#staticBackdrop"
onClick={(e) => edit(item.id, e)}
>
Изменить
</a>
<a
type="button"
className="btn btn-outline-dark text-center d-flex justify-content-md-center mx-5"
onClick={()=>mess(item)}
>
в корзину
</a>
</div>
</div>
</div>
))}
</div>
);
}

View File

@ -0,0 +1,8 @@
export default function Footer(props) {
return (
<footer className="footer mt-auto d-flex justify-content-center align-items-center">
ООО "Вкусно" © 2022
</footer>
);
}

View File

@ -0,0 +1,35 @@
import { NavLink } from "react-router-dom";
export default function Header(props) {
return (
<nav className="navbar navbar-expand-lg">
<div className="container-fluid">
<NavLink className="navbar-brand" to={"/"}>
<h1>Очень вкусно и запятая</h1>
</NavLink>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
{props.links.map((route) => (
<li key={route.path} className="nav-item">
<NavLink className="nav-link fs-4" to={route.path}>
{route.label}
</NavLink>
</li>
))}
</ul>
</div>
</div>
</nav>
);
}

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,46 @@
import React from "react";
export default function ModalProduct(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-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,97 @@
import { useEffect } from "react";
import { useState } from "react";
import DataService from "../../services/DataService";
import Order from "../../models/Order";
export default function TableOrder(props) {
const [order, setOrder] = useState(new Order())
const [cost, setCost] = useState(0);
const [del, setDel] = useState(false);
useEffect(() => {
loadItems();
}, []);
useEffect(() => {
loadItems();
setDel(false);
}, [del]);
async function loadItems() {
await summ(props.product.sort((a, b) => a.name > b.name ? 1 : -1));
setOrder({...order,["productDTOList"]: props.product, ["price"]:cost});
}
async function summ(data) {
let tem = 0;
for (let i = 0; i < data.length; i++) {
tem += data[i].count * Number(data[i].price);
}
setCost(tem);
setOrder({...order,["price"]: tem});
}
async function deleteItem(item) {
let currentProduct = props.product.filter((x) => x.id == item.id)[0];
let temp = props.product.filter((x) => x.id != item.id);
if (currentProduct.count - 1 == 0) {
props.setProduct(temp);
setDel(true);
loadItems();
return;
} else {
currentProduct.count--;
temp.push(currentProduct);
props.setProduct(temp);
setDel(true);
loadItems();
}
}
async function needWait(){
setOrder({...order, ["price"]:cost});
}
async function acceptOrder(){
await needWait();
await DataService.create("/order",order ).then(data => {
props.setProduct([]);
setCost(0);
});
}
return (
<div>
<div style={{ maxWidth: "35%" }}>
<table className="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Позиция</th>
<th scope="col"> </th>
<th scope="col">Стоимость</th>
<th scope="col"></th>
</tr>
</thead>
<tbody className="table-group-divider">
{props.product.map((item, index) => (
<tr key={item.id}>
<th scope="row">{index + 1}</th>
<td colSpan="2">{item.name}</td>
<td>
{item.count}x{item.price} руб
</td>
<td>
<button onClick={() => deleteItem(item)}>Удалить</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<h2 className="ms-5 my-5">Итого: {cost} руб</h2>
<button
className="btn btn-success ms-5 w-25"
type="button"
style={{ color: "black" }}
onClick={acceptOrder}
>
Купить
</button>
</div>
);
}

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-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3`} onClick={add}>
Добавить
</button>
<button type="button" className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3`} onClick={edit} >
Изменить
</button >
<button type="button" className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-2 mb-3`} onClick={remove}>
Удалить
</button >
</div >
);
}

View File

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

View File

@ -0,0 +1,17 @@
export default function ToolbarProduct(props) {
function add() {
props.onAdd();
}
return (
<div className="btn-group mt-2" role="group">
<button
type="button"
className={`btn btn-outline-dark text-center d-flex justify-content-md-center mx-5 mb-3`}
onClick={add}
>
Добавить
</button>
</div>
);
}

View File

@ -1,82 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Заказы</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html">Заказы</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="components.html">Компоненты</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Продукты</a>
</li>
</ul>
</div>
</nav>
<form id="form" novalidate>
<div class="row mt-3">
<div class="col-sm-4">
<label for="orderId" class="form-label">ИД Заказа</label>
<input type="text" class="form-control" id="orderId" required>
</div>
<div class="col-sm-4">
<label for="orderDate" class="form-label">Время оформления</label>
<input type="text" class="form-control" id="orderDate" required>
</div>
<div class="col-sm-4">
<label for="orderPrice" class="form-label">Цена</label>
<input type="text" class="form-control" id="orderPrice" required>
</div>
<div class="col-sm-4">
<label for="productId" class="form-label">ИД продукта</label>
<input type="text" class="form-control" id="productId" required>
</div>
<div class="col-sm-4">
<label for="productCount" class="form-label">Количество продукта</label>
<input type="text" class="form-control" id="productCount" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Добавить</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success" id="btnUpdate" >Обновить</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button id="btnRemove" class="btn btn-success">Удалить</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">ИД</th>
<th scope="col">Дата оформления</th>
<th scope="col">Цена</th>
<th scope="col">Продукты</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="scriptOrder.js"/>
</html>

8
front/src/main.jsx Normal file
View File

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

View File

@ -0,0 +1,7 @@
export default class Component {
constructor(data) {
this.id = data?.id;
this.price = data?.price || "";
this.componentName = data?.componentName || "";
}
}

View File

@ -0,0 +1,8 @@
export default class Order {
constructor(data) {
this.id = data?.id;
this.date = data?.date || "";
this.price = data?.price || 0;
this.productDTOList = data?.productDTOList || [];
}
}

View File

@ -0,0 +1,10 @@
export default class Product {
constructor(data) {
this.id = data?.id;
this.price = data?.price || "";
this.name = data?.name || "";
this.count = data?.count || 0;
this.image = data?.image || "";
this.componentDTOList = data?.componentDTOList || [];
}
}

View File

@ -1,82 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Продукты</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.html">Заказы</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="components.html">Компоненты</a>
</li>
<li class="nav-item">
<a class="nav-link" href="products.html">Продукты</a>
</li>
</ul>
</div>
</nav>
<form id="form" novalidate>
<div class="row mt-3">
<div class="col-sm-4">
<label for="productId" class="form-label">ИД продукта</label>
<input type="text" class="form-control" id="productId" required>
</div>
<div class="col-sm-4">
<label for="productName" class="form-label">Название продукта</label>
<input type="text" class="form-control" id="productName" required>
</div>
<div class="col-sm-4">
<label for="productPrice" class="form-label">Цена</label>
<input type="text" class="form-control" id="productPrice" required>
</div>
<div class="col-sm-4">
<label for="componentId" class="form-label">ИД компонента</label>
<input type="text" class="form-control" id="componentId" required>
</div>
<div class="col-sm-4">
<label for="componentCount" class="form-label">Количество компонента</label>
<input type="text" class="form-control" id="componentCount" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Добавить</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success" id="btnUpdate" >Обновить</button>
</div>
<div class="d-grid col-sm-4 mx-auto">
<button id="btnRemove" class="btn btn-success">Удалить</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table id="table" class="table mt-3">
<thead>
<tr>
<th scope="col">ИД</th>
<th scope="col">Название продукта</th>
<th scope="col">Цена</th>
<th scope="col">Компоненты</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="scriptProduct.js"/>
</html>

View File

@ -1,100 +0,0 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const componentNameInput = document.getElementById("componentName");
const priceInput = document.getElementById("price");
const componentIdInput = document.getElementById("componentId");
const buttonRemove = document.getElementById("btnRemove");
const buttonUpdate = document.getElementById("btnUpdate");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/component");
const data = await response.json();
data.forEach(Component => {
table.innerHTML +=
`<tr>
<th scope="row" id="componentId">${Component.id}</th>
<td>${Component.componentName}</td>
<td>${Component.price}</td>
</tr>`;
})
}
const create = async function (price, componentName) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/component?price=${price}&name=${componentName}`, requestParams);
return await response.json();
}
const remove = async function (){
console.info('Try to remove item');
if (componentIdInput.value !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/component/` + componentIdInput.value, requestParams);
return await response.json();
}
const update = async function (){
console.info('Try to update item');
if (componentIdInput.value === 0 || componentNameInput.value == null || priceInput.value === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/component/${componentIdInput.value}?price=${priceInput.value}&name=${componentNameInput.value}`, requestParams);
return await response.json();
}
buttonRemove.addEventListener('click', function (event){
event.preventDefault();
remove().then((result) => {
getData()
componentIdInput.value = "";
priceInput.value = "";
componentNameInput.value = "";
});
});
buttonUpdate.addEventListener('click', function (event){
event.preventDefault();
update().then((result) => {
getData()
componentIdInput.value = "";
priceInput.value = "";
componentNameInput.value = "";
});
});
form.addEventListener("submit", function (event) {
event.preventDefault();
create(priceInput.value, componentNameInput.value).then((result) => {
getData();
priceInput.value = "";
componentNameInput.value = "";
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.componentName}]`);
});
});
getData();
});

View File

@ -1,113 +0,0 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const orderIdInput = document.getElementById("orderId");
const orderDate = document.getElementById("orderDate");
const priceInput = document.getElementById("orderPrice");
const productIdInput = document.getElementById("productId");
const productCountInput = document.getElementById("productCount");
const buttonRemove = document.getElementById("btnRemove");
const buttonUpdate = document.getElementById("btnUpdate");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/order");
const data = await response.json();
data.forEach(Order => {
let temp = "<select>";
Order.productDTOList.forEach(Product => {
temp += `<option>${Product.productName + " " + Product.count}</option>>`
})
temp += "</select>"
table.innerHTML +=
`<tr>
<th scope="row">${Order.id}</th>
<td>${Order.date}</td>
<td>${Order.price}</td>
<td>${temp}</td>
</tr>`;
})
}
const create = async function () {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
let temp = Date.now();
let time = new Date(temp);
let tru = time.toString();
const response = await fetch(host + `/order?price=${priceInput.value}&date=${tru}&count=${productCountInput.value}&prod=${productIdInput.value}`, requestParams);
return await response.json();
}
const remove = async function (){
console.info('Try to remove item');
if (orderIdInput.value !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/order/` + orderIdInput.value, requestParams);
return await response.json();
}
const update = async function (){
console.info('Try to update item');
if (orderIdInput.value === 0 || orderDate.value == null || orderPrice.value === 0 || productIdInput.value === 0 || productCountInput.value === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
let temp = Date.now();
let time = new Date(temp);
let tru = time.toString();
const response = await fetch(host + `/order/${orderIdInput.value}?price=${priceInput.value}&date=${tru}&count=${productCountInput.value}&prod=${productIdInput.value}`, requestParams);
return await response.json();
}
buttonRemove.addEventListener('click', function (event){
event.preventDefault();
remove().then((result) => {
getData()
orderIdInput.value = "";
});
});
buttonUpdate.addEventListener('click', function (event){
event.preventDefault();
update().then((result) => {
getData()
orderIdInput.value = "";
priceInput.value = "";
});
});
form.addEventListener("submit", function (event) {
event.preventDefault();
create().then((result) => {
getData();
priceInput.value = "";
orderIdInput.value = "";
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.date}]`);
});
});
getData();
});

View File

@ -1,106 +0,0 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const productIdInpit = document.getElementById("productId");
const productNameInput = document.getElementById("productName");
const priceInput = document.getElementById("productPrice");
const componentIdInput = document.getElementById("componentId");
const componentCountInput = document.getElementById("componentCount");
const buttonRemove = document.getElementById("btnRemove");
const buttonUpdate = document.getElementById("btnUpdate");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/product");
const data = await response.json();
data.forEach(Product => {
let temp = "<select>";
Product.componentDTOList.forEach(Component => {
temp += `<option>${Component.componentName + " " + Component.count}</option>>`
})
temp += "</select>"
table.innerHTML +=
`<tr>
<th scope="row">${Product.id}</th>
<td>${Product.productName}</td>
<td>${Product.price}</td>
<td>${temp}</td>
</tr>`;
})
}
const create = async function () {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/product?price=${priceInput.value}&name=${productNameInput.value}&count=${componentCountInput.value}&comp=${componentIdInput.value}`, requestParams);
return await response.json();
}
const remove = async function (){
console.info('Try to remove item');
if (productIdInpit.value !== 0) {
if (!confirm('Do you really want to remove this item?')) {
console.info('Canceled');
return;
}
}
const requestParams = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/product/` + productIdInpit.value, requestParams);
return await response.json();
}
const update = async function (){
console.info('Try to update item');
if (productIdInpit.value === 0 || productNameInput.value == null || priceInput.value === 0 || componentIdInput.value === 0 || componentCountInput.value === 0) {
return;
}
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/product/${productIdInpit.value}?price=${priceInput.value}&name=${productNameInput.value}&count=${componentCountInput.value}&comp=${componentIdInput.value}`, requestParams);
return await response.json();
}
buttonRemove.addEventListener('click', function (event){
event.preventDefault();
remove().then((result) => {
getData()
productIdInpit.value = "";
});
});
buttonUpdate.addEventListener('click', function (event){
event.preventDefault();
update().then((result) => {
getData()
componentIdInput.value = "";
priceInput.value = "";
});
});
form.addEventListener("submit", function (event) {
event.preventDefault();
create().then((result) => {
getData();
priceInput.value = "";
productNameInput.value = "";
alert(`Component[id=${result.id}, price=${result.price}, componentName=${result.productName}]`);
});
});
getData();
});

View File

@ -0,0 +1,44 @@
import axios from 'axios';
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080';
static async readAll(url, transformer) {
const response = await fetch(this.dataUrlPrefix + url);
const data = await response.json();
return 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) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
const response = await fetch(this.dataUrlPrefix + url, requestParams);
}
static async update(url, data) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
};
const response = await fetch(this.dataUrlPrefix + url, requestParams);
return true;
}
static async delete(url) {
const response = await axios.delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

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