This commit is contained in:
Extrimal 2024-01-10 17:27:29 +03:00
parent 6885a66528
commit a775d2c182
97 changed files with 9494 additions and 0 deletions

24
laba5/.eslintrc.cjs Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', 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
laba5/.gitignore vendored Normal file
View 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?

8
laba5/README.md Normal file
View File

@ -0,0 +1,8 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

163
laba5/data.json Normal file

File diff suppressed because one or more lines are too long

13
laba5/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Book Shop</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
laba5/jsconfig.json Normal file
View 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
laba5/json-server.json Normal file
View File

@ -0,0 +1,5 @@
{
"static": "./node_modules/json-server/public",
"port": 8081,
"watch": "true"
}

5953
laba5/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
laba5/package.json Normal file
View File

@ -0,0 +1,38 @@
{
"name": "lec4",
"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"
}
}

1
laba5/public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

31
laba5/src/App.jsx Normal file
View File

@ -0,0 +1,31 @@
import PropTypes from 'prop-types';
import { Container } from 'react-bootstrap';
import { Outlet } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
import { IdProvider } from './components/users/context_hooks/AuthorizationContext.jsx';
import { CartProvider } from './components/cart/CartContext.jsx';
import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx';
const App = ({ routes }) => {
return (
<>
<CartProvider>
<IdProvider>
<Navigation routes={routes}></Navigation>
<Container className='p-2' as="main" fluid>
<Outlet />
</Container>
<Footer />
<Toaster position='top-center' reverseOrder={true} />
</IdProvider>
</CartProvider>
</>
);
};
App.propTypes = {
routes: PropTypes.array,
};
export default App;

BIN
laba5/src/assets/200.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 875 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 814 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
laba5/src/assets/Image1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 812 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 767 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 309 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 18 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 26 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 22 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

View File

@ -0,0 +1,3 @@
<svg width="1" height="30" viewBox="0 0 1 30" fill="none" xmlns="http://www.w3.org/2000/svg">
<line x1="0.5" y1="30" x2="0.5" stroke="black"/>
</svg>

After

Width:  |  Height:  |  Size: 150 B

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg width="800px" height="800px" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">
<title>menu-hamburger</title>
<g id="Layer_2" data-name="Layer 2">
<g id="invisible_box" data-name="invisible box">
<rect width="48" height="48" fill="none"/>
</g>
<g id="icons_Q2" data-name="icons Q2">
<g>
<path d="M42,12a2,2,0,0,1-2,2H8a2,2,0,0,1-2-2H6a2,2,0,0,1,2-2H40a2,2,0,0,1,2,2Z"/>
<path d="M42,24a2,2,0,0,1-2,2H8a2,2,0,0,1-2-2H6a2,2,0,0,1,2-2H40a2,2,0,0,1,2,2Z"/>
<path d="M42,36a2,2,0,0,1-2,2H8a2,2,0,0,1-2-2H6a2,2,0,0,1,2-2H40a2,2,0,0,1,2,2Z"/>
</g>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 750 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View 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);

View 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;

View File

@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';
import AuthorsApiService from '../service/AuthorsApiService';
const useAuthors = () => {
const [authors, setAuthors] = useState([]);
const getAuthors = async () => {
const data = await AuthorsApiService.getAll();
setAuthors(data ?? []);
};
useEffect(() => {
getAuthors();
}, []);
return {
authors,
};
};
export default useAuthors;

View File

@ -0,0 +1,5 @@
import ApiService from '../../api/ApiService';
const AuthorsApiService = new ApiService('authors');
export default AuthorsApiService;

View File

@ -0,0 +1,30 @@
import DopImage from '../../assets/PngInSite.png';
import PropTypes from 'prop-types';
// eslint-disable-next-line react/prop-types
function ProductCard({ image, price, name, authors, types, onAddCart}) {
if (!image) {
image = DopImage;
}
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<div className="Conteiner_Films">
<img src={image} className="Img_Films"/>
<p className="word_Prince_book">{price} $</p>
<p className="word_Name_book">{name}</p>
<p className="word_Author_book">{authors}</p>
<p className="word_Genres_book">Genres: {types}</p>
<div className="block2_button">
<button className="button_InBusket_book" onClick={(event) => handleAnchorClick(event, onAddCart)}>
In a basket
</button>
</div>
</div>
);
}
ProductCard.propTypes = {
onAddCart: PropTypes.func,
};
export default ProductCard;

View File

@ -0,0 +1,8 @@
.cart-image {
width: 3.1rem;
padding: .25rem;
}
.cart-item {
height: auto;
}

View File

@ -0,0 +1,142 @@
import imgPlaceholder from '../../assets/PngInSite.png';
import './Cart.css';
import useCart from './CartHook';
import { Link } from 'react-router-dom';
import { Modal } from 'react-bootstrap';
import { useState } from 'react';
import useUserObject from '../users/hooks/UserObjectHook';
const Cart = () => {
const id = parseInt(localStorage.getItem('userId'), 10);
const { user } = useUserObject(id);
const {
cart,
getCartSum,
addToCart,
removeFromCart,
removeFromCartAll,
clearCart,
} = useCart();
const [showModal, setShowModal] = useState(false);
const handleArrangeClick = () => {
// Дополнительные действия, если необходимо
// Например, отправка заказа на сервер, обновление состояния и т.д.
// Показываем модальное окно
setShowModal(true);
};
const handleCloseModal = () => {
// Закрываем модальное окно
clearCart();
setShowModal(false);
};
return (
<>
<div className="main_Basket">
<div className="container">
<div className="main_wrapper_Basket">
<div className="main_block1_Basket">
<h1 className="Word_Basket">
Basket
</h1>
<div className="line_Basket"></div>
<Link className = "Word_DeleteAll" onClick={() => clearCart()}>
Delete all
</Link >
</div>
<div className="Block_Two_Three">
<div className="Shell">
{
cart.map((cartItem) =>
<>
<div className="line_black" key={cartItem.id}></div>
<div className="main_block2_Basket">
<img src={cartItem.image || imgPlaceholder} className="Img_Films_Basket"/>
<div className="Options_In_Films">
<p className="word_Dracula">{cartItem.name}</p>
<p className="word_Author">{cartItem.authors.name}</p>
<p className="word_Ganres_Basket">Genres: {cartItem.types.name}</p>
<a href = "#" className = "word_Delete_Basket" onClick={() => removeFromCartAll(cartItem)}>
Delete
</a>
</div>
<div className="Button_add_In_Basket">
<button className="Circle_Left" onClick={() => removeFromCart(cartItem)}>-</button>
<div className="main_field_one">
<input type="text" className="text_Count" placeholder={cartItem.count}/>
</div>
<button className="Circle_Right" onClick={() => addToCart(cartItem)}>+</button>
</div>
<p className="Word_Dollars">{parseFloat(cartItem.price * cartItem.count)} $</p>
</div>
</>
)
}
</div>
<div className="main_block3">
<div className="wrapper_block3">
<p className="Word_with_Registr">
{(user.role === 'user' || user.role === 'admin') ? (
<>
Thank you for registering on our website, now you can easily use your shopping cart to make a purchase
</>
) : (
<>
<Link to="/SignIn" className = "word_registr">Log in </Link>
on the site and buy all the books in stock
</>
)}
</p>
<div className="All_price">
<p className="Text_Left_All_price">Total order amount</p>
<p className="Price">{getCartSum()} $</p>
</div>
<div className="class_Arrange">
<button className="button_Arrange" onClick={handleArrangeClick}>
Arrange
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<Modal show={showModal} onHide={handleCloseModal}>
<Modal.Body>
{(user.role === 'user' || user.role === 'admin') ? (
<>
<Modal.Header closeButton>
<Modal.Title>The purchase has been completed successfully!</Modal.Title>
</Modal.Header>
Thank you for your order! We are glad that you chose our books.
</>
) : (
<>
<Modal.Header closeButton>
<Modal.Title>The order was rejected!</Modal.Title>
</Modal.Header>
Please, <Link to="/SignIn">log in</Link> to your account to make a purchase.
</>
)}
</Modal.Body>
<Modal.Footer>
<button className="button_Arrange" onClick={handleCloseModal}>
Close
</button>
</Modal.Footer>
</Modal>
</>
);
};
export default Cart;

View 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;

View File

@ -0,0 +1,27 @@
import { useContext } from 'react';
import CartContext from './CartContext.jsx';
import { cartAdd, cartClear, cartRemove, cartRemoveAll } 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)),
removeFromCartAll: (item) => dispatch(cartRemoveAll(item)),
clearCart: () => dispatch(cartClear()),
};
};
export default useCart;

View File

@ -0,0 +1,82 @@
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 removeFromCartAll = (cart, item) =>{
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined && existsItem.count > 1) {
return cart.filter((cartItem) => cartItem.id !== item.id);
}
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';
const CART_REMOVE_ALL = 'cart/removeall'
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_REMOVE_ALL: {
return removeFromCartAll(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 cartRemoveAll = (item) => ({
type: CART_REMOVE_ALL, item,
});
export const cartClear = () => ({
type: CART_CLEAR,
});

View File

View File

@ -0,0 +1,42 @@
import InstogramLogo from '../../assets/iconInstogram.svg';
import TelegramLogo from '../../assets/iconTelegram.svg';
import VkLogo from '../../assets/iconVk.svg';
import WatsappLogo from '../../assets/iconWatsapp.svg';
import Line from '../../assets/line.svg';
import '../../index.css';
const Footer = () => {
return (
<footer className="footer">
<div className="container">
<div className = "footer_wrapper">
<nav>
<a href = "https://chat.whatsapp.com/KDJp7dnHzAWBQmT7PF3ZN3" className = "nav_foot">
<img src={WatsappLogo} alt=""/>
</a>
<a href = "https://vk.com/shanygin2000" className = "nav_foot">
<img src={VkLogo} alt=""/>
</a>
<a href = "https://instagram.com/sshanygin?igshid=NzZlODBkYWE4Ng==&utm_source=qr" className = "nav_foot">
<img src={InstogramLogo} alt=""/>
</a>
<a href="https://web.telegram.org/a/#1337526477" className="nav_foot">
<img src={TelegramLogo} alt=""/>
</a>
</nav>
<nav className="nav_mail_line_phone">
<a href = "#" className="mail_line_phone">
Book_shop@mail.com
</a>
<img src={Line} alt="" className="mail_line_phone" id ="line"/>
<a href = "#" className="mail_line_phone">
+7(999)-323-65-23
</a>
</nav>
</div>
</div>
</footer>
);
};
export default Footer;

View 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;

View 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;

View 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;

View File

@ -0,0 +1,3 @@
#image-preview {
width: 200px;
}

View File

@ -0,0 +1,37 @@
import PropTypes from 'prop-types';
import imgPlaceholder from '../../../assets/FirstPage.png';
import Input from '../../input/Input.jsx';
import Select from '../../input/Select.jsx';
import useTypes from '../../types/hooks/TypesHook';
import useAuthors from '../../authors/hooks/AuthorsHook';
import './LinesItemForm.css';
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
const { authors } = useAuthors();
return (
<>
<div className='text-center'>
<img id='image-preview' className='rounded' alt='placeholder'
src={item.image || imgPlaceholder} />
</div>
<Input name='name' label='Name' value={item.name} onChange={handleChange}
type='text' required />
<Input name='price' label='Price' value={item.price} onChange={handleChange}
type='number' min='100.0' step='0.50' required />
<Select values={types} name='typesId' label='Genre' value={item.typesId} onChange={handleChange}
required />
<Select values={authors} name='authorsId' label='Author' value={item.authorsId} onChange={handleChange}
required />
<Input name='image' label='image' onChange={handleChange}
type='file' accept='image/*' />
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

View 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;

View 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;

View 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;

View File

@ -0,0 +1,30 @@
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=authors&_expand=types';
if (typeFilter) {
expand = `${expand}&typesId=${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;

View File

@ -0,0 +1,81 @@
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 { name } = formData;
const price = parseFloat(formData.price).toFixed(2);
const typesId = parseInt(formData.typesId, 10);
const authorsId = parseInt(formData.authorsId, 10);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
name: name.toString(),
price: price.toString(),
typesId: typesId.toString(),
authorsId: authorsId.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;

View File

@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
name: '',
price: '0',
typesId: '',
authorsId: '',
image: '',
id: '',
};
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;

View File

@ -0,0 +1,5 @@
import ApiService from '../../api/ApiService';
const LinesApiService = new ApiService('lines');
export default LinesApiService;

View File

@ -0,0 +1,73 @@
import { Button, ButtonGroup } from 'react-bootstrap';
import useCart from '../../cart/CartHook';
import Select from '../../input/Select.jsx';
import ModalConfirm from '../../modal/ModalConfirm.jsx';
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 { addToCart } = useCart();
return (
<>
<div className='MainAdminFon'>
<ButtonGroup>
<Button variant='info' onClick={() => showFormModal()}>
Добавить товар (диалог)
</Button>
</ButtonGroup>
<Select className='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)}
/>)
}
</LinesTable>
<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;

View File

@ -0,0 +1,30 @@
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'>Name</th>
<th scope='col' className='w-25'>Price</th>
<th scope='col' className='w-25'>Genre</th>
<th scope='col' className='w-25'>Author</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;

View File

@ -0,0 +1,35 @@
import PropTypes from 'prop-types';
import { Cart, PencilFill, Trash3 }
from 'react-bootstrap-icons';
const LinesTableRow = ({
index, line, onAddCart, onDelete, onEdit,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.name}</td>
<td>{parseFloat(line.price).toFixed(2)}</td>
<td>{line.types.name}</td>
<td>{line.authors.name}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}><Cart/></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEdit)}><PencilFill /></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,
onEdit: PropTypes.func,
};
export default LinesTableRow;

View File

@ -0,0 +1,3 @@
.modal-title {
font-size: 1.2rem;
}

View 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;

View 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;

View 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;

View File

@ -0,0 +1,29 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../lines/service/LinesApiService';
const useLinesname = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
let expand = '?_expand=authors&_expand=types';
if (typeFilter) {
expand = `${expand}&name_like=${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 useLinesname;

View File

@ -0,0 +1,47 @@
import PropTypes from 'prop-types';
import {
Nav, Navbar, NavbarCollapse, NavbarToggle,
} from 'react-bootstrap';
import { Link, useLocation } from 'react-router-dom';
import iconBook from '../../assets/iconBook.svg';
import '../../index.css';
const Navigation = ({ routes }) => {
const location = useLocation();
const indexPageLink = routes.filter((route) => route.index === false).shift();
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title', 'title2'));
return(
<header id="header" className="fixed-top">
<Navbar expand='md' bg='light' data-bs-theme='dark' className='navbar navbar-expand-md navbar-dark'>
<div className='container'>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? '/'}>
<img src={iconBook} alt="логотип" />
<div className="word">
Book <br/>
shop
</div>
</Navbar.Brand>
<NavbarToggle aria-controls='main-navbar' />
<NavbarCollapse className="justify-content-end me-5" id='main-navbar '>
<Nav className='main-navbar' activeKey={location.pathname}>
{
pages.map((page) =>
<Nav.Link as={Link} key={page.path} eventKey={page.path} to={page.path ?? '/'}>
{page.title} {page.title2}
</Nav.Link>)
}
</Nav>
</NavbarCollapse>
</div>
</Navbar >
</header>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

View 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;

View File

@ -0,0 +1,5 @@
import ApiService from '../../api/ApiService';
const TypesApiService = new ApiService('types');
export default TypesApiService;

View File

@ -0,0 +1,58 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
import useAuthorizationForm from '../hooks/AuthorizationFormHook';
import AuthorizationInput from './AuthorizationInput.jsx';
import { Link } from 'react-router-dom';
const RegistrationForm = () => {
const {
user,
validated,
handleSubmit,
handleChange,
} = useAuthorizationForm();
const onSubmit = async (event) => {
await handleSubmit(event);
};
return (
<>
<Form className='main_Sign_in' noValidate validated={validated} onSubmit={onSubmit}>
<div className="main_wrapper_Sign_in">
<div className="main_block_Sign_in">
<div className="up_word">
<p className="main_title">
Sign in
</p>
<p className="main_text">
Login using your username and password
</p>
</div>
<div className="main_fields">
<AuthorizationInput user={user} handleChange={handleChange} />
</div>
<div className="class_login">
<button className="button_login" type='submit'>
Login
</button>
</div>
<div className="down_word">
If you don&apos;t have an account, <br/>
then
<Link to="/Register" className = "word_registr_Sign_in">register</Link>
</div>
</div>
</div>
</Form>
</>
);
};
RegistrationForm.propTypes = {
id: PropTypes.string,
};
export default RegistrationForm;

View File

@ -0,0 +1,23 @@
import PropTypes from 'prop-types';
const AuthorizationInput = ({ user, handleChange }) => {
return (
<>
<div className="main_field_one_Sign_in">
<input type="text" placeholder="login" name='name' className="input_Sign_in" value={user.name} onChange={handleChange}
required/>
</div>
<div className="main_field_two_Sign_in">
<input type="password" placeholder="password" name='password' className="input_Sign_in" value={user.password} onChange={handleChange}
required/>
</div>
</>
);
};
AuthorizationInput.propTypes = {
user: PropTypes.object,
handleChange: PropTypes.func,
};
export default AuthorizationInput;

View File

@ -0,0 +1,66 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import UsersApiService from '../../service/UsersApiService';
import useUserObject from '../../hooks/UserObjectHook';
import useAuthorization from '../../context_hooks/AuthorizationHook';
const useAuthorizationForm = () => {
const { user, setUser } = useUserObject();
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const { userLogin } = useAuthorization();
const getProperties = (formData) => {
const { name } = formData;
const { password } = formData;
const { role } = formData;
return {
name: name.toString(),
password: password.toString(),
role: role.toString(),
};
};
const handleChange = (event) => {
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setUser({
...user,
[inputName]: inputValue,
});
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
const body = getProperties(user);
const { name, password } = body;
if (form.checkValidity()) {
const expand = `?name=${name}&password=${password}`;
const data = await UsersApiService.getAll(expand);
if (data.length !== 0) {
userLogin(data[0].id);
return true;
}
}
toast.error('Неправильно введен логин или пароль', { id: 'Authorization' });
setValidated(true);
return false;
};
return {
user,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useAuthorizationForm;

View File

@ -0,0 +1,33 @@
import PropTypes from 'prop-types';
import {
createContext,
useEffect,
useReducer,
} from 'react';
import { authorizationReducer, loadId, saveId } from './AuthorizationReducer';
const UserContext = createContext(null);
export const IdProvider = ({ children }) => {
const [id, dispatch] = useReducer(authorizationReducer, null, loadId);
useEffect(() => {
if (id && id !== undefined) {
saveId(id);
} else {
loadId();
}
}, [id]);
return (
<UserContext.Provider value={{ user_id: id, dispatch }}>
{children}
</UserContext.Provider>
);
};
IdProvider.propTypes = {
children: PropTypes.node,
};
export default UserContext;

View File

@ -0,0 +1,23 @@
import { useContext } from 'react';
import AuthorizationContext from './AuthorizationContext';
import { userLogin, userLogout } from './AuthorizationReducer';
const useAuthorization = () => {
const { id, dispatch } = useContext(AuthorizationContext);
const getId = () => {
if (!id) {
return '';
}
return id.toString();
};
return {
id,
getId,
userLogin: (item) => dispatch(userLogin(item)),
userLogout: () => dispatch(userLogout()),
};
};
export default useAuthorization;

View File

@ -0,0 +1,40 @@
const USER_ID = 'userId';
const USER_LOGIN = 'user/login';
const USER_LOGOUT = 'user/logout';
export const saveId = (id) => {
localStorage.setItem(USER_ID, JSON.stringify(id));
};
export const loadId = (initialValue = null) => {
const idData = localStorage.getItem(USER_ID);
if (idData) {
return JSON.parse(idData);
}
return initialValue;
};
export const authorizationReducer = (id, action) => {
const { item: user } = action;
window.location.reload();
switch (action.type) {
case USER_LOGIN: {
return user;
}
case USER_LOGOUT: {
localStorage.removeItem(USER_ID);
return '';
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const userLogin = (item) => ({
type: USER_LOGIN, item,
});
export const userLogout = () => ({
type: USER_LOGOUT,
});

View File

@ -0,0 +1,34 @@
import { useState, useEffect } from 'react';
import UsersApiService from '../service/UsersApiService';
const useUserObject = (id) => {
const emptyObject = {
name: '',
password: '',
role: '',
id: '',
};
const [userObject, setUserObject] = useState({ ...emptyObject });
const getUserObject = async (userId) => {
if (userId && userId > 0) {
const data = await UsersApiService.get(userId);
setUserObject(data);
} else {
setUserObject({ ...emptyObject });
}
};
useEffect(() => {
getUserObject(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
user: userObject,
setUser: setUserObject,
};
};
export default useUserObject;

View File

@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';
import UsersApiService from '../service/UsersApiService';
const useUsers = () => {
const [users, setUsers] = useState([]);
const getUsers = async () => {
const data = await UsersApiService.getAll();
setUsers(data ?? []);
};
useEffect(() => {
getUsers();
}, []);
return {
types: users,
};
};
export default useUsers;

View File

@ -0,0 +1,59 @@
import PropTypes from 'prop-types';
import { Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useRegistrationForm from '../hooks/RegistrationFormHook';
import RegistrationInput from './RegistrationInput.jsx';
const RegistrationForm = () => {
const navigate = useNavigate();
const {
user,
validated,
handleSubmit,
handleChange,
} = useRegistrationForm();
const onBack = () => {
navigate('/user-page');
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onBack();
}
};
return (
<>
<Form className='main_Register' noValidate validated={validated} onSubmit={onSubmit}>
<div className="main_wrapper_Register">
<div className="main_block_Register">
<div className="up_word_Register">
<p className="main_title_Register">
Create an account
</p>
<p className="main_text_Register">
Enter your nickname, username and password
</p>
</div>
<div className="main_fields_Register">
<RegistrationInput user={user} handleChange={handleChange} />
</div>
<div className="class_login_Register">
<button className="button_login_Register" type='submit'>
Register
</button>
</div>
</div>
</div>
</Form>
</>
);
};
RegistrationForm.propTypes = {
id: PropTypes.string,
};
export default RegistrationForm;

View File

@ -0,0 +1,26 @@
import PropTypes from 'prop-types';
const RegistrationInput = ({ user, handleChange }) => {
return (
<>
{/* <div className="main_field_one_Register">
<input type="text" placeholder="nickname" className="input_Register"/>
</div> */}
<div className="main_field_one_Register">
<input name='name' type="text" placeholder="login" className="input_Register" value={user.name} onChange={handleChange}
required/>
</div>
<div className="main_field_two_Register">
<input name='password' type="password" placeholder="password" className="input_Register" value={user.password} onChange={handleChange}
required/>
</div>
</>
);
};
RegistrationInput.propTypes = {
user: PropTypes.object,
handleChange: PropTypes.func,
};
export default RegistrationInput;

View File

@ -0,0 +1,72 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import UsersApiService from '../../service/UsersApiService';
import useUserObject from '../../hooks/UserObjectHook';
import useAuthorization from '../../context_hooks/AuthorizationHook';
const useRegistrationForm = () => {
const { user, setUser } = useUserObject();
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const { userLogin } = useAuthorization();
const getProperties = (formData) => {
const { name } = formData;
const { password } = formData;
const { role } = formData;
return {
name: name.toString(),
password: password.toString(),
role: role.toString(),
};
};
const handleChange = (event) => {
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setUser({
...user,
[inputName]: inputValue,
});
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
const body = getProperties(user);
const { name, password } = body;
if (form.checkValidity()) {
let expand = `?name=${name}`;
let data = await UsersApiService.getAll(expand);
if (data.length !== 0) {
toast.error('Имя уже занято', { id: 'Registration' });
setValidated(true);
return false;
}
await UsersApiService.create(body);
toast.success('Элемент успешно сохранен', { id: 'Registration' });
expand = `?name=${name}&password=${password}`;
data = await UsersApiService.getAll(expand);
userLogin(data[0].id);
return true;
}
setValidated(true);
return false;
};
return {
user,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useRegistrationForm;

View File

@ -0,0 +1,5 @@
import ApiService from '../../api/ApiService';
const UsersApiService = new ApiService('users');
export default UsersApiService;

View File

@ -0,0 +1,52 @@
import { Form, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import useAuthorization from '../context_hooks/AuthorizationHook';
import useUserObject from '../hooks/UserObjectHook';
const UserPageInfo = () => {
const id = parseInt(localStorage.getItem('userId'), 10);
const { user } = useUserObject(id);
const { userLogout } = useAuthorization();
return (
<>
<Form className='main_Register'>
<div className="main_wrapper_Register">
<div className="main_block_Register">
<div className="up_word_Register">
<p className="UserPage_HelloWord">
Hello, {user.name || 'гость'}!
</p>
<p className="main_text_Register">
This is your personal account. Here you can go to the catalog and buy your favorite books and contact us in case of an error.
</p>
</div>
<div className='ButtonUserPageInfo'>
<div className="d-grid gap-2 mt-2 d-md-flex justify-content-md-center">
<Button as={Link} to="/Books" className='button_UserName'>Books</Button>
<Button as={Link} to="/Contact" className='button_UserName'>Contacts</Button>
<Button className='button_UserName' onClick={userLogout}>Exit</Button>
{user.role === 'admin'
&&
<>
<Button as={Link} to="/PageAdmin" className='button_UserName'>Admin Page</Button> <br/>
</>
}
</div>
</div>
{/* <div className="d-grid gap-2 mt-2 d-md-flex justify-content-md-center">
{user.role === 'admin'
&&
<>
<Button as={Link} to="/PurchaseManagement" className='button_UserName'>Purchase Management</Button>
</>
}
</div> */}
</div>
</div>
</Form>
</>
);
};
export default UserPageInfo;

View 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;

1115
laba5/src/index.css Normal file

File diff suppressed because it is too large Load Diff

77
laba5/src/main.jsx Normal file
View File

@ -0,0 +1,77 @@
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 ErrorPage from './pages/ErrorPage.jsx';
import MainPage from './pages/MainPage.jsx';
import Books from './pages/Books.jsx';
import Contact from './pages/Contact.jsx';
import Basket from './pages/Basket.jsx';
import iconBasket from './assets/iconShoppingCurt.svg';
import SignIn from './pages/SignIn.jsx';
import iconMan from './assets/iconMan.svg';
import Register from './pages/Register.jsx';
import PageAdmin from './pages/PageAdmin.jsx';
import UserPage from './pages/UserPage.jsx';
const routes = [
{
index: true,
path: '/',
element: <MainPage />,
title: 'Home',
},
{
path: '/Books',
element: <Books />,
title: 'Books',
},
{
path: '/Contact',
element: <Contact />,
title: 'Contact',
},
{
path: '/Basket',
element: <Basket />,
title: <img src={iconBasket}/>,
},
{
path: '/SignIn',
element: <SignIn />,
},
{
path: '/Register',
element: <Register />,
},
{
path: '/PageAdmin',
element: <PageAdmin />,
},
{
path: '/user-page',
element: <UserPage/>,
title: <img src={iconMan} />,
title2: 'personal area',
}
];
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>,
);

View File

@ -0,0 +1,11 @@
import '../index.css';
// import imageDracula from '../assets/imageDracula.jpg';
// import { Link } from 'react-router-dom';
import Cart from '../components/cart/Cart.jsx';
const Basket = () => {
return (
<Cart />
);
};
export default Basket;

71
laba5/src/pages/Books.jsx Normal file
View File

@ -0,0 +1,71 @@
import '../index.css';
//import { useState } from 'react';
import ProductCard from '../components/cards/cards.jsx';
import useLines from '../components/lines/hooks/LinesHook';
import useCart from '../components/cart/CartHook';
import useTypeFilter from '../components/lines/hooks/LinesFilterHook'
import Select from '../components/input/Select.jsx'
//import useLinesname from '../components/name/name'
const Books = () => {
//const [searchTerm, setSearchTerm] = useState('');
const { types, currentFilter, handleFilterChange,} = useTypeFilter();
//const { lines } = useLinesname(searchTerm);
const { lines } = useLines(currentFilter);
const { addToCart } = useCart();
// const handleSearchChange = (event) => {
// // Обновляем состояние при вводе текста в поле поиска
// setSearchTerm(event.target.value);
// };
return (
<div className="main_Books">
<div className="container">
<div className="main_wrapper">
<div className="main_block1">
<p className="Word_Genres">Genres</p>
<div className="Label">
<div className="Label_block_1">
<Select className='mt-2' values={types}
value={currentFilter} onChange={handleFilterChange} />
</div>
</div>
<div className="Search_Field">
{/* <label className="label_search">
<input
className="search_input"
type="text"
placeholder="name"
value={searchTerm}
onChange={handleSearchChange}
/>
</label> */}
</div>
</div>
<div className="main_block2">
{lines.map((line) => (
<ProductCard
key={line.id}
image={line.image}
price={line.price}
name={line.name}
authors={line.authors.name}
types={line.types.name}
onAddCart={() => addToCart(line)}
/>
))}
</div>
</div>
</div>
</div>
);
};
export default Books;

View File

@ -0,0 +1,35 @@
import '../index.css';
import {Link} from 'react-router-dom';
const Contact = () => {
return (
<div className='Unite'>
<div className="main_Contact">
<div className="container">
<div className="intro_wrapper_Contact">
<h1 className="intro_title_Contact">
Contact
</h1>
</div>
</div>
</div>
<div className="footer_Contact">
<div className="container">
<div className="footer_wrapper_Contact">
<div className="footer_words_with_link">
<p className="footer_word_Contact">
If you have any questions or there was some mistake,
please write to us by email<span className='e-mail'></span>
<Link to={'/https://mail.ru/?ysclid=lqfruhxqbz509144246'} className = "word_link_mail">
book_shop@mail.com.
</Link>
We will try to respond as soon as possible.
</p>
</div>
</div>
</div>
</div>
</div>
);
};
export default Contact;

View 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;

View File

@ -0,0 +1,23 @@
import '../index.css';
const MainPage = () => {
return (
<div className="mainPage">
<div className="container">
<div className="intro_wrapper">
<div className="intro_block">
<h1 className="intro_title">
There are a lot of books in our store
</h1>
<p className="intro_text">
Come to our store or choose any books&shy; to your taste at a very favorable price.
Every day we are replenished with more and more products.
</p>
</div>
</div>
</div>
</div>
);
};
export default MainPage;

View File

@ -0,0 +1,8 @@
import Lines from '../components/lines/table/Lines.jsx';
const PageAdmin = () => {
return (
<Lines />
);
};
export default PageAdmin;

View File

@ -0,0 +1,11 @@
import '../index.css';
import RegistrationForm from '../components/users/registration/form/RegistrationForm.jsx';
const Register = () => {
return (
<>
<RegistrationForm />
</>
);
};
export default Register;

View File

@ -0,0 +1,9 @@
import '../index.css';
import AuthorizationForm from '../components/users/authorization/form/AuthorizationForm.jsx';
const SignIn = () => {
return (
<AuthorizationForm />
);
};
export default SignIn;

View File

@ -0,0 +1,16 @@
import AuthorizationForm from '../components/users/authorization/form/AuthorizationForm.jsx';
import UserPageInfo from '../components/users/userPage/UserPageInfo.jsx';
const UserPage = () => {
const id = parseInt(localStorage.getItem('userId'), 10);
if (!id) {
return (
<AuthorizationForm/>
);
}
return (
<UserPageInfo/>
);
};
export default UserPage;

12
laba5/vite.config.js Normal file
View File

@ -0,0 +1,12 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
sourcemap: true,
chunkSizeWarningLimit: 1024,
emptyOutDir: true,
},
});