Лабораторная 5
24
Lab5/.eslintrc.cjs
Normal file
@ -0,0 +1,24 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: { browser: true, es2020: true },
|
||||
extends: [
|
||||
'airbnb-base',
|
||||
'plugin:react/recommended',
|
||||
'plugin:react/jsx-runtime',
|
||||
'plugin:react-hooks/recommended',
|
||||
],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
||||
parserOptions: { ecmaVersion: 12, sourceType: 'module' },
|
||||
settings: { react: { version: '18.2' } },
|
||||
plugins: ['react-refresh'],
|
||||
rules: {
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
'indent': 'off',
|
||||
'no-console': 'off',
|
||||
'arrow-body-style': 'off',
|
||||
'implicit-arrow-linebreak': 'off',
|
||||
},
|
||||
}
|
24
Lab5/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
29
Lab5/README.md
Normal file
@ -0,0 +1,29 @@
|
||||
#### Окружение:
|
||||
- nodejs 18;
|
||||
- VSCode;
|
||||
- ESLint плагин для VSCode;
|
||||
- для отладки необходимы бразузеры Chrome или Edge.
|
||||
|
||||
#### Создание пустого проекта:
|
||||
|
||||
```commandline
|
||||
npm create vite@latest ./ -- --template react
|
||||
```
|
||||
|
||||
#### Установка зависимостей:
|
||||
|
||||
```commandline
|
||||
npm install
|
||||
```
|
||||
|
||||
#### Запуск проекта:
|
||||
|
||||
```commandline
|
||||
npm run dev
|
||||
```
|
||||
|
||||
#### Сборка проекта:
|
||||
|
||||
```commandline
|
||||
npm run build
|
||||
```
|
120
Lab5/data.json
Normal file
14
Lab5/index.html
Normal file
@ -0,0 +1,14 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image" href="/src/assets/logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>FastFood</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root" class="h-100 d-flex flex-column"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
15
Lab5/jsconfig.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"target": "ES2020",
|
||||
"jsx": "react",
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"**/node_modules/*"
|
||||
]
|
||||
}
|
5
Lab5/json-server.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"static": "./node_modules/json-server/public",
|
||||
"port": 8081,
|
||||
"watch": "true"
|
||||
}
|
5936
Lab5/package-lock.json
generated
Normal file
38
Lab5/package.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "ip5",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
|
||||
"rest": "json-server data.json",
|
||||
"vite": "vite",
|
||||
"dev": "npm-run-all --parallel rest vite",
|
||||
"prod": "npm-run-all lint 'vite build' --parallel rest 'vite preview'"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.18.0",
|
||||
"react-hot-toast": "^2.4.1",
|
||||
"axios": "^1.6.1",
|
||||
"bootstrap": "^5.3.2",
|
||||
"react-bootstrap": "^2.9.1",
|
||||
"react-bootstrap-icons": "^1.10.3",
|
||||
"prop-types": "^15.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.15",
|
||||
"@types/react-dom": "^18.2.15",
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"eslint": "^8.45.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint-plugin-import": "^2.29.0",
|
||||
"eslint-plugin-react": "^7.32.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.3",
|
||||
"json-server": "^0.17.4",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"vite": "^4.4.5"
|
||||
}
|
||||
}
|
BIN
Lab5/public/BackgroundAboutUs.png
Normal file
After Width: | Height: | Size: 2.4 MiB |
BIN
Lab5/public/BackgroundBasket.png
Normal file
After Width: | Height: | Size: 2.8 MiB |
BIN
Lab5/public/BackgroundOurContacts.png
Normal file
After Width: | Height: | Size: 2.4 MiB |
BIN
Lab5/public/BakcgroundRegistration.png
Normal file
After Width: | Height: | Size: 2.5 MiB |
3
Lab5/public/favicon.svg
Normal file
@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-cart2" viewBox="0 0 16 16">
|
||||
<path d="M0 2.5A.5.5 0 0 1 .5 2H2a.5.5 0 0 1 .485.379L2.89 4H14.5a.5.5 0 0 1 .485.621l-1.5 6A.5.5 0 0 1 13 11H4a.5.5 0 0 1-.485-.379L1.61 3H.5a.5.5 0 0 1-.5-.5zM3.14 5l1.25 5h8.22l1.25-5H3.14zM5 13a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0zm9-1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0z"/>
|
||||
</svg>
|
After Width: | Height: | Size: 463 B |
29
Lab5/src/App.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Container } from 'react-bootstrap';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import Footer from './components/footer/Footer.jsx';
|
||||
import { CartProvider } from './components/cart/CartContext.jsx';
|
||||
import Navigation from './components/navigation/Navigation.jsx';
|
||||
import { LoginProvider } from './components/login/LoginContext.jsx';
|
||||
|
||||
const App = ({ routes }) => {
|
||||
return (
|
||||
<>
|
||||
<LoginProvider>
|
||||
<CartProvider>
|
||||
<Navigation routes={routes}></Navigation>
|
||||
<Container className='px-0' as="main" fluid>
|
||||
<Outlet />
|
||||
</Container>
|
||||
<Footer />
|
||||
</CartProvider>
|
||||
</LoginProvider>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
App.propTypes = {
|
||||
routes: PropTypes.array,
|
||||
};
|
||||
|
||||
export default App;
|
BIN
Lab5/src/assets/200.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
Lab5/src/assets/Background.png
Normal file
After Width: | Height: | Size: 414 KiB |
BIN
Lab5/src/assets/BackgroundAboutUs.png
Normal file
After Width: | Height: | Size: 2.4 MiB |
BIN
Lab5/src/assets/BackgroundBasket.png
Normal file
After Width: | Height: | Size: 2.8 MiB |
BIN
Lab5/src/assets/BackgroundOurContacts.png
Normal file
After Width: | Height: | Size: 2.4 MiB |
BIN
Lab5/src/assets/BakcgroundRegistration.png
Normal file
After Width: | Height: | Size: 2.5 MiB |
BIN
Lab5/src/assets/Burger.png
Normal file
After Width: | Height: | Size: 98 KiB |
BIN
Lab5/src/assets/Cola.png
Normal file
After Width: | Height: | Size: 37 KiB |
BIN
Lab5/src/assets/Man1.png
Normal file
After Width: | Height: | Size: 165 KiB |
BIN
Lab5/src/assets/Salat.png
Normal file
After Width: | Height: | Size: 61 KiB |
BIN
Lab5/src/assets/Shaurma.png
Normal file
After Width: | Height: | Size: 139 KiB |
BIN
Lab5/src/assets/ShaurmaForMenu.png
Normal file
After Width: | Height: | Size: 47 KiB |
BIN
Lab5/src/assets/logo.png
Normal file
After Width: | Height: | Size: 5.9 KiB |
40
Lab5/src/components/api/ApiClient.js
Normal file
@ -0,0 +1,40 @@
|
||||
import axios from 'axios';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(message = '') {
|
||||
super(message);
|
||||
this.name = 'HttpError';
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
toast.error(message, { id: 'HttpError' });
|
||||
}
|
||||
}
|
||||
|
||||
function responseHandler(response) {
|
||||
if (response.status === 200 || response.status === 201) {
|
||||
const data = response?.data;
|
||||
if (!data) {
|
||||
throw new HttpError('API Error. No data!');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
throw new HttpError(`API Error! Invalid status code ${response.status}!`);
|
||||
}
|
||||
|
||||
function responseErrorHandler(error) {
|
||||
if (error === null) {
|
||||
throw new Error('Unrecoverable error!! Error is null!');
|
||||
}
|
||||
toast.error(error.message, { id: 'AxiosError' });
|
||||
return Promise.reject(error.message);
|
||||
}
|
||||
|
||||
export const ApiClient = axios.create({
|
||||
baseURL: 'http://localhost:8081/',
|
||||
timeout: '3000',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
ApiClient.interceptors.response.use(responseHandler, responseErrorHandler);
|
29
Lab5/src/components/api/ApiService.js
Normal file
@ -0,0 +1,29 @@
|
||||
import { ApiClient } from './ApiClient';
|
||||
|
||||
class ApiService {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
async getAll(expand) {
|
||||
return ApiClient.get(`${this.url}${expand || ''}`);
|
||||
}
|
||||
|
||||
async get(id, expand) {
|
||||
return ApiClient.get(`${this.url}/${id}${expand || ''}`);
|
||||
}
|
||||
|
||||
async create(body) {
|
||||
return ApiClient.post(this.url, body);
|
||||
}
|
||||
|
||||
async update(id, body) {
|
||||
return ApiClient.put(`${this.url}/${id}`, body);
|
||||
}
|
||||
|
||||
async delete(id) {
|
||||
return ApiClient.delete(`${this.url}/${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
export default ApiService;
|
8
Lab5/src/components/cart/Cart.css
Normal file
@ -0,0 +1,8 @@
|
||||
.cart-image {
|
||||
width: 3.1rem;
|
||||
padding: .25rem;
|
||||
}
|
||||
|
||||
.cart-item {
|
||||
height: auto;
|
||||
}
|
59
Lab5/src/components/cart/Cart.jsx
Normal file
@ -0,0 +1,59 @@
|
||||
import { Button, ButtonGroup, Card } from 'react-bootstrap';
|
||||
import { DashLg, PlusLg, XLg } from 'react-bootstrap-icons';
|
||||
import imgPlaceholder from '../../assets/200.png';
|
||||
import './Cart.css';
|
||||
import useCart from './CartHook';
|
||||
|
||||
const Cart = () => {
|
||||
const {
|
||||
cart,
|
||||
getCartSum,
|
||||
addToCart,
|
||||
removeFromCart,
|
||||
clearCart,
|
||||
} = useCart();
|
||||
|
||||
return (
|
||||
<div className='d-flex flex-column align-items-center min-vh-100 my-4'>
|
||||
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex align-items-center'>
|
||||
<strong className='flex-fill'>Корзина</strong>
|
||||
<Button variant='danger' onClick={() => clearCart()}>
|
||||
<XLg /> Очистить
|
||||
</Button>
|
||||
</div>
|
||||
{
|
||||
cart.map((cartItem) =>
|
||||
<Card key={cartItem.id} className='mb-2 col-12 col-md-8 col-lg-6'>
|
||||
<Card.Body className='p-2 d-flex flex-column flex-sm-row align-items-center'>
|
||||
<div className='cart-item flex-fill'>
|
||||
<img className='cart-image' src={cartItem.image || imgPlaceholder} alt="Cart Image" />
|
||||
{cartItem.type.name}
|
||||
</div>
|
||||
<div className='cart-item mt-2 mt-sm-0 d-flex flex-column align-items-center align-items-sm-end'>
|
||||
<div>
|
||||
{cartItem.price}
|
||||
{' * '}
|
||||
{cartItem.count}
|
||||
{' = '}
|
||||
{parseFloat(cartItem.price * cartItem.count).toFixed(2)}
|
||||
</div>
|
||||
<ButtonGroup className='mt-2 mt-sm-1' aria-label="Cart counter">
|
||||
<Button variant="primary" onClick={() => addToCart(cartItem)}>
|
||||
<PlusLg />
|
||||
</Button>
|
||||
<Button variant="danger" onClick={() => removeFromCart(cartItem)}>
|
||||
<DashLg />
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
</Card.Body>
|
||||
</Card>)
|
||||
}
|
||||
<div className='mb-2 col-12 col-md-8 col-lg-6 d-flex justify-content-end'>
|
||||
<strong>Итого: {getCartSum()} ₽</strong>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Cart;
|
29
Lab5/src/components/cart/CartContext.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import {
|
||||
createContext,
|
||||
useEffect,
|
||||
useReducer,
|
||||
} from 'react';
|
||||
import { cartReducer, loadCart, saveCart } from './CartReducer';
|
||||
|
||||
const CartContext = createContext(null);
|
||||
|
||||
export const CartProvider = ({ children }) => {
|
||||
const [cart, dispatch] = useReducer(cartReducer, [], loadCart);
|
||||
|
||||
useEffect(() => {
|
||||
saveCart(cart || []);
|
||||
}, [cart]);
|
||||
|
||||
return (
|
||||
<CartContext.Provider value={{ cart, dispatch }}>
|
||||
{children}
|
||||
</CartContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
CartProvider.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default CartContext;
|
26
Lab5/src/components/cart/CartHook.js
Normal file
@ -0,0 +1,26 @@
|
||||
import { useContext } from 'react';
|
||||
import CartContext from './CartContext.jsx';
|
||||
import { cartAdd, cartClear, cartRemove } from './CartReducer';
|
||||
|
||||
const useCart = () => {
|
||||
const { cart, dispatch } = useContext(CartContext);
|
||||
|
||||
const cartSum = () => {
|
||||
return parseFloat(
|
||||
cart?.reduce((sum, cartItem) => {
|
||||
return sum + (cartItem.price * cartItem.count);
|
||||
}, 0)
|
||||
?? 0,
|
||||
).toFixed(2);
|
||||
};
|
||||
|
||||
return {
|
||||
cart,
|
||||
getCartSum: () => cartSum(),
|
||||
addToCart: (item) => dispatch(cartAdd(item)),
|
||||
removeFromCart: (item) => dispatch(cartRemove(item)),
|
||||
clearCart: () => dispatch(cartClear()),
|
||||
};
|
||||
};
|
||||
|
||||
export default useCart;
|
71
Lab5/src/components/cart/CartReducer.js
Normal file
@ -0,0 +1,71 @@
|
||||
const setCartCount = (cart, item, value) => {
|
||||
return cart.map((cartItem) => {
|
||||
if (cartItem.id === item.id) {
|
||||
return { ...cartItem, count: cartItem.count + value };
|
||||
}
|
||||
return cartItem;
|
||||
});
|
||||
};
|
||||
|
||||
const addToCart = (cart, item) => {
|
||||
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
|
||||
if (existsItem !== undefined) {
|
||||
return setCartCount(cart, item, 1);
|
||||
}
|
||||
return [...cart, { ...item, count: 1 }];
|
||||
};
|
||||
|
||||
const removeFromCart = (cart, item) => {
|
||||
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
|
||||
if (existsItem !== undefined && existsItem.count > 1) {
|
||||
return setCartCount(cart, item, -1);
|
||||
}
|
||||
return cart.filter((cartItem) => cartItem.id !== item.id);
|
||||
};
|
||||
|
||||
const CART_KEY = 'localCart';
|
||||
const CART_ADD = 'cart/add';
|
||||
const CART_REMOVE = 'cart/remove';
|
||||
const CART_CLEAR = 'cart/clear';
|
||||
|
||||
export const saveCart = (cart) => {
|
||||
localStorage.setItem(CART_KEY, JSON.stringify(cart));
|
||||
};
|
||||
|
||||
export const loadCart = (initialValue = []) => {
|
||||
const cartData = localStorage.getItem(CART_KEY);
|
||||
if (cartData) {
|
||||
return JSON.parse(cartData);
|
||||
}
|
||||
return initialValue;
|
||||
};
|
||||
|
||||
export const cartReducer = (cart, action) => {
|
||||
const { item } = action;
|
||||
switch (action.type) {
|
||||
case CART_ADD: {
|
||||
return addToCart(cart, item);
|
||||
}
|
||||
case CART_REMOVE: {
|
||||
return removeFromCart(cart, item);
|
||||
}
|
||||
case CART_CLEAR: {
|
||||
return [];
|
||||
}
|
||||
default: {
|
||||
throw Error(`Unknown action: ${action.type}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const cartAdd = (item) => ({
|
||||
type: CART_ADD, item,
|
||||
});
|
||||
|
||||
export const cartRemove = (item) => ({
|
||||
type: CART_REMOVE, item,
|
||||
});
|
||||
|
||||
export const cartClear = () => ({
|
||||
type: CART_CLEAR,
|
||||
});
|
27
Lab5/src/components/cartItems/hooks/CartItemsHook.js
Normal file
@ -0,0 +1,27 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import CartItemsApiService from '../service/CartItemsApiService';
|
||||
|
||||
const useCartItems = (userFilter) => {
|
||||
const [cartItems, setCartItems] = useState([]);
|
||||
|
||||
const getCartItems = async () => {
|
||||
let expand = '';
|
||||
if (userFilter) {
|
||||
expand = `?userId=${userFilter}`;
|
||||
}
|
||||
const data = await CartItemsApiService.getAll(expand);
|
||||
setCartItems(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getCartItems();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [userFilter]);
|
||||
|
||||
return {
|
||||
cartItems,
|
||||
setCartItems,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCartItems;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const CartItemsApiService = new ApiService('cart-items');
|
||||
|
||||
export default CartItemsApiService;
|
21
Lab5/src/components/categories/hooks/CategoriesHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import CategoriesApiService from '../service/CategoriesApiService';
|
||||
|
||||
const useCategories = () => {
|
||||
const [categories, setCategories] = useState([]);
|
||||
|
||||
const getCategories = async () => {
|
||||
const data = await CategoriesApiService.getAll();
|
||||
setCategories(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getCategories();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
categories,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCategories;
|
30
Lab5/src/components/categories/hooks/CategoriesItemHook.js
Normal file
@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import CategoriesApiService from '../service/CategoriesApiService';
|
||||
|
||||
const useCategoriesItem = (id) => {
|
||||
const emptyItem = {
|
||||
id: '',
|
||||
name: '',
|
||||
};
|
||||
const [item, setItem] = useState({ ...emptyItem });
|
||||
|
||||
const getItem = async (itemId = undefined) => {
|
||||
if (itemId && itemId > 0) {
|
||||
const data = await CategoriesApiService.get(itemId);
|
||||
setItem(data);
|
||||
} else {
|
||||
setItem({ ...emptyItem });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getItem(id);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
return {
|
||||
item,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCategoriesItem;
|
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const CategoriesApiService = new ApiService('categories');
|
||||
|
||||
export default CategoriesApiService;
|
5
Lab5/src/components/footer/Footer.css
Normal file
@ -0,0 +1,5 @@
|
||||
.my-footer {
|
||||
background-color: #9c9c9c;
|
||||
height: 32px;
|
||||
color: #fff;
|
||||
}
|
16
Lab5/src/components/footer/Footer.jsx
Normal file
@ -0,0 +1,16 @@
|
||||
import './Footer.css';
|
||||
|
||||
const Footer = () => {
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
return (
|
||||
<footer className="my-footer mt-auto d-flex flex-shrink-0 justify-content-center align-items-center">
|
||||
Fastest Food, {year}
|
||||
Время работы:
|
||||
ПН-ПТ:10-19
|
||||
СБ-ВС:12-17
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Footer;
|
23
Lab5/src/components/input/Input.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Input = ({
|
||||
name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
|
||||
<Form.Label>{label}</Form.Label>
|
||||
<Form.Control name={name || ''} value={value || ''} onChange={onChange} {...rest} />
|
||||
</Form.Group>
|
||||
);
|
||||
};
|
||||
|
||||
Input.propTypes = {
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.string,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Input;
|
29
Lab5/src/components/input/Select.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Select = ({
|
||||
values, name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`mb-2 ${className || ''}`} controlId={name}>
|
||||
<Form.Label className='form-label'>{label}</Form.Label>
|
||||
<Form.Select name={name || ''} value={value || ''} onChange={onChange} {...rest}>
|
||||
<option value=''>Выберите значение</option>
|
||||
{
|
||||
values.map((type) => <option key={type.id} value={type.id}>{type.name}</option>)
|
||||
}
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
);
|
||||
};
|
||||
|
||||
Select.propTypes = {
|
||||
values: PropTypes.array,
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.string,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Select;
|
33
Lab5/src/components/item/Item.jsx
Normal file
@ -0,0 +1,33 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import imgPlaceholder from '../../assets/200.png';
|
||||
import useLinesItem from '../lines/hooks/LinesItemFormHook';
|
||||
|
||||
const Item = ({ id }) => {
|
||||
const { item } = useLinesItem(id);
|
||||
const price = `${parseInt(item.price, 10)} ₽`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="allAboutUs d-flex flex-fill align-items-center justify-content-center min-vh-100">
|
||||
<div className="bg-white rounded-5 p-5">
|
||||
<h1 className="text-center">{item.food}</h1>
|
||||
<p className='text-center'>{price}</p>
|
||||
<div className="d-flex flex-column flex-md-row justify-content-evenly align-items-center">
|
||||
<img className="w-25 h-25" src={item.image || imgPlaceholder} />
|
||||
</div>
|
||||
<div className="d-flex justify-content-center">
|
||||
<a href="basket.html" className="btn btn-danger">
|
||||
Добавить в корзину
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Item.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Item;
|
48
Lab5/src/components/lines/form/LinesForm.jsx
Normal file
@ -0,0 +1,48 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import useLinesItemForm from '../hooks/LinesItemFormHook';
|
||||
import LinesItemForm from './LinesItemForm.jsx';
|
||||
|
||||
const LinesForm = ({ id }) => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
item,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useLinesItemForm(id);
|
||||
|
||||
const onBack = () => {
|
||||
navigate(-1);
|
||||
};
|
||||
|
||||
const onSubmit = async (event) => {
|
||||
if (await handleSubmit(event)) {
|
||||
onBack();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form className='m-0 p-2' noValidate validated={validated} onSubmit={onSubmit}>
|
||||
<LinesItemForm item={item} handleChange={handleChange} />
|
||||
<Form.Group className='row justify-content-center m-0 mt-3'>
|
||||
<Button className='col-5 col-lg-2 m-0 me-2' variant='secondary' onClick={() => onBack()}>
|
||||
Назад
|
||||
</Button>
|
||||
<Button className='col-5 col-lg-2 m-0 ms-2' type='submit' variant='primary'>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesForm.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default LinesForm;
|
3
Lab5/src/components/lines/form/LinesItemForm.css
Normal file
@ -0,0 +1,3 @@
|
||||
#image-preview {
|
||||
width: 200px;
|
||||
}
|
38
Lab5/src/components/lines/form/LinesItemForm.jsx
Normal file
@ -0,0 +1,38 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import imgPlaceholder from '../../../assets/200.png';
|
||||
import Input from '../../input/Input.jsx';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import useTypes from '../../types/hooks/TypesHook';
|
||||
import './LinesItemForm.css';
|
||||
|
||||
const LinesItemForm = ({ item, handleChange }) => {
|
||||
const { types } = useTypes();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='text-center'>
|
||||
<img id='image-preview' className='rounded' alt='placeholder'
|
||||
src={item.image || imgPlaceholder} />
|
||||
</div>
|
||||
<Select values={types} name='typeId' label='Тип' value={item.typeId} onChange={handleChange}
|
||||
required />
|
||||
<Input name='food' label='Название товара' value={item.food} onChange={handleChange}
|
||||
type='text' required />
|
||||
<Input name='date' label='Дата поступления' value={item.date} onChange={handleChange}
|
||||
type='date' required />
|
||||
<Input name='price' label='Цена' value={item.price} onChange={handleChange}
|
||||
type='number' min='100.0' step='10.0' required />
|
||||
<Input name='count' label='Количество' value={item.count} onChange={handleChange}
|
||||
type='number' min='1' step='1' required />
|
||||
<Input name='image' label='Изображение' onChange={handleChange}
|
||||
type='file' accept='image/*' />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesItemForm.propTypes = {
|
||||
item: PropTypes.object,
|
||||
handleChange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesItemForm;
|
34
Lab5/src/components/lines/hooks/LinesDeleteModalHook.js
Normal file
@ -0,0 +1,34 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useModal from '../../modal/ModalHook';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLinesDeleteModal = (linesChangeHandle) => {
|
||||
const { isModalShow, showModal, hideModal } = useModal();
|
||||
const [currentId, setCurrentId] = useState(0);
|
||||
|
||||
const showModalDialog = (id) => {
|
||||
showModal();
|
||||
setCurrentId(id);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
hideModal();
|
||||
};
|
||||
|
||||
const onDelete = async () => {
|
||||
await LinesApiService.delete(currentId);
|
||||
linesChangeHandle();
|
||||
toast.success('Элемент успешно удален', { id: 'LinesTable' });
|
||||
onClose();
|
||||
};
|
||||
|
||||
return {
|
||||
isDeleteModalShow: isModalShow,
|
||||
showDeleteModal: showModalDialog,
|
||||
handleDeleteConfirm: onDelete,
|
||||
handleDeleteCancel: onClose,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesDeleteModal;
|
28
Lab5/src/components/lines/hooks/LinesFilterHook.js
Normal file
@ -0,0 +1,28 @@
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import useTypes from '../../types/hooks/TypesHook';
|
||||
|
||||
const useTypeFilter = () => {
|
||||
const filterName = 'type';
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const { types } = useTypes();
|
||||
|
||||
const handleFilterChange = (event) => {
|
||||
const type = event.target.value;
|
||||
if (type) {
|
||||
searchParams.set(filterName, event.target.value);
|
||||
} else {
|
||||
searchParams.delete(filterName);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
};
|
||||
|
||||
return {
|
||||
types,
|
||||
currentFilter: searchParams.get(filterName) || '',
|
||||
handleFilterChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useTypeFilter;
|
45
Lab5/src/components/lines/hooks/LinesFormModalHook.js
Normal file
@ -0,0 +1,45 @@
|
||||
import { useState } from 'react';
|
||||
import useModal from '../../modal/ModalHook';
|
||||
import useLinesItemForm from './LinesItemFormHook';
|
||||
|
||||
const useLinesFormModal = (linesChangeHandle) => {
|
||||
const { isModalShow, showModal, hideModal } = useModal();
|
||||
const [currentId, setCurrentId] = useState(0);
|
||||
|
||||
const {
|
||||
item,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
} = useLinesItemForm(currentId, linesChangeHandle);
|
||||
|
||||
const showModalDialog = (id) => {
|
||||
setCurrentId(id);
|
||||
resetValidity();
|
||||
showModal();
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
setCurrentId(-1);
|
||||
hideModal();
|
||||
};
|
||||
|
||||
const onSubmit = async (event) => {
|
||||
if (await handleSubmit(event)) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isFormModalShow: isModalShow,
|
||||
isFormValidated: validated,
|
||||
showFormModal: showModalDialog,
|
||||
currentItem: item,
|
||||
handleItemChange: handleChange,
|
||||
handleFormSubmit: onSubmit,
|
||||
handleFormClose: onClose,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesFormModal;
|
29
Lab5/src/components/lines/hooks/LinesHook.js
Normal file
@ -0,0 +1,29 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLines = (typeFilter) => {
|
||||
const [linesRefresh, setLinesRefresh] = useState(false);
|
||||
const [lines, setLines] = useState([]);
|
||||
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
|
||||
|
||||
const getLines = async () => {
|
||||
let expand = '?_expand=type';
|
||||
if (typeFilter) {
|
||||
expand = `${expand}&typeId=${typeFilter}`;
|
||||
}
|
||||
const data = await LinesApiService.getAll(expand);
|
||||
setLines(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getLines();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [linesRefresh, typeFilter]);
|
||||
|
||||
return {
|
||||
lines,
|
||||
handleLinesChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLines;
|
85
Lab5/src/components/lines/hooks/LinesItemFormHook.js
Normal file
@ -0,0 +1,85 @@
|
||||
import { useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import getBase64FromFile from '../../utils/Base64';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
import useLinesItem from './LinesItemHook';
|
||||
|
||||
const useLinesItemForm = (id, linesChangeHandle) => {
|
||||
const { item, setItem } = useLinesItem(id);
|
||||
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const getLineObject = (formData) => {
|
||||
const typeId = parseInt(formData.typeId, 10);
|
||||
const { food } = formData;
|
||||
const { date } = formData;
|
||||
const price = parseFloat(formData.price).toFixed(2);
|
||||
const count = parseInt(formData.count, 10);
|
||||
const sum = parseFloat(price * count).toFixed(2);
|
||||
const image = formData.image.startsWith('data:image') ? formData.image : '';
|
||||
return {
|
||||
typeId: typeId.toString(),
|
||||
food: food.toString(),
|
||||
date: date.toString(),
|
||||
price: price.toString(),
|
||||
count: count.toString(),
|
||||
sum: sum.toString(),
|
||||
image,
|
||||
};
|
||||
};
|
||||
|
||||
const handleImageChange = async (event) => {
|
||||
const { files } = event.target;
|
||||
const file = await getBase64FromFile(files.item(0));
|
||||
setItem({
|
||||
...item,
|
||||
image: file,
|
||||
});
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
if (event.target.type === 'file') {
|
||||
handleImageChange(event);
|
||||
return;
|
||||
}
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
setItem({
|
||||
...item,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const body = getLineObject(item);
|
||||
if (form.checkValidity()) {
|
||||
if (id === undefined) {
|
||||
await LinesApiService.create(body);
|
||||
} else {
|
||||
await LinesApiService.update(id, body);
|
||||
}
|
||||
if (linesChangeHandle) linesChangeHandle();
|
||||
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
|
||||
return true;
|
||||
}
|
||||
setValidated(true);
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
item,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesItemForm;
|
34
Lab5/src/components/lines/hooks/LinesItemHook.js
Normal file
@ -0,0 +1,34 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLinesItem = (id) => {
|
||||
const emptyItem = {
|
||||
id: '',
|
||||
typeId: '',
|
||||
price: '0',
|
||||
count: '0',
|
||||
image: '',
|
||||
};
|
||||
const [item, setItem] = useState({ ...emptyItem });
|
||||
|
||||
const getItem = async (itemId = undefined) => {
|
||||
if (itemId && itemId > 0) {
|
||||
const data = await LinesApiService.get(itemId);
|
||||
setItem(data);
|
||||
} else {
|
||||
setItem({ ...emptyItem });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getItem(id);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
return {
|
||||
item,
|
||||
setItem,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLinesItem;
|
5
Lab5/src/components/lines/service/LinesApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const LinesApiService = new ApiService('lines');
|
||||
|
||||
export default LinesApiService;
|
79
Lab5/src/components/lines/table/Lines.jsx
Normal file
@ -0,0 +1,79 @@
|
||||
import { Button } from 'react-bootstrap';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import ModalConfirm from '../../modal/ModalConfirm.jsx';
|
||||
import useCart from '../../cart/CartHook';
|
||||
import ModalForm from '../../modal/ModalForm.jsx';
|
||||
import LinesItemForm from '../form/LinesItemForm.jsx';
|
||||
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
|
||||
import useTypeFilter from '../hooks/LinesFilterHook';
|
||||
import useLinesFormModal from '../hooks/LinesFormModalHook';
|
||||
import useLines from '../hooks/LinesHook';
|
||||
import LinesTable from './LinesTable.jsx';
|
||||
import LinesTableRow from './LinesTableRow.jsx';
|
||||
|
||||
const Lines = () => {
|
||||
const { types, currentFilter, handleFilterChange } = useTypeFilter();
|
||||
|
||||
const { lines, handleLinesChange } = useLines(currentFilter);
|
||||
|
||||
const {
|
||||
isDeleteModalShow,
|
||||
showDeleteModal,
|
||||
handleDeleteConfirm,
|
||||
handleDeleteCancel,
|
||||
} = useLinesDeleteModal(handleLinesChange);
|
||||
|
||||
const {
|
||||
isFormModalShow,
|
||||
isFormValidated,
|
||||
showFormModal,
|
||||
currentItem,
|
||||
handleItemChange,
|
||||
handleFormSubmit,
|
||||
handleFormClose,
|
||||
} = useLinesFormModal(handleLinesChange);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const showEditPage = (id) => {
|
||||
navigate(`/PageEdit/${id}`);
|
||||
};
|
||||
|
||||
const { addToCart } = useCart();
|
||||
|
||||
return (
|
||||
<div className='min-vh-100'>
|
||||
<Select className='text-center mt-2' values={types} label='Фильтр по товарам'
|
||||
value={currentFilter} onChange={handleFilterChange} />
|
||||
<LinesTable>
|
||||
{
|
||||
lines.map((line, index) =>
|
||||
<LinesTableRow key={line.id}
|
||||
index={index} line={line}
|
||||
onAddCart={() => addToCart(line)}
|
||||
onDelete={() => showDeleteModal(line.id)}
|
||||
onEdit={() => showFormModal(line.id)}
|
||||
onEditInPage={() => showEditPage(line.id)}
|
||||
/>)
|
||||
}
|
||||
</LinesTable>
|
||||
<div className='d-flex justify-content-center'>
|
||||
<Button as={Link} to='/PageEdit' variant='success'>
|
||||
Добавить товар
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ModalConfirm show={isDeleteModalShow}
|
||||
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
|
||||
title='Удаление' message='Удалить элемент?' />
|
||||
<ModalForm show={isFormModalShow} validated={isFormValidated}
|
||||
onSubmit={handleFormSubmit} onClose={handleFormClose}
|
||||
title='Редактирование'>
|
||||
<LinesItemForm item={currentItem} handleChange={handleItemChange} />
|
||||
</ModalForm>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Lines;
|
32
Lab5/src/components/lines/table/LinesTable.jsx
Normal file
@ -0,0 +1,32 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Table } from 'react-bootstrap';
|
||||
|
||||
const LinesTable = ({ children }) => {
|
||||
return (
|
||||
<Table className='mt-2' striped responsive>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope='col'>№</th>
|
||||
<th scope='col' className='w-25'>Тип</th>
|
||||
<th scope='col' className='w-25'>Название</th>
|
||||
<th scope='col' className='w-25'>Дата поступления</th>
|
||||
<th scope='col' className='w-25'>Цена</th>
|
||||
<th scope='col' className='w-25'>Колич.</th>
|
||||
<th scope='col' className='w-25'>Сумма</th>
|
||||
<th scope='col'></th>
|
||||
<th scope='col'></th>
|
||||
<th scope='col'></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{children}
|
||||
</tbody >
|
||||
</Table >
|
||||
);
|
||||
};
|
||||
|
||||
LinesTable.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default LinesTable;
|
38
Lab5/src/components/lines/table/LinesTableRow.jsx
Normal file
@ -0,0 +1,38 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import {
|
||||
Cart, PencilSquare, Trash3,
|
||||
} from 'react-bootstrap-icons';
|
||||
|
||||
const LinesTableRow = ({
|
||||
index, line, onAddCart, onDelete, onEditInPage,
|
||||
}) => {
|
||||
const handleAnchorClick = (event, action) => {
|
||||
event.preventDefault();
|
||||
action();
|
||||
};
|
||||
|
||||
return (
|
||||
<tr>
|
||||
<th scope="row">{index + 1}</th>
|
||||
<td>{line.type.name}</td>
|
||||
<td>{line.food}</td>
|
||||
<td>{line.date}</td>
|
||||
<td>{parseFloat(line.price).toFixed(2)}</td>
|
||||
<td>{line.count}</td>
|
||||
<td>{parseFloat(line.sum).toFixed(2)}</td>
|
||||
<td><a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}><Cart /></a></td>
|
||||
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a></td>
|
||||
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
|
||||
</tr>
|
||||
);
|
||||
};
|
||||
|
||||
LinesTableRow.propTypes = {
|
||||
index: PropTypes.number,
|
||||
line: PropTypes.object,
|
||||
onAddCart: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
onEditInPage: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesTableRow;
|
23
Lab5/src/components/login/LoginContext.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import {
|
||||
createContext,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
const LoginContext = createContext(null);
|
||||
|
||||
export const LoginProvider = ({ children }) => {
|
||||
const [login, setLogin] = useState(JSON.parse(localStorage.getItem('localLogin')));
|
||||
|
||||
return (
|
||||
<LoginContext.Provider value={{ login, setLogin }}>
|
||||
{children}
|
||||
</LoginContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
LoginProvider.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default LoginContext;
|
43
Lab5/src/components/login/LoginForm.jsx
Normal file
@ -0,0 +1,43 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import { useState } from 'react';
|
||||
import useLoginForm from './LoginHook';
|
||||
|
||||
const LoginForm = () => {
|
||||
const {
|
||||
formData,
|
||||
validated,
|
||||
correctLoginInfo,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useLoginForm();
|
||||
let wrongLoginInfoWarning;
|
||||
if (!correctLoginInfo) wrongLoginInfoWarning = (<p className='text-danger text-center mt-3'>Неверные Email или пароль</p>);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form className="p-5 rounded login-form" noValidate validated={validated} onSubmit={handleSubmit}>
|
||||
<Form.Group className='mb-2 fw-bold' controlId='email'>
|
||||
<Form.Label>E-mail</Form.Label>
|
||||
<Form.Control type='email' name='email' required
|
||||
value={formData.email} onChange={handleChange} />
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2 position-relative" controlId='password'>
|
||||
<Form.Label className="fw-bold">Пароль</Form.Label>
|
||||
<Form.Control type={showPassword ? 'text' : 'password'} name='password' required
|
||||
value={formData.password} onChange={handleChange} />
|
||||
<input className='mt-2' type="checkbox" onClick={() => setShowPassword(!showPassword)} /> Показать пароль
|
||||
</Form.Group>
|
||||
<Button className="w-100 fw-bold mt-3" variant='primary' type='submit'>Войти</Button>
|
||||
{wrongLoginInfoWarning}
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
LoginForm.propTypes = {
|
||||
setNeedsRegistration: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LoginForm;
|
51
Lab5/src/components/login/LoginFormNew.jsx
Normal file
@ -0,0 +1,51 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import { useState } from 'react';
|
||||
import useLoginForm from './LoginHook';
|
||||
|
||||
const LoginFormNew = ({ setNeedsRegistration }) => {
|
||||
const {
|
||||
formData,
|
||||
validated,
|
||||
correctLoginInfo,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useLoginForm();
|
||||
let wrongLoginInfoWarning;
|
||||
if (!correctLoginInfo) wrongLoginInfoWarning = (<p className='text-danger text-center mt-3'>Неверные Email или пароль</p>);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form className="p-5 rounded login-form" noValidate validated={validated} onSubmit={handleSubmit}>
|
||||
<p className="text-center mb-4">
|
||||
Только для зарегистрированных пользователей
|
||||
<br />
|
||||
Нет аккаунта?{' '}
|
||||
<Link to='#' className="link-info" onClick={() => setNeedsRegistration(true)}>
|
||||
Зарегистрироваться
|
||||
</Link>
|
||||
</p>
|
||||
<Form.Group className='mb-2 fw-bold' controlId='email'>
|
||||
<Form.Label>E-mail</Form.Label>
|
||||
<Form.Control type='email' name='email' required
|
||||
value={formData.email} onChange={handleChange} />
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2 position-relative" controlId='password'>
|
||||
<Form.Label className="fw-bold">Пароль</Form.Label>
|
||||
<Form.Control type={showPassword ? 'text' : 'password'} name='password' required
|
||||
value={formData.password} onChange={handleChange} />
|
||||
<input className='mt-2' type="checkbox" onClick={() => setShowPassword(!showPassword)} /> Показать пароль
|
||||
</Form.Group>
|
||||
<Button className="w-100 fw-bold mt-3" variant='primary' type='submit'>Войти</Button>
|
||||
{wrongLoginInfoWarning}
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
LoginFormNew.propTypes = {
|
||||
setNeedsRegistration: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LoginFormNew;
|
58
Lab5/src/components/login/LoginHook.js
Normal file
@ -0,0 +1,58 @@
|
||||
import { useState, useContext } from 'react';
|
||||
import LoginContext from './LoginContext.jsx';
|
||||
import AccountsApiService from '../registration/AccountsApiService';
|
||||
|
||||
const useLoginForm = () => {
|
||||
const [validated, setValidated] = useState(false);
|
||||
const [correctLoginInfo, setCorrectLoginInfo] = useState(true);
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
password: '',
|
||||
});
|
||||
const { setLogin } = useContext(LoginContext);
|
||||
|
||||
const LOGIN_KEY = 'localLogin';
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (form.checkValidity() !== false) {
|
||||
const loggedInUser = (await AccountsApiService.getAll(`?email=${formData.email}`))[0];
|
||||
if (loggedInUser && loggedInUser.password === formData.password) {
|
||||
localStorage.setItem(LOGIN_KEY, JSON.stringify(loggedInUser));
|
||||
setLogin(loggedInUser);
|
||||
setCorrectLoginInfo(true);
|
||||
} else {
|
||||
setCorrectLoginInfo(false);
|
||||
}
|
||||
}
|
||||
setValidated(true);
|
||||
};
|
||||
|
||||
const logOut = () => {
|
||||
localStorage.removeItem(LOGIN_KEY);
|
||||
setValidated(false);
|
||||
setLogin(null);
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
setFormData({
|
||||
...formData,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
formData,
|
||||
validated,
|
||||
correctLoginInfo,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
logOut,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLoginForm;
|
33
Lab5/src/components/menu/Menu.jsx
Normal file
@ -0,0 +1,33 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import Food from './MenuFood.jsx';
|
||||
import useLines from '../lines/hooks/LinesHook';
|
||||
|
||||
const Menu = ({ id }) => {
|
||||
const { lines } = useLines(id);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="container-fluid mx-0 min-vh-100">
|
||||
<div className="row">
|
||||
{lines.map((line) => (
|
||||
<Food
|
||||
key={line.id}
|
||||
description={{
|
||||
img: line.image,
|
||||
food: line.food,
|
||||
price: `${parseInt(line.price, 10)} ₽`,
|
||||
destination: `/PageItem/${line.id}`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Menu.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Menu;
|
23
Lab5/src/components/menu/MenuFood.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Link } from 'react-router-dom';
|
||||
import imgPlaceholder from '../../assets/200.png';
|
||||
|
||||
const MenuFood = ({ description }) => {
|
||||
return (
|
||||
<>
|
||||
<div className='col-3 m-2 bg-white rounded-5'>
|
||||
<Link className='mb-3 d-flex justify-content-center' to={description.destination}>
|
||||
<img src={description.img || imgPlaceholder} width="120" height="220" />
|
||||
</Link>
|
||||
<p className="mb-3 text-center">{description.food || ''}</p>
|
||||
<p className="mb-3 text-center">{description.price || ''}</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
MenuFood.propTypes = {
|
||||
description: PropTypes.object,
|
||||
};
|
||||
|
||||
export default MenuFood;
|
3
Lab5/src/components/modal/Modal.css
Normal file
@ -0,0 +1,3 @@
|
||||
.modal-title {
|
||||
font-size: 1.2rem;
|
||||
}
|
42
Lab5/src/components/modal/ModalConfirm.jsx
Normal file
@ -0,0 +1,42 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Modal } from 'react-bootstrap';
|
||||
import { createPortal } from 'react-dom';
|
||||
import './Modal.css';
|
||||
|
||||
const ModalConfirm = ({
|
||||
show, title, message, onConfirm, onClose,
|
||||
}) => {
|
||||
return createPortal(
|
||||
<Modal show={show} backdrop='static' onHide={() => onClose()}>
|
||||
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
|
||||
<Modal.Title>{title}</Modal.Title>
|
||||
</Modal.Header>
|
||||
|
||||
<Modal.Body>
|
||||
{message}
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
|
||||
<Button variant='secondary' className='col-5 m-0 me-2'
|
||||
onClick={() => onClose()}>
|
||||
Нет
|
||||
</Button>
|
||||
<Button variant='primary' className='col-5 m-0 ms-2'
|
||||
onClick={() => onConfirm()}>
|
||||
Да
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Modal>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
|
||||
ModalConfirm.propTypes = {
|
||||
show: PropTypes.bool,
|
||||
title: PropTypes.string,
|
||||
message: PropTypes.string,
|
||||
onConfirm: PropTypes.func,
|
||||
onClose: PropTypes.func,
|
||||
};
|
||||
|
||||
export default ModalConfirm;
|
43
Lab5/src/components/modal/ModalForm.jsx
Normal file
@ -0,0 +1,43 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Form, Modal } from 'react-bootstrap';
|
||||
import { createPortal } from 'react-dom';
|
||||
import './Modal.css';
|
||||
|
||||
const ModalForm = ({
|
||||
show, title, validated, onSubmit, onClose, children,
|
||||
}) => {
|
||||
return createPortal(
|
||||
<Modal show={show} backdrop='static' onHide={() => onClose()}>
|
||||
<Modal.Header className='pt-2 pb-2 ps-3 pe-3' closeButton>
|
||||
<Modal.Title>{title}</Modal.Title>
|
||||
</Modal.Header>
|
||||
<Form className='m-0' noValidate validated={validated} onSubmit={onSubmit}>
|
||||
<Modal.Body>
|
||||
{children}
|
||||
</Modal.Body>
|
||||
|
||||
<Modal.Footer className='m-0 pt-2 pb-2 ps-3 pe-3 row justify-content-center'>
|
||||
<Button variant='secondary' className='col-5 m-0 me-2'
|
||||
onClick={() => onClose()}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button variant='primary' className='col-5 m-0 ms-2' type='submit'>
|
||||
Сохранить
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
</Form>
|
||||
</Modal>,
|
||||
document.body,
|
||||
);
|
||||
};
|
||||
|
||||
ModalForm.propTypes = {
|
||||
show: PropTypes.bool,
|
||||
title: PropTypes.string,
|
||||
validated: PropTypes.bool,
|
||||
onSubmit: PropTypes.func,
|
||||
onClose: PropTypes.func,
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default ModalForm;
|
21
Lab5/src/components/modal/ModalHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
const useModal = () => {
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
const showModalDialog = () => {
|
||||
setShowModal(true);
|
||||
};
|
||||
|
||||
const hideModalDialog = () => {
|
||||
setShowModal(false);
|
||||
};
|
||||
|
||||
return {
|
||||
isModalShow: showModal,
|
||||
showModal: showModalDialog,
|
||||
hideModal: hideModalDialog,
|
||||
};
|
||||
};
|
||||
|
||||
export default useModal;
|
12
Lab5/src/components/navigation/Navigation.css
Normal file
@ -0,0 +1,12 @@
|
||||
.my-navbar {
|
||||
background-color: #161010 !important;
|
||||
}
|
||||
|
||||
.my-navbar .link a:hover {
|
||||
text-decoration: underline !important;
|
||||
}
|
||||
|
||||
.my-navbar .logo {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
49
Lab5/src/components/navigation/Navigation.jsx
Normal file
@ -0,0 +1,49 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Container, Nav, Navbar } from 'react-bootstrap';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { Cart2 } from 'react-bootstrap-icons';
|
||||
import useCart from '../cart/CartHook';
|
||||
import logo from '../../assets/logo.png';
|
||||
import './Navigation.css';
|
||||
|
||||
const Navigation = ({ routes }) => {
|
||||
const { getCartSum } = useCart();
|
||||
const location = useLocation();
|
||||
const indexPageLink = routes.filter((route) => route.index === false).shift();
|
||||
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
|
||||
|
||||
return (
|
||||
<header>
|
||||
<Navbar expand='md' bg='dark' data-bs-theme='dark' className='my-navbar'>
|
||||
<Container fluid>
|
||||
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
|
||||
<img src={logo} className='d-inline-block align-top mx-2 logo' />
|
||||
FastFood
|
||||
</Navbar.Brand>
|
||||
<Navbar.Toggle aria-controls='main-navbar' />
|
||||
<Navbar.Collapse id='main-navbar'>
|
||||
<Nav className='me-auto link' activeKey={location.pathname}>
|
||||
{
|
||||
pages.map((page) =>
|
||||
<Nav.Link as={Link} key={page.path} eventKey={page.path} to={page.path ?? '/'}>
|
||||
{page.title}
|
||||
</Nav.Link>)
|
||||
}
|
||||
</Nav>
|
||||
<Nav>
|
||||
<Navbar.Brand as={Link} to='/CartPage'>
|
||||
<Cart2 className='d-inline-block align-top me-1 logo' /> {getCartSum() ?? ''} ₽
|
||||
</Navbar.Brand>
|
||||
</Nav>
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
</Navbar >
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
||||
Navigation.propTypes = {
|
||||
routes: PropTypes.array,
|
||||
};
|
||||
|
||||
export default Navigation;
|
5
Lab5/src/components/registration/AccountsApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../api/ApiService';
|
||||
|
||||
const AccountsApiService = new ApiService('accounts');
|
||||
|
||||
export default AccountsApiService;
|
53
Lab5/src/components/registration/RegistrationForm.jsx
Normal file
@ -0,0 +1,53 @@
|
||||
import { Button, Form } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
import { useState } from 'react';
|
||||
import useRegistrationForm from './RegistrationHook';
|
||||
|
||||
const RegistrationForm = () => {
|
||||
const {
|
||||
formData,
|
||||
validated,
|
||||
accountAlreadyExists,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
} = useRegistrationForm();
|
||||
let accountAlreadyExistsWarning;
|
||||
if (accountAlreadyExists) accountAlreadyExistsWarning = (<p className='text-danger text-center mt-3'>Данный Email уже зарегистрирован</p>);
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form className="p-5 rounded registration-form" noValidate validated={validated} onSubmit={handleSubmit}>
|
||||
<Form.Group className="mb-2" controlId='surname'>
|
||||
<Form.Label className="fw-bold">Фамилия</Form.Label>
|
||||
<Form.Control type='text' name='surname' required
|
||||
value={formData.login} onChange={handleChange} />
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId='name'>
|
||||
<Form.Label className="fw-bold">Имя</Form.Label>
|
||||
<Form.Control type='text' name='name' required
|
||||
value={formData.login} onChange={handleChange} />
|
||||
</Form.Group>
|
||||
<Form.Group className='mb-2 fw-bold' controlId='email'>
|
||||
<Form.Label>E-mail</Form.Label>
|
||||
<Form.Control type='email' name='email' required
|
||||
value={formData.email} onChange={handleChange} />
|
||||
</Form.Group>
|
||||
<Form.Group className="mb-2" controlId='password'>
|
||||
<Form.Label className="fw-bold">Пароль</Form.Label>
|
||||
<Form.Control type={showPassword ? 'text' : 'password'} name='password' required
|
||||
value={formData.password} onChange={handleChange} />
|
||||
<input className='mt-2' type="checkbox" onClick={() => setShowPassword(!showPassword)} /> Показать пароль
|
||||
</Form.Group>
|
||||
<Button className="w-100 fw-bold mt-3" variant='primary' type='submit'>Зарегистрироваться</Button>
|
||||
{accountAlreadyExistsWarning}
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
RegistrationForm.propTypes = {
|
||||
setNeedsRegistration: PropTypes.func,
|
||||
};
|
||||
|
||||
export default RegistrationForm;
|
50
Lab5/src/components/registration/RegistrationHook.js
Normal file
@ -0,0 +1,50 @@
|
||||
import { useState, useContext } from 'react';
|
||||
import AccountsApiService from './AccountsApiService';
|
||||
import LoginContext from '../login/LoginContext.jsx';
|
||||
|
||||
const useRegistrationForm = () => {
|
||||
const [validated, setValidated] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
surname: '',
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
});
|
||||
const { setLogin } = useContext(LoginContext);
|
||||
const [accountAlreadyExists, setAccountAlreadyExists] = useState(false);
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
const form = event.currentTarget;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (form.checkValidity() !== false) {
|
||||
if (!(await AccountsApiService.getAll(`?email=${formData.email}`))[0]) {
|
||||
const newUser = await AccountsApiService.create(formData);
|
||||
localStorage.setItem('localLogin', JSON.stringify(newUser));
|
||||
setLogin(newUser);
|
||||
} else {
|
||||
setAccountAlreadyExists(true);
|
||||
}
|
||||
}
|
||||
setValidated(true);
|
||||
};
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputName = event.target.name;
|
||||
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
|
||||
setFormData({
|
||||
...formData,
|
||||
[inputName]: inputValue,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
formData,
|
||||
validated,
|
||||
accountAlreadyExists,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useRegistrationForm;
|
21
Lab5/src/components/types/hooks/TypesHook.js
Normal file
@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import TypesApiService from '../service/TypesApiService';
|
||||
|
||||
const useTypes = () => {
|
||||
const [types, setTypes] = useState([]);
|
||||
|
||||
const getTypes = async () => {
|
||||
const data = await TypesApiService.getAll();
|
||||
setTypes(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getTypes();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
types,
|
||||
};
|
||||
};
|
||||
|
||||
export default useTypes;
|
5
Lab5/src/components/types/service/TypesApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const TypesApiService = new ApiService('types');
|
||||
|
||||
export default TypesApiService;
|
34
Lab5/src/components/users/hooks/UserHook.js
Normal file
@ -0,0 +1,34 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import UsersApiService from '../service/UsersApiService';
|
||||
|
||||
const useUser = (id) => {
|
||||
const emptyUser = {
|
||||
id: '',
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
isAdmin: false,
|
||||
};
|
||||
const [user, setUser] = useState({ ...emptyUser });
|
||||
|
||||
const getUser = async (userId = undefined) => {
|
||||
if (userId && userId > 0) {
|
||||
const data = await UsersApiService.get(userId);
|
||||
setUser(data);
|
||||
} else {
|
||||
setUser({ ...emptyUser });
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getUser(id);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [id]);
|
||||
|
||||
return {
|
||||
user,
|
||||
setUser,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUser;
|
24
Lab5/src/components/users/hooks/UsersHook.js
Normal file
@ -0,0 +1,24 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import UsersApiService from '../service/UsersApiService';
|
||||
|
||||
const useUsers = () => {
|
||||
const [usersRefresh, setUsersRefresh] = useState(false);
|
||||
const [users, setUsers] = useState([]);
|
||||
const handleUsersChange = () => setUsersRefresh(!usersRefresh);
|
||||
|
||||
const getUsers = async () => {
|
||||
const data = await UsersApiService.getAll();
|
||||
setUsers(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getUsers();
|
||||
}, [usersRefresh]);
|
||||
|
||||
return {
|
||||
users,
|
||||
handleUsersChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useUsers;
|
5
Lab5/src/components/users/service/UsersApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const UsersApiService = new ApiService('users');
|
||||
|
||||
export default UsersApiService;
|
15
Lab5/src/components/utils/Base64.js
Normal file
@ -0,0 +1,15 @@
|
||||
const getBase64FromFile = async (file) => {
|
||||
const reader = new FileReader();
|
||||
return new Promise((resolve, reject) => {
|
||||
reader.onloadend = () => {
|
||||
const fileContent = reader.result;
|
||||
resolve(fileContent);
|
||||
};
|
||||
reader.onerror = () => {
|
||||
reject(new Error('Oops, something went wrong with the file reader.'));
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
};
|
||||
|
||||
export default getBase64FromFile;
|
27
Lab5/src/index.css
Normal file
@ -0,0 +1,27 @@
|
||||
h1 {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.25em;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.1em;
|
||||
}
|
||||
|
||||
.btn-mw {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.btn-mw {
|
||||
width: 30%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1200px) {
|
||||
.btn-mw {
|
||||
width: 20%;
|
||||
}
|
||||
}
|
84
Lab5/src/main.jsx
Normal file
@ -0,0 +1,84 @@
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
|
||||
import App from './App.jsx';
|
||||
import './index.css';
|
||||
import '../style.css';
|
||||
import ErrorPage from './pages/ErrorPage.jsx';
|
||||
import AboutUs from './pages/About-us.jsx';
|
||||
import Home from './pages/Home.jsx';
|
||||
import Contacts from './pages/Contacts.jsx';
|
||||
import PageMenu from './pages/PageMenu.jsx';
|
||||
import PageEdit from './pages/PageEdit.jsx';
|
||||
import PageAdmin from './pages/PageAdmin.jsx';
|
||||
import PageItem from './pages/PageItem.jsx';
|
||||
import CartPage from './pages/CartPage.jsx';
|
||||
import PageRegistration from './pages/PageRegistration.jsx';
|
||||
import PageLogin from './pages/PageLogin.jsx';
|
||||
|
||||
const routes = [
|
||||
{
|
||||
index: true,
|
||||
path: '/',
|
||||
element: <Home />,
|
||||
title: 'Главная страница',
|
||||
},
|
||||
{
|
||||
path: '/About-us',
|
||||
element: <AboutUs />,
|
||||
title: 'О нас',
|
||||
},
|
||||
{
|
||||
path: '/Contacts',
|
||||
element: <Contacts />,
|
||||
title: 'Наши контакты',
|
||||
},
|
||||
{
|
||||
path: '/PageRegistration',
|
||||
element: <PageRegistration />,
|
||||
title: 'Регистрация',
|
||||
},
|
||||
{
|
||||
path: '/PageLogin',
|
||||
element: <PageLogin />,
|
||||
title: 'Авторизация',
|
||||
},
|
||||
{
|
||||
path: '/PageMenu',
|
||||
element: <PageMenu />,
|
||||
title: 'Меню',
|
||||
},
|
||||
{
|
||||
path: '/PageAdmin',
|
||||
element: <PageAdmin />,
|
||||
title: 'Страница админа',
|
||||
},
|
||||
{
|
||||
path: '/PageEdit/:id?',
|
||||
element: <PageEdit />,
|
||||
},
|
||||
{
|
||||
path: '/PageItem/:id',
|
||||
element: <PageItem />,
|
||||
},
|
||||
{
|
||||
path: '/CartPage',
|
||||
element: <CartPage />,
|
||||
},
|
||||
];
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
path: '/',
|
||||
element: <App routes={routes} />,
|
||||
children: routes,
|
||||
errorElement: <ErrorPage />,
|
||||
},
|
||||
]);
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
</React.StrictMode>,
|
||||
);
|
32
Lab5/src/pages/About-us.jsx
Normal file
@ -0,0 +1,32 @@
|
||||
import man from '../assets/Man1.png';
|
||||
|
||||
const AboutUs = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="allAboutUs d-flex flex-fill align-items-center justify-content-center min-vh-100">
|
||||
<div className="bg-white rounded-5 p-5">
|
||||
<h1 className="text-center">О нас</h1>
|
||||
<div className="d-flex flex-column flex-md-row justify-content-evenly align-items-center">
|
||||
<p className="text-center">
|
||||
С самого детства мы
|
||||
<br />
|
||||
хотели открыть
|
||||
<br />
|
||||
ресторан и шли к нашей
|
||||
<br />
|
||||
мечте. На пути было
|
||||
<br />
|
||||
много трудностей но
|
||||
<br />
|
||||
мы справились
|
||||
<br />с каждой
|
||||
</p>
|
||||
<img className="w-50 h-50" src={man} alt="" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default AboutUs;
|
87
Lab5/src/pages/Admin.html
Normal file
@ -0,0 +1,87 @@
|
||||
<html lang="ru">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Моя страница</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<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" />
|
||||
<link href="./node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet" />
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
|
||||
<body class="h-100 d-flex flex-column">
|
||||
<header>
|
||||
<nav class = "navbar navbar-expand-lg navbar-dark bg-dark">
|
||||
<div class="container-fluid">
|
||||
<a href="Admin.html" class="nav-item"><img class="logo w-50 h-50" src="images/logo.png"></a>
|
||||
<a href="index.html" class="navbar-brand">Fastest Food</a>
|
||||
<button class = "navbar-toggler" type = "button" data-bs-toggle = "collapse" data-bs-target = "#navbarContent"
|
||||
aria-controls="navbarContent" aria-expanded="false">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="collapse navbar-collapse" id="navbarContent">
|
||||
<ul class="navbar-nav me-auto mb-auto">
|
||||
<li class="nav-item">
|
||||
<a href="login.html" class="nav-link">Войти/Регистрация</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="about-us.html" class="nav-link">О нас</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="menu.html" class="nav-link">Меню</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="contacts.html" class="nav-link">Наши контакты</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="container-fluid p-2 min-vh-100">
|
||||
<div class="d-flex flex-column align-items-center">
|
||||
<h1 class="my-3">
|
||||
Панель управления
|
||||
</h1>
|
||||
<table id="items-table" class="table table-striped">
|
||||
<thead>
|
||||
<th scope="col">№</th>
|
||||
<th scope="col" class="w-25">Товар</th>
|
||||
<th scope="col" class="w-25">Название товара</th>
|
||||
<th scope="col" class="w-25">Дата появления</th>
|
||||
<th scope="col" class="w-25">Цена</th>
|
||||
<th scope="col" class="w-25">Количество</th>
|
||||
<th scope="col" class="w-25">Сумма</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<a class="btn btn-success" href="/page-edit.html">Добавить товар</a>
|
||||
</div>
|
||||
</main>
|
||||
<footer>
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col d-flex align-items-center">
|
||||
<h2>Fastest Food</h2>
|
||||
</div>
|
||||
<div class="col">
|
||||
<p class="time">Время работы:<br>ПН-ПТ:10-19<br>СБ-ВС:12-17</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
<script type="module">
|
||||
import validation from "./js/validation";
|
||||
import { linesPageForm } from "./js/lines";
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
validation();
|
||||
linesPageForm();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
9
Lab5/src/pages/CartPage.jsx
Normal file
@ -0,0 +1,9 @@
|
||||
import Cart from '../components/cart/Cart.jsx';
|
||||
|
||||
const CartPage = () => {
|
||||
return (
|
||||
<Cart />
|
||||
);
|
||||
};
|
||||
|
||||
export default CartPage;
|
29
Lab5/src/pages/Contacts.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
const Contacts = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="allOurContacts d-flex flex-fill align-items-center justify-content-center min-vh-100">
|
||||
<div className="bg-white rounded-5 p-5">
|
||||
<h1 className="text-center mb-5">Наши контакты</h1>
|
||||
<div className="justify-content-evenly align-items-center">
|
||||
<div className="row">
|
||||
<div className="col text-center">Адресс</div>
|
||||
<div className="col text-center">Телефон</div>
|
||||
<div className="col text-center">Соцсети</div>
|
||||
</div>
|
||||
<div className="row mt-3">
|
||||
<div className="col text-center">Ул. Врача михайлова 65</div>
|
||||
<div className="col text-center">+79439419513</div>
|
||||
<div className="col text-center">
|
||||
ВК: Fastest Food
|
||||
<br />
|
||||
ТГ: Fastest Food
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Contacts;
|
19
Lab5/src/pages/ErrorPage.jsx
Normal file
@ -0,0 +1,19 @@
|
||||
import { Alert, Button, Container } from 'react-bootstrap';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
const ErrorPage = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<Container fluid className="p-2 row justify-content-center">
|
||||
<Container className='col-md-6'>
|
||||
<Alert variant="danger">
|
||||
Страница не найдена
|
||||
</Alert>
|
||||
<Button className="w-25 mt-2" variant="primary" onClick={() => navigate(-1)}>Назад</Button>
|
||||
</Container>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default ErrorPage;
|
29
Lab5/src/pages/Home.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import shaurma from '../assets/Shaurma.png';
|
||||
|
||||
const Home = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="row d-flex align-content-center flex-fill mx-0 min-vh-100">
|
||||
<div className="col-lg-6 col-sm-12 d-flex align-items-center justify-content-center">
|
||||
<div className="offer p-5 rounded-5 d-flex flex-column justify-content-center">
|
||||
<p className="text-center font-size">
|
||||
НОВИНКУ!!!
|
||||
<br />
|
||||
за 240 рублей
|
||||
<br />
|
||||
куриная шаурма
|
||||
</p>
|
||||
<button type="button" className="btn btn-danger rounded-pill">
|
||||
Купить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-lg-6 col-sm-12 d-flex align-content-center justify-content-center py-4">
|
||||
<img className="im w-100" src={shaurma} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Home;
|
28
Lab5/src/pages/Meal.jsx
Normal file
@ -0,0 +1,28 @@
|
||||
import shaurma from '../assets/Shaurma.png';
|
||||
|
||||
const Meal = () => {
|
||||
return (
|
||||
<>
|
||||
<div className="allAboutUs d-flex flex-fill align-items-center justify-content-center min-vh-100">
|
||||
<div className="bg-white rounded-5 p-5">
|
||||
<h1 className="text-center">Шаурма</h1>
|
||||
<div className="d-flex flex-column flex-md-row justify-content-evenly align-items-center">
|
||||
<p className="text-center">
|
||||
Вкуснейшая шаурма сделанная из специально выращенной курицы, овощей,
|
||||
<br />
|
||||
сбираемых на плантации специально для нашей компании
|
||||
</p>
|
||||
<img className="w-50 h-50" src={shaurma} />
|
||||
</div>
|
||||
<div className="d-flex justify-content-center">
|
||||
<a href="basket.html" className="btn btn-danger">
|
||||
Добавить в корзину
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Meal;
|
11
Lab5/src/pages/PageAdmin.jsx
Normal file
@ -0,0 +1,11 @@
|
||||
import Lines from '../components/lines/table/Lines.jsx';
|
||||
|
||||
const PageAdmin = () => {
|
||||
return (
|
||||
<>
|
||||
<Lines />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageAdmin;
|
12
Lab5/src/pages/PageEdit.jsx
Normal file
@ -0,0 +1,12 @@
|
||||
import { useParams } from 'react-router-dom';
|
||||
import LinesForm from '../components/lines/form/LinesForm.jsx';
|
||||
|
||||
const PageEdit = () => {
|
||||
const { id } = useParams();
|
||||
|
||||
return (
|
||||
<LinesForm id={id} />
|
||||
);
|
||||
};
|
||||
|
||||
export default PageEdit;
|
14
Lab5/src/pages/PageItem.jsx
Normal file
@ -0,0 +1,14 @@
|
||||
import { useParams } from 'react-router-dom';
|
||||
import Item from '../components/item/Item.jsx';
|
||||
|
||||
const PageItem = () => {
|
||||
const { id } = useParams();
|
||||
|
||||
return (
|
||||
<>
|
||||
<Item id={id} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageItem;
|
23
Lab5/src/pages/PageLogin.jsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { useContext } from 'react';
|
||||
import LoginForm from '../components/login/LoginFormNew.jsx';
|
||||
import LoginContext from '../components/login/LoginContext.jsx';
|
||||
|
||||
const PageLogin = () => {
|
||||
const { login } = useContext(LoginContext);
|
||||
console.log(login);
|
||||
|
||||
if (!login) {
|
||||
return (
|
||||
<>
|
||||
<LoginForm />
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<p className='text-center fs-1 min-vh-100'>Добро пожаловать, {login.name}</p>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageLogin;
|
13
Lab5/src/pages/PageMenu.jsx
Normal file
@ -0,0 +1,13 @@
|
||||
import { useParams } from 'react-router-dom';
|
||||
import Menu from '../components/menu/Menu.jsx';
|
||||
|
||||
const PageMenu = () => {
|
||||
const { id } = useParams();
|
||||
return (
|
||||
<>
|
||||
<Menu id={id} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageMenu;
|
11
Lab5/src/pages/PageRegistration.jsx
Normal file
@ -0,0 +1,11 @@
|
||||
import RegistrationForm from '../components/registration/RegistrationForm.jsx';
|
||||
|
||||
const PageRegistration = () => {
|
||||
return (
|
||||
<>
|
||||
<RegistrationForm />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageRegistration;
|
50
Lab5/style.css
Normal file
@ -0,0 +1,50 @@
|
||||
main{
|
||||
background-color: bisque;
|
||||
}
|
||||
.offer{
|
||||
background-color: #ffffff;
|
||||
}
|
||||
.time{
|
||||
font-size: 14px;
|
||||
}
|
||||
p{
|
||||
font-size: 16px;
|
||||
font-family: Inter;
|
||||
}
|
||||
.allRegistration{
|
||||
background-image: url("/BakcgroundRegistration.png");
|
||||
background-size: cover;
|
||||
}
|
||||
.allAboutUs{
|
||||
background-image: url("/BackgroundAboutUs.png");
|
||||
background-size: cover;
|
||||
}
|
||||
.allOurContacts{
|
||||
background-image: url("/BackgroundOurContacts.png");
|
||||
background-size: cover;
|
||||
}
|
||||
@media (max-width: 768px){
|
||||
.allAboutUs{
|
||||
background-image: none;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
.allOurContacts{
|
||||
background-image: none;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
.allRegistration{
|
||||
background-image: none;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
.allAdmin{
|
||||
background-image: none;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
}
|
||||
.Menu{
|
||||
width: 250px;
|
||||
height: 220px;
|
||||
}
|
||||
#image-preview{
|
||||
width: 200px;
|
||||
}
|
13
Lab5/vite.config.js
Normal file
@ -0,0 +1,13 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
sourcemap: true,
|
||||
chunkSizeWarningLimit: 1024,
|
||||
emptyOutDir: true,
|
||||
},
|
||||
});
|