Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
2752d01aef | |||
|
f341bab21e | ||
|
3a8a3ba990 | ||
7b06ac0698 | |||
|
02ae977f7a | ||
|
bbd1a705b9 | ||
7072f16e11 | |||
e1f14b7116 | |||
44e6ca1e00 | |||
0dd01c5211 | |||
c8e161d7d6 |
25
.eslintrc.cjs
Normal file
@ -0,0 +1,25 @@
|
||||
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',
|
||||
},
|
||||
}
|
||||
|
146
.gitignore
vendored
@ -1,146 +1,24 @@
|
||||
# ---> Node
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
.cache
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
|
||||
# ---> VisualStudioCode
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
44
README.md
@ -1,2 +1,44 @@
|
||||
# Internet_Programming_PIbd-21_Rodionov_I_A
|
||||
### Окружение:
|
||||
- [nodejs 20 LTS latest](https://nodejs.org/en/download/);
|
||||
- [VSCode](https://code.visualstudio.com/download);
|
||||
- [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) плагин для VSCode;
|
||||
- [CSS Class Intellisense](https://marketplace.visualstudio.com/items?itemName=Tarrow.css-class-intellisense) плагин для автодополнения CSS-классов в HTML;
|
||||
- для отладки необходимы бразузеры Chrome или Edge.
|
||||
|
||||
Настройки плагина CSS Class Intellisense находятся в файле ./vscode/cssconfig.json
|
||||
|
||||
### Команды
|
||||
|
||||
#### Создание пустого проекта:
|
||||
|
||||
```commandline
|
||||
npm create vite@latest ./ -- --template react
|
||||
```
|
||||
|
||||
#### Установка зависимостей:
|
||||
|
||||
```commandline
|
||||
npm install
|
||||
```
|
||||
|
||||
#### Запуск проекта в режиме разработки (development):
|
||||
|
||||
```commandline
|
||||
npm run dev
|
||||
```
|
||||
|
||||
#### Запуск проекта в продуктовом режиме (production):
|
||||
|
||||
```commandline
|
||||
npm run prod
|
||||
```
|
||||
|
||||
### Полезные ссылки
|
||||
|
||||
1. Global Object - https://developer.mozilla.org/en-US/docs/Glossary/Global_object
|
||||
2. Global Scope - https://developer.mozilla.org/en-US/docs/Glossary/Global_scope
|
||||
3. localStorage - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
|
||||
4. JavaScript Execution Context – How JS Works Behind The Scenes - https://www.freecodecamp.org/news/execution-context-how-javascript-works-behind-the-scenes/
|
||||
5. Extracting State Logic into a Reducer - https://react.dev/learn/extracting-state-logic-into-a-reducer
|
||||
6. Passing Data Deeply with Context - https://react.dev/learn/passing-data-deeply-with-context
|
||||
7. Scaling Up with Reducer and Context - https://react.dev/learn/scaling-up-with-reducer-and-context
|
16
index.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image" href="src/assets/icons/logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Читай-комната</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root" class="d-flex flex-column min-vh-100 h-100"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
15
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
json-server.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"static": "./node_modules/json-server/public",
|
||||
"port": 8081,
|
||||
"watch": "true"
|
||||
}
|
5953
package-lock.json
generated
Normal file
38
package.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "ip-rodionov",
|
||||
"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"
|
||||
}
|
||||
}
|
3
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
src/App.jsx
Normal file
@ -0,0 +1,29 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Container } from 'react-bootstrap';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import Footer from './components/footer/Footer.jsx';
|
||||
import Navigation from './components/navigation/Navigation.jsx';
|
||||
import { SearchProvider } from './components/navigation/SearchContext.jsx';
|
||||
import { CartProvider } from './components/cart/CartContext.jsx';
|
||||
|
||||
const App = ({ routes }) => {
|
||||
return (
|
||||
<CartProvider>
|
||||
<SearchProvider>
|
||||
<Navigation routes={routes}></Navigation>
|
||||
<Container className="d-flex flex-column flex-grow-1" as="main" fluid="md">
|
||||
<Outlet />
|
||||
</Container>
|
||||
<Footer />
|
||||
<Toaster position='top-center' reverseOrder={true} />
|
||||
</SearchProvider>
|
||||
</CartProvider>
|
||||
);
|
||||
};
|
||||
|
||||
App.propTypes = {
|
||||
routes: PropTypes.array,
|
||||
};
|
||||
|
||||
export default App;
|
BIN
src/assets/book_covers/cart/1.png
Normal file
After Width: | Height: | Size: 25 KiB |
BIN
src/assets/book_covers/cart/2.png
Normal file
After Width: | Height: | Size: 84 KiB |
BIN
src/assets/book_covers/catalog/1.png
Normal file
After Width: | Height: | Size: 524 KiB |
BIN
src/assets/book_covers/catalog/2.png
Normal file
After Width: | Height: | Size: 1.5 MiB |
BIN
src/assets/book_covers/catalog/3.png
Normal file
After Width: | Height: | Size: 283 KiB |
BIN
src/assets/book_covers/catalog/4.png
Normal file
After Width: | Height: | Size: 1.3 MiB |
BIN
src/assets/book_covers/catalog/5.png
Normal file
After Width: | Height: | Size: 1.2 MiB |
BIN
src/assets/book_covers/catalog/6.png
Normal file
After Width: | Height: | Size: 754 KiB |
BIN
src/assets/book_covers/catalog/7.png
Normal file
After Width: | Height: | Size: 1.3 MiB |
BIN
src/assets/book_covers/catalog/8.png
Normal file
After Width: | Height: | Size: 932 KiB |
BIN
src/assets/book_covers/catalog/9.png
Normal file
After Width: | Height: | Size: 519 KiB |
BIN
src/assets/book_covers/novelties/1.png
Normal file
After Width: | Height: | Size: 1.6 MiB |
BIN
src/assets/book_covers/novelties/2.png
Normal file
After Width: | Height: | Size: 283 KiB |
BIN
src/assets/book_covers/novelties/3.png
Normal file
After Width: | Height: | Size: 1.4 MiB |
BIN
src/assets/book_covers/novelties/4.png
Normal file
After Width: | Height: | Size: 573 KiB |
BIN
src/assets/book_covers/novelties/5.png
Normal file
After Width: | Height: | Size: 1.6 MiB |
BIN
src/assets/book_covers/novelties/6.png
Normal file
After Width: | Height: | Size: 1.3 MiB |
BIN
src/assets/book_covers/product_card/cover13d__w410.png
Normal file
After Width: | Height: | Size: 283 KiB |
BIN
src/assets/book_covers/promotions/1.png
Normal file
After Width: | Height: | Size: 534 KiB |
BIN
src/assets/book_covers/promotions/2.png
Normal file
After Width: | Height: | Size: 296 KiB |
BIN
src/assets/book_covers/promotions/3.png
Normal file
After Width: | Height: | Size: 413 KiB |
BIN
src/assets/book_covers/promotions/4.png
Normal file
After Width: | Height: | Size: 82 KiB |
BIN
src/assets/book_covers/promotions/5.png
Normal file
After Width: | Height: | Size: 1.8 MiB |
BIN
src/assets/book_covers/promotions/6.png
Normal file
After Width: | Height: | Size: 366 KiB |
BIN
src/assets/book_covers/recommendations/1.png
Normal file
After Width: | Height: | Size: 207 KiB |
BIN
src/assets/book_covers/recommendations/2.png
Normal file
After Width: | Height: | Size: 426 KiB |
BIN
src/assets/book_covers/recommendations/3.png
Normal file
After Width: | Height: | Size: 511 KiB |
BIN
src/assets/book_covers/recommendations/4.png
Normal file
After Width: | Height: | Size: 355 KiB |
BIN
src/assets/book_covers/recommendations/5.png
Normal file
After Width: | Height: | Size: 110 KiB |
BIN
src/assets/book_covers/recommendations/6.png
Normal file
After Width: | Height: | Size: 504 KiB |
BIN
src/assets/icons/card.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
src/assets/icons/cart_button.png
Normal file
After Width: | Height: | Size: 520 B |
BIN
src/assets/icons/check.png
Normal file
After Width: | Height: | Size: 501 B |
BIN
src/assets/icons/discont.png
Normal file
After Width: | Height: | Size: 484 B |
BIN
src/assets/icons/email.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
BIN
src/assets/icons/fire.png
Normal file
After Width: | Height: | Size: 1.1 KiB |
BIN
src/assets/icons/line.png
Normal file
After Width: | Height: | Size: 484 B |
BIN
src/assets/icons/logo.png
Normal file
After Width: | Height: | Size: 2.9 KiB |
BIN
src/assets/icons/map.png
Normal file
After Width: | Height: | Size: 950 KiB |
BIN
src/assets/icons/nothing.png
Normal file
After Width: | Height: | Size: 800 KiB |
BIN
src/assets/icons/novelty.png
Normal file
After Width: | Height: | Size: 709 B |
BIN
src/assets/icons/odnoklassniki.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
src/assets/icons/phone-call.png
Normal file
After Width: | Height: | Size: 4.4 KiB |
BIN
src/assets/icons/photo.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
src/assets/icons/placeholder_400_600.png
Normal file
After Width: | Height: | Size: 9.8 KiB |
BIN
src/assets/icons/skype.png
Normal file
After Width: | Height: | Size: 4.9 KiB |
BIN
src/assets/icons/telegram.png
Normal file
After Width: | Height: | Size: 733 B |
BIN
src/assets/icons/telephone-call.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
src/assets/icons/trash.png
Normal file
After Width: | Height: | Size: 1.0 KiB |
BIN
src/assets/icons/vk.png
Normal file
After Width: | Height: | Size: 1019 B |
BIN
src/assets/icons/youtube.png
Normal file
After Width: | Height: | Size: 714 B |
40
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
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;
|
99
src/components/cart/Cart.jsx
Normal file
@ -0,0 +1,99 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import Trash from '../../assets/icons/trash.png';
|
||||
import Item from '../cartItem/CartItem.jsx';
|
||||
import useCart from './CartHook';
|
||||
|
||||
const Cart = () => {
|
||||
const {
|
||||
cart,
|
||||
getCartSum,
|
||||
clearCart,
|
||||
numMorph,
|
||||
} = useCart();
|
||||
|
||||
const handleOrder = async () => {
|
||||
clearCart();
|
||||
toast.success('Заказ оформлен!');
|
||||
};
|
||||
|
||||
const [linesText, setLinesText] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setLinesText(numMorph(cart.length, 'товар', 'товара', 'товаров'));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [cart.length]);
|
||||
|
||||
return (
|
||||
<div className="row gy-3 mb-1">
|
||||
<div className="col-12 mb-3 mb-sm-4 mt-0 px-0">
|
||||
<div
|
||||
className="block d-flex justify-content-center lh-1"
|
||||
id="cart-title"
|
||||
>
|
||||
Моя корзина
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-8 px-0">
|
||||
<div
|
||||
className="block d-flex align-items-end lh-1"
|
||||
id="cart-items-num-text"
|
||||
>
|
||||
В корзине {cart.length} {linesText}:
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-4 d-flex justify-content-end px-0">
|
||||
<div className="block align-self-end">
|
||||
<button className="cart-button-remove d-flex justify-content-end align-items-end lh-1 border-0 bg-white pe-0" onClick={() => clearCart()}>
|
||||
<img
|
||||
src={Trash}
|
||||
className="trash-icon me-sm-2"
|
||||
alt="trash"
|
||||
width="24"
|
||||
height="24"
|
||||
/>
|
||||
Удалить все
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{cart.map((cartItem) => (
|
||||
<Item
|
||||
key = {cartItem.id}
|
||||
info={{
|
||||
cartItem,
|
||||
trash: Trash,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<div className="col-12 pt-3 border-top border-black px-0">
|
||||
<div
|
||||
className="block d-flex justify-content-end align-items-end lh-1"
|
||||
id="cart-final-price"
|
||||
>
|
||||
<span className="me-4" id="cart-final-price-text">
|
||||
Итого:
|
||||
</span>
|
||||
<span id="cart-final-price-value"> {`${parseInt(getCartSum(), 10)} р.`} </span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12 px-0">
|
||||
<div className="block d-flex justify-content-end">
|
||||
{
|
||||
cart.length === 0 && (
|
||||
<button className="btn rounded-5" id="cart-btn-checkout" disabled>
|
||||
Перейти к оформлению
|
||||
</button>)
|
||||
}
|
||||
{
|
||||
cart.length > 0 && (
|
||||
<button className="btn rounded-5" id="cart-btn-checkout" onClick={() => handleOrder()}>
|
||||
Перейти к оформлению
|
||||
</button>)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Cart;
|
29
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;
|
43
src/components/cart/CartHook.js
Normal file
@ -0,0 +1,43 @@
|
||||
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);
|
||||
};
|
||||
|
||||
const numMorph = (n, f1, f2, f5) => {
|
||||
const n1 = Math.abs(n) % 100;
|
||||
|
||||
if (n1 >= 11 && n1 <= 19) return f5;
|
||||
|
||||
const n2 = n % 10;
|
||||
if (n2 === 1) return f1;
|
||||
if (n2 > 1 && n2 < 5) return f2;
|
||||
return f5;
|
||||
};
|
||||
|
||||
const isPresent = (id) => {
|
||||
return cart.some((book) => book.id === id);
|
||||
};
|
||||
|
||||
return {
|
||||
cart,
|
||||
getCartSum: () => cartSum(),
|
||||
addToCart: (item) => dispatch(cartAdd(item)),
|
||||
removeFromCart: (item, instant) => dispatch(cartRemove(item, instant)),
|
||||
clearCart: () => dispatch(cartClear()),
|
||||
numMorph,
|
||||
isPresent,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCart;
|
74
src/components/cart/CartReducer.js
Normal file
@ -0,0 +1,74 @@
|
||||
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, instant) => {
|
||||
if (instant) {
|
||||
return cart.filter((cartItem) => cartItem.id !== item.id);
|
||||
}
|
||||
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, instant } = action;
|
||||
switch (action.type) {
|
||||
case CART_ADD: {
|
||||
return addToCart(cart, item);
|
||||
}
|
||||
case CART_REMOVE: {
|
||||
return removeFromCart(cart, item, instant);
|
||||
}
|
||||
case CART_CLEAR: {
|
||||
return [];
|
||||
}
|
||||
default: {
|
||||
throw Error(`Unknown action: ${action.type}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const cartAdd = (item) => ({
|
||||
type: CART_ADD, item,
|
||||
});
|
||||
|
||||
export const cartRemove = (item, instant) => ({
|
||||
type: CART_REMOVE, item, instant,
|
||||
});
|
||||
|
||||
export const cartClear = () => ({
|
||||
type: CART_CLEAR,
|
||||
});
|
25
src/components/cartItem/CartItem.jsx
Normal file
@ -0,0 +1,25 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import Desktop from './cartItemDesktop/CartItemDesktop.jsx';
|
||||
import Mobile from './cartItemMobile/CartItemMobile.jsx';
|
||||
|
||||
const CartItem = ({ info }) => {
|
||||
const [count, setCount] = useState(info.cartItem.count);
|
||||
|
||||
useEffect(() => {
|
||||
setCount(info.cartItem.count);
|
||||
}, [info.cartItem.count]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Desktop info={info} count={count}/>
|
||||
<Mobile info={info} count={count}/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
CartItem.propTypes = {
|
||||
info: PropTypes.object,
|
||||
};
|
||||
|
||||
export default CartItem;
|
92
src/components/cartItem/cartItemDesktop/CartItemDesktop.jsx
Normal file
@ -0,0 +1,92 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import useCart from '../../cart/CartHook';
|
||||
import imgPlaceholder from '../../../assets/icons/placeholder_400_600.png';
|
||||
|
||||
const CartItemDesktop = ({ info, count }) => {
|
||||
const {
|
||||
addToCart,
|
||||
removeFromCart,
|
||||
} = useCart();
|
||||
|
||||
const price = `${parseInt(info.cartItem.price, 10)} р.`;
|
||||
const countPrice = `${parseInt(info.cartItem.price * info.cartItem.count, 10)} р.`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="col-1 border-top border-black pt-3 d-none d-sm-block">
|
||||
<div className="block">
|
||||
<img
|
||||
src={info.cartItem.image || imgPlaceholder}
|
||||
className="cart-book-cover me-3"
|
||||
alt="cart-book-cover-1"
|
||||
width="88"
|
||||
height="138"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-6 pt-3 border-top border-black d-none d-sm-block">
|
||||
<div className="cart-book-description block d-flex flex-column justify-content-start ms-5 ms-lg-4 ms-xl-0 ps-0 ps-sm-2 ps-md-0 ps-xl-3 ps-xxl-0">
|
||||
<p className="cart-book-description-title mb-2">{info.cartItem.title}</p>
|
||||
<p className="cart-book-description-author">{info.cartItem.author}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-3 pt-2 border-top border-black d-none d-sm-block">
|
||||
<div className="block d-flex align-items-start justify-content-end">
|
||||
<button
|
||||
type="button"
|
||||
className="button-minus border border-end-0 rounded-start bg-white"
|
||||
onClick={() => removeFromCart(info.cartItem, false)}
|
||||
>
|
||||
–
|
||||
</button>
|
||||
<label className="cart-input-label">
|
||||
<input
|
||||
readOnly
|
||||
type="tel"
|
||||
className="cart-input h-100 w-100 border text-center p-0"
|
||||
placeholder="1"
|
||||
value={count}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="button-plus border border-start-0 rounded-end bg-white"
|
||||
onClick={() => addToCart(info.cartItem)}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-2 pt-3 border-top border-black d-none d-sm-block">
|
||||
<div className="block d-flex flex-column align-items-end h-100">
|
||||
<p className="cart-price">{price}</p>
|
||||
<p className="cart-price-count text-secondary mt-3">
|
||||
{parseInt(info.cartItem.price, 10)}
|
||||
{' * '}
|
||||
{info.cartItem.count}
|
||||
{' = '}
|
||||
{countPrice}
|
||||
</p>
|
||||
<div className="flex-grow-1"></div>
|
||||
<button className="cart-button-remove d-flex align-items-end lh-1 border-0 bg-white pe-0" onClick={() => removeFromCart(info.cartItem, true)}>
|
||||
<img
|
||||
src={info.trash}
|
||||
className="trash-icon me-2"
|
||||
alt="trash"
|
||||
width="24"
|
||||
height="24"
|
||||
/>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
CartItemDesktop.propTypes = {
|
||||
info: PropTypes.object,
|
||||
count: PropTypes.number,
|
||||
};
|
||||
|
||||
export default CartItemDesktop;
|
86
src/components/cartItem/cartItemMobile/CartItemMobile.jsx
Normal file
@ -0,0 +1,86 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import useCart from '../../cart/CartHook';
|
||||
import imgPlaceholder from '../../../assets/icons/placeholder_400_600.png';
|
||||
|
||||
const CartItemMobile = ({ info, count }) => {
|
||||
const {
|
||||
addToCart,
|
||||
removeFromCart,
|
||||
} = useCart();
|
||||
|
||||
const price = `${parseInt(info.cartItem.price, 10)} р.`;
|
||||
const countPrice = `${parseInt(info.cartItem.price * info.cartItem.count, 10)} р.`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="col-2 border-top border-black pt-3 d-sm-none">
|
||||
<div className="block">
|
||||
<img
|
||||
src={info.cartItem.image || imgPlaceholder}
|
||||
className="cart-book-cover me-3"
|
||||
alt="cart-book-cover"
|
||||
width="88"
|
||||
height="138"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-10 pt-3 border-top border-black d-sm-none">
|
||||
<div className="block ms-4">
|
||||
<p className="cart-book-description-title mb-2">{info.cartItem.title}</p>
|
||||
<p className="cart-book-description-author mb-2">{info.cartItem.author}</p>
|
||||
<div className="d-flex mb-2">
|
||||
<p className="cart-price me-3">{price}</p>
|
||||
<p className="cart-price-count text-secondary text-center lh-sm mt-1" id="mobile-price-count">
|
||||
{parseInt(info.cartItem.price, 10)}
|
||||
{' * '}
|
||||
{info.cartItem.count}
|
||||
{' = '}
|
||||
{countPrice}
|
||||
</p>
|
||||
</div>
|
||||
<div className="d-flex align-items-center">
|
||||
<button
|
||||
type="button"
|
||||
className="button-minus border border-end-0 rounded-start bg-white"
|
||||
onClick={() => removeFromCart(info.cartItem, false)}
|
||||
>
|
||||
–
|
||||
</button>
|
||||
<label className="cart-input-label d-flex">
|
||||
<input
|
||||
readOnly
|
||||
type="tel"
|
||||
className="cart-input h-100 w-100 border text-center"
|
||||
value={count}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="button-plus border border-start-0 rounded-end bg-white"
|
||||
onClick={() => addToCart(info.cartItem)}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<div className="flex-grow-1"></div>
|
||||
<button className="cart-button-remove d-flex align-items-end lh-1 border-0 bg-white pe-0" onClick={() => removeFromCart(info.cartItem, true)}>
|
||||
<img
|
||||
src={info.trash}
|
||||
className="trash-icon"
|
||||
alt="trash"
|
||||
width="24"
|
||||
height="24"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
CartItemMobile.propTypes = {
|
||||
info: PropTypes.object,
|
||||
count: PropTypes.number,
|
||||
};
|
||||
|
||||
export default CartItemMobile;
|
27
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;
|
5
src/components/cartItems/service/CartItemsApiService.js
Normal file
@ -0,0 +1,5 @@
|
||||
import ApiService from '../../api/ApiService';
|
||||
|
||||
const CartItemsApiService = new ApiService('cart-items');
|
||||
|
||||
export default CartItemsApiService;
|
152
src/components/catalog/Catalog.jsx
Normal file
@ -0,0 +1,152 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { Link } from 'react-router-dom';
|
||||
import Book from '../catalogBook/CatalogBook.jsx';
|
||||
import useCategoryFilter from '../lines/hooks/LinesFilterHook';
|
||||
import useLines from '../lines/hooks/LinesHook';
|
||||
import useCategoriesItem from '../categories/hooks/CategoriesItemHook';
|
||||
import usePagination from '../pagination/hooks/PaginationHook';
|
||||
import Select from '../sortSelect/SortSelect.jsx';
|
||||
import Pagination from '../pagination/Pagination.jsx';
|
||||
import useUser from '../users/hooks/UserHook';
|
||||
|
||||
const Catalog = ({ id }) => {
|
||||
const { categories } = useCategoryFilter();
|
||||
const { item } = useCategoriesItem(id);
|
||||
|
||||
const { lines } = useLines(id);
|
||||
const [sortedLines, setSortedLines] = useState(lines);
|
||||
|
||||
const {
|
||||
items, numbers, prevPage, changeCPage, nextPage, currPage,
|
||||
} = usePagination(sortedLines, 8);
|
||||
|
||||
const idUser = parseInt(localStorage.getItem('CurrentUser'), 10) || -1;
|
||||
const currUser = useUser(idUser).user;
|
||||
|
||||
useEffect(() => {
|
||||
const mainElement = document.querySelector('main');
|
||||
|
||||
if (mainElement) {
|
||||
mainElement.classList.add('my-0');
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (mainElement) {
|
||||
mainElement.classList.remove('my-0');
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="row gy-3 flex-grow-1">
|
||||
<div
|
||||
className="col-2 d-none d-md-block ps-0 mt-0 bg-white border border-3 border-top-0 border-bottom-0"
|
||||
id="catalog-categories"
|
||||
>
|
||||
<div className="block d-flex flex-column justify-content-center p-2 h-100">
|
||||
<p className="mb-4 mt-2" id="catalog-categories-title">
|
||||
Категории
|
||||
</p>
|
||||
<ul
|
||||
className="list-unstyled ps-0 mb-4 d-flex flex-column gap-3 flex-grow-1"
|
||||
id="catalog-categories-list"
|
||||
>
|
||||
{categories.map((category) => (
|
||||
<li
|
||||
className={
|
||||
category.name === item.name ? 'active-category' : ''
|
||||
}
|
||||
key={category.id}
|
||||
>
|
||||
<Link to={`/pageCatalog/${category.id}`}>
|
||||
{category.name}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12 col-md-10 d-flex flex-column bg-white mt-0 pt-2 pt-lg-3">
|
||||
<div className="row gy-3">
|
||||
<div className="col-12 mb-3 mb-lg-5 px-0 d-md-none">
|
||||
<div
|
||||
className="block d-flex lh-1"
|
||||
id="catalog-section-navigation"
|
||||
>
|
||||
<Link
|
||||
to="/pageCatalogMobile"
|
||||
className="me-2 text-decoration-none"
|
||||
>
|
||||
Каталог
|
||||
</Link>
|
||||
<span className="text-secondary me-2"> {'>'} </span>
|
||||
<Link
|
||||
to={`/pageCatalog/${id}`}
|
||||
className="text-decoration-none"
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12 mb-3 mb-lg-5 px-0">
|
||||
<div
|
||||
className="block d-flex justify-content-center lh-1"
|
||||
id="catalog-title"
|
||||
>
|
||||
<div>{item.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-12 mb-3 mb-lg-5 gx-0">
|
||||
<div className="block">
|
||||
<Select
|
||||
setLines={setSortedLines}
|
||||
initialLines={lines}
|
||||
storageName='sortType'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{items.map((line) => (
|
||||
<Book
|
||||
key={line.id}
|
||||
description={{
|
||||
id: line.id,
|
||||
cover: line.image,
|
||||
price: `${parseInt(line.price, 10)} ₽`,
|
||||
title: line.title,
|
||||
author: line.author,
|
||||
destination: `/pageProductСard/${line.id}`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{
|
||||
currUser.id !== '' && currUser.isAdmin && (
|
||||
<Link to="/pageAdmin" className="text-dark fw-bolder mt-5 text-decoration-none">
|
||||
Админ.
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
<div className="d-flex flex-grow-1"></div>
|
||||
<nav className="block mt-5 mt-sm-4 mt-lg-5 mb-2 gx-0 table-responsive">
|
||||
<Pagination
|
||||
numbers={numbers}
|
||||
prevPage={prevPage}
|
||||
changeCPage={changeCPage}
|
||||
nextPage={nextPage}
|
||||
currPage={currPage}
|
||||
/>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Catalog.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default Catalog;
|
56
src/components/catalogBook/CatalogBook.jsx
Normal file
@ -0,0 +1,56 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Link } from 'react-router-dom';
|
||||
import imgPlaceholder from '../../assets/icons/placeholder_400_600.png';
|
||||
import useLinesItem from '../lines/hooks/LinesItemHook';
|
||||
import useCart from '../cart/CartHook';
|
||||
|
||||
const CatalogBook = ({ description }) => {
|
||||
const { item } = useLinesItem(description.id);
|
||||
const { addToCart, isPresent } = useCart();
|
||||
|
||||
return (
|
||||
<div className="col-sm-6 col-md-4 col-lg-3 mt-4">
|
||||
<div className="block d-flex flex-column h-100">
|
||||
<div className="d-flex justify-content-center mb-4">
|
||||
<Link to={description.destination}>
|
||||
<img src={description.cover || imgPlaceholder} className="catalog-book-cover" alt="book-cover-catalog-2" width="155" height="245" />
|
||||
</Link>
|
||||
</div>
|
||||
<div className="catalog-book-description d-flex flex-column align-items-start">
|
||||
<p className="catalog-price mb-3">
|
||||
{description.price || ''}
|
||||
</p>
|
||||
<p className="catalog-book-title mb-3">
|
||||
{description.title || ''}
|
||||
</p>
|
||||
<p className="catalog-author mb-3">
|
||||
{description.author || ''}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex-grow-1"></div>
|
||||
<div className="catalog-btn-checkout-div d-flex justify-content-start">
|
||||
{
|
||||
isPresent(description.id) && (
|
||||
<button className="catalog-bth-checkout btn rounded-5 px-3 btn-info" disabled>
|
||||
Уже в корзине
|
||||
</button>
|
||||
)
|
||||
}
|
||||
{
|
||||
!isPresent(description.id) && (
|
||||
<button className="catalog-bth-checkout btn rounded-5 px-3" onClick={() => addToCart(item)}>
|
||||
В корзину
|
||||
</button>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
CatalogBook.propTypes = {
|
||||
description: PropTypes.object,
|
||||
};
|
||||
|
||||
export default CatalogBook;
|
21
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
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;
|
53
src/components/footer/Footer.jsx
Normal file
@ -0,0 +1,53 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import Call from '../../assets/icons/telephone-call.png';
|
||||
import VK from '../../assets/icons/vk.png';
|
||||
import YouTube from '../../assets/icons/youtube.png';
|
||||
import Telegram from '../../assets/icons/telegram.png';
|
||||
import Odnoklassniki from '../../assets/icons/odnoklassniki.png';
|
||||
|
||||
const Footer = () => {
|
||||
const year = new Date().getFullYear();
|
||||
|
||||
return (
|
||||
<footer className="footer flex-shrink-0">
|
||||
<div className="container-md" id="footer-container">
|
||||
<div className="row d-flex align-items-center gy-3 gy-lg-0 gx-0" id="footer-row">
|
||||
<div className="col-md-6 col-lg-4">
|
||||
<div className="block d-flex justify-content-center justify-content-md-start" id="footer-copyright">
|
||||
© И. А. Родионов, {year}.
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-md-6 col-lg-3">
|
||||
<div className="block d-flex align-items-center justify-content-center justify-content-md-end">
|
||||
<img src={Call} className="me-2" alt="telephone-call" width="32" height="32" />
|
||||
<p id="footer-phone-number-text">
|
||||
+7 927 818-61-60
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-md-12 col-lg-5 mb-3 mb-lg-0">
|
||||
<div className="block d-flex align-items-center justify-content-center justify-content-lg-end">
|
||||
<p className="me-3" id="footer-social-media-text">
|
||||
Мы в соцсетях:
|
||||
</p>
|
||||
<Link to="/" className="me-3">
|
||||
<img src={VK} alt="vk" width="32" height="32" />
|
||||
</Link>
|
||||
<Link to="/" className="me-3">
|
||||
<img src={YouTube} alt="youtube" width="32" height="32" />
|
||||
</Link>
|
||||
<Link to="/" className="me-3">
|
||||
<img src={Telegram} alt="telegram" width="32" height="32" />
|
||||
</Link>
|
||||
<Link to="/">
|
||||
<img src={Odnoklassniki} alt="odnoklassniki" width="32" height="32" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
|
||||
export default Footer;
|
23
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={`${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;
|
30
src/components/input/Select.jsx
Normal file
@ -0,0 +1,30 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const Select = ({
|
||||
values, name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`${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((сategory) =>
|
||||
<option key={сategory.id} value={сategory.id}>{сategory.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;
|
24
src/components/input/TextArea.jsx
Normal file
@ -0,0 +1,24 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import { Form } from 'react-bootstrap';
|
||||
|
||||
const TextArea = ({
|
||||
name, label, value, onChange, className, ...rest
|
||||
}) => {
|
||||
return (
|
||||
<Form.Group className={`${className || ''}`} controlId={name}>
|
||||
<Form.Label>{label}</Form.Label>
|
||||
<Form.Control as="textarea" rows="3" name={name || ''} value={value || ''}
|
||||
onChange={onChange} {...rest} />
|
||||
</Form.Group>
|
||||
);
|
||||
};
|
||||
|
||||
TextArea.propTypes = {
|
||||
name: PropTypes.string,
|
||||
label: PropTypes.string,
|
||||
value: PropTypes.string,
|
||||
onChange: PropTypes.func,
|
||||
className: PropTypes.string,
|
||||
};
|
||||
|
||||
export default TextArea;
|
50
src/components/lines/form/LinesForm.jsx
Normal file
@ -0,0 +1,50 @@
|
||||
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 (
|
||||
<>
|
||||
<div className="row justify-content-center">
|
||||
<Form className='col-lg-8 col-xl-7 col-xxl-6' noValidate validated={validated} onSubmit={onSubmit}>
|
||||
<LinesItemForm item={item} handleChange={handleChange} />
|
||||
<Form.Group className='text-center mb-5 d-flex flex-column'>
|
||||
<Button className='edit-btn w-25 rounded-5' type='submit' variant='primary'>
|
||||
Сохранить
|
||||
</Button>
|
||||
<Button className='edit-btn w-25 mt-4' variant='secondary' onClick={() => onBack()}>
|
||||
Назад
|
||||
</Button>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesForm.propTypes = {
|
||||
id: PropTypes.string,
|
||||
};
|
||||
|
||||
export default LinesForm;
|
65
src/components/lines/form/LinesItemForm.jsx
Normal file
@ -0,0 +1,65 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import imgPlaceholder from '../../../assets/icons/placeholder_400_600.png';
|
||||
import Input from '../../input/Input.jsx';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import TextArea from '../../input/TextArea.jsx';
|
||||
import useCategories from '../../categories/hooks/CategoriesHook';
|
||||
|
||||
const LinesItemForm = ({ item, handleChange }) => {
|
||||
const { categories } = useCategories();
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='text-center'>
|
||||
<img id='image-preview' className='mb-4' alt='placeholder'
|
||||
src={item.image || imgPlaceholder} width={400} height={600} />
|
||||
</div>
|
||||
<Select values={categories} name='categoryId' label='Категории' value={item.categoryId} onChange={handleChange}
|
||||
className='mb-4' required />
|
||||
<Input name='title' label='Название книги' value={item.title} onChange={handleChange}
|
||||
className='mb-4' type='text' required />
|
||||
<Input name='author' label='Автор' value={item.author} onChange={handleChange}
|
||||
className='mb-4' type='text' required />
|
||||
<Input name='price' label='Цена' value={item.price} onChange={handleChange}
|
||||
className='mb-4' type='number' min='100.0' step='0.50' required />
|
||||
<Input name='count' label='Количество' value={item.count} onChange={handleChange}
|
||||
className='mb-4' type='number' min='1' step='1' required />
|
||||
<TextArea name='description' label='Описание книги' value={item.description}
|
||||
onChange={handleChange} className='mb-4' />
|
||||
<TextArea name='annotation' label='Аннотация' value={item.annotation}
|
||||
onChange={handleChange} className='mb-4' />
|
||||
<p className="mb-3">
|
||||
Xарактеристики:
|
||||
</p>
|
||||
<div className="mb-4 border border-1 border-secondary p-2">
|
||||
<Input name='bookIdCode' label='ID книги' value={item.bookIdCode} onChange={handleChange}
|
||||
className='mb-3' type='number' required />
|
||||
<Input name='publisher' label='Издательство' value={item.publisher} onChange={handleChange}
|
||||
className='mb-3' type='text' />
|
||||
<Input name='series' label='Серия' value={item.series} onChange={handleChange}
|
||||
className='mb-3' type='text' />
|
||||
<Input name='publicationYear' label='Год издания' value={item.publicationYear} onChange={handleChange}
|
||||
className='mb-3' type='number' required />
|
||||
<Input name='pagesNum' label='Количество страниц' value={item.pagesNum} onChange={handleChange}
|
||||
className='mb-3' type='number' />
|
||||
<Input name='size' label='Размер' value={item.size} onChange={handleChange}
|
||||
className='mb-3' type='text' />
|
||||
<Input name='coverType' label='Тип обложки' value={item.coverType} onChange={handleChange}
|
||||
className='mb-3' type='text' />
|
||||
<Input name='circulation' label='Тираж' value={item.circulation} onChange={handleChange}
|
||||
className='mb-3' type='number' />
|
||||
<Input name='weight' label='Вес, г' value={item.weight} onChange={handleChange}
|
||||
type='number' />
|
||||
</div>
|
||||
<Input name='image' label='Обложка книги' onChange={handleChange}
|
||||
className='mb-4' type='file' accept='image/*' />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LinesItemForm.propTypes = {
|
||||
item: PropTypes.object,
|
||||
handleChange: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesItemForm;
|
34
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
src/components/lines/hooks/LinesFilterHook.js
Normal file
@ -0,0 +1,28 @@
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import useСategories from '../../categories/hooks/CategoriesHook';
|
||||
|
||||
const useCategoryFilter = () => {
|
||||
const filterName = 'category';
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const { categories } = useСategories();
|
||||
|
||||
const handleFilterChange = (event) => {
|
||||
const category = event.target.value;
|
||||
if (category) {
|
||||
searchParams.set(filterName, event.target.value);
|
||||
} else {
|
||||
searchParams.delete(filterName);
|
||||
}
|
||||
setSearchParams(searchParams);
|
||||
};
|
||||
|
||||
return {
|
||||
categories,
|
||||
currentFilter: searchParams.get(filterName) || '',
|
||||
handleFilterChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useCategoryFilter;
|
30
src/components/lines/hooks/LinesHook.js
Normal file
@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLines = (categoryFilter) => {
|
||||
const [linesRefresh, setLinesRefresh] = useState(false);
|
||||
const [lines, setLines] = useState([]);
|
||||
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
|
||||
|
||||
const getLines = async () => {
|
||||
let expand = '?_expand=category';
|
||||
if (categoryFilter) {
|
||||
expand = `${expand}&categoryId=${categoryFilter}`;
|
||||
}
|
||||
const data = await LinesApiService.getAll(expand);
|
||||
setLines(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getLines();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [linesRefresh, categoryFilter]);
|
||||
|
||||
return {
|
||||
lines,
|
||||
setLines,
|
||||
handleLinesChange,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLines;
|
107
src/components/lines/hooks/LinesItemFormHook.js
Normal file
@ -0,0 +1,107 @@
|
||||
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 categoryId = parseInt(formData.categoryId, 10);
|
||||
const { title } = formData;
|
||||
const { author } = formData;
|
||||
const price = parseFloat(formData.price).toFixed(2);
|
||||
const count = parseInt(formData.count, 10);
|
||||
const sum = parseFloat(price * count).toFixed(2);
|
||||
const { description } = formData;
|
||||
const { annotation } = formData;
|
||||
const bookIdCode = parseInt(formData.bookIdCode, 10);
|
||||
const { publisher } = formData;
|
||||
const { series } = formData;
|
||||
const publicationYear = parseInt(formData.publicationYear, 10);
|
||||
const pagesNum = parseInt(formData.pagesNum, 10);
|
||||
const { size } = formData;
|
||||
const { coverType } = formData;
|
||||
const circulation = parseInt(formData.circulation, 10);
|
||||
const weight = parseInt(formData.weight, 10);
|
||||
const image = formData.image.startsWith('data:image') ? formData.image : '';
|
||||
return {
|
||||
categoryId: categoryId.toString(),
|
||||
title: title.toString(),
|
||||
author: author.toString(),
|
||||
price: price.toString(),
|
||||
count: count.toString(),
|
||||
sum: sum.toString(),
|
||||
description: description.toString(),
|
||||
annotation: annotation.toString(),
|
||||
bookIdCode: bookIdCode.toString(),
|
||||
publisher: publisher.toString(),
|
||||
series: series.toString(),
|
||||
publicationYear: publicationYear.toString(),
|
||||
pagesNum: pagesNum.toString(),
|
||||
size: size.toString(),
|
||||
coverType: coverType.toString(),
|
||||
circulation: circulation.toString(),
|
||||
weight: weight.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;
|
47
src/components/lines/hooks/LinesItemHook.js
Normal file
@ -0,0 +1,47 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import LinesApiService from '../service/LinesApiService';
|
||||
|
||||
const useLinesItem = (id) => {
|
||||
const emptyItem = {
|
||||
id: '',
|
||||
categoryId: '',
|
||||
title: '',
|
||||
author: '',
|
||||
price: '0',
|
||||
count: '0',
|
||||
description: '',
|
||||
annotation: '',
|
||||
bookIdCode: '',
|
||||
publisher: '',
|
||||
series: '',
|
||||
publicationYear: '',
|
||||
pagesNum: '',
|
||||
size: '',
|
||||
coverType: '',
|
||||
circulation: '',
|
||||
weight: '',
|
||||
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
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;
|
62
src/components/lines/table/Lines.jsx
Normal file
@ -0,0 +1,62 @@
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import Select from '../../input/Select.jsx';
|
||||
import ModalConfirm from '../../modal/ModalConfirm.jsx';
|
||||
import useLinesDeleteModal from '../hooks/LinesDeleteModalHook';
|
||||
import useCategoryFilter from '../hooks/LinesFilterHook';
|
||||
import useLines from '../hooks/LinesHook';
|
||||
import LinesTable from './LinesTable.jsx';
|
||||
import LinesTableRow from './LinesTableRow.jsx';
|
||||
|
||||
const Lines = () => {
|
||||
const { categories, currentFilter, handleFilterChange } = useCategoryFilter();
|
||||
|
||||
const { lines, handleLinesChange } = useLines(currentFilter);
|
||||
|
||||
const {
|
||||
isDeleteModalShow,
|
||||
showDeleteModal,
|
||||
handleDeleteConfirm,
|
||||
handleDeleteCancel,
|
||||
} = useLinesDeleteModal(handleLinesChange);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const showEditPage = (id) => {
|
||||
navigate(`/pageAddItem/${id}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="row gy-3">
|
||||
<div className="col-12 px-0">
|
||||
<div className="block d-flex justify-content-center fs-2 fw-bold" id="admin-title">
|
||||
Панель администратора
|
||||
</div>
|
||||
</div>
|
||||
<Select className='сol-12 mb-4' values={categories} label='Фильтр по категориям'
|
||||
value={currentFilter} onChange={handleFilterChange} />
|
||||
<LinesTable>
|
||||
{
|
||||
lines.map((line, index) =>
|
||||
<LinesTableRow
|
||||
key={line.id}
|
||||
index={index} line={line}
|
||||
onDelete={() => showDeleteModal(line.id)}
|
||||
onEditInPage={() => showEditPage(line.id)}
|
||||
/>)
|
||||
}
|
||||
</LinesTable>
|
||||
<div className="col-12 px-0 mb-2">
|
||||
<div className="block mb-4">
|
||||
<Link to="/pageAddItem" className="btn btn-primary">Добавить товар</Link>
|
||||
</div>
|
||||
</div>
|
||||
<ModalConfirm show={isDeleteModalShow}
|
||||
onConfirm={handleDeleteConfirm} onClose={handleDeleteCancel}
|
||||
title='Удаление' message='Удалить элемент?' />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Lines;
|
34
src/components/lines/table/LinesTable.jsx
Normal file
@ -0,0 +1,34 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const LinesTable = ({ children }) => {
|
||||
return (
|
||||
<div className="col-12 px-0">
|
||||
<div className="block table-responsive">
|
||||
<table className="table table-hover table-bordered align-middle">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope='col'>№</th>
|
||||
<th scope='col'>Название книги</th>
|
||||
<th scope='col'>Автор</th>
|
||||
<th scope='col'>Цена</th>
|
||||
<th scope='col'>Количество</th>
|
||||
<th scope='col'>Сумма</th>
|
||||
<th scope='col'>Категория каталога</th>
|
||||
<th scope='col'></th>
|
||||
<th scope='col'></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{children}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
LinesTable.propTypes = {
|
||||
children: PropTypes.node,
|
||||
};
|
||||
|
||||
export default LinesTable;
|
45
src/components/lines/table/LinesTableRow.jsx
Normal file
@ -0,0 +1,45 @@
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const LinesTableRow = ({
|
||||
index, line, onDelete, onEditInPage,
|
||||
}) => {
|
||||
const handleAnchorClick = (event, action) => {
|
||||
event.preventDefault();
|
||||
action();
|
||||
};
|
||||
|
||||
return (
|
||||
<tr>
|
||||
<th scope="row">{index + 1}</th>
|
||||
<td>{line.title}</td>
|
||||
<td>{line.author}</td>
|
||||
<td>{parseFloat(line.price).toFixed(2)}</td>
|
||||
<td>{line.count}</td>
|
||||
<td>{parseFloat(line.sum).toFixed(2)}</td>
|
||||
<td>{line.category.name}</td>
|
||||
<td>
|
||||
<a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}>
|
||||
<button className='btn btn-primary w-100'>
|
||||
Редактировать
|
||||
</button>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}>
|
||||
<button className='btn btn-primary w-100'>
|
||||
Удалить
|
||||
</button>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
};
|
||||
|
||||
LinesTableRow.propTypes = {
|
||||
index: PropTypes.number,
|
||||
line: PropTypes.object,
|
||||
onDelete: PropTypes.func,
|
||||
onEditInPage: PropTypes.func,
|
||||
};
|
||||
|
||||
export default LinesTableRow;
|
79
src/components/login/hooks/LoginFormHook.js
Normal file
@ -0,0 +1,79 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import useUsers from '../../users/hooks/UsersHook';
|
||||
import useUser from '../../users/hooks/UserHook';
|
||||
import { saveCart } from '../../cart/CartReducer';
|
||||
import CartItemsApiService from '../../cartItems/service/CartItemsApiService';
|
||||
|
||||
const useLoginForm = () => {
|
||||
const { user, setUser } = useUser();
|
||||
const { users } = useUsers();
|
||||
const [validated, setValidated] = useState(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const resetValidity = () => {
|
||||
setValidated(false);
|
||||
};
|
||||
|
||||
const getUserObject = (formData) => {
|
||||
const { email } = formData;
|
||||
const { password } = formData;
|
||||
|
||||
return {
|
||||
email: email.toString(),
|
||||
password: password.toString(),
|
||||
isAdmin: false,
|
||||
};
|
||||
};
|
||||
|
||||
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 = getUserObject(user);
|
||||
if (form.checkValidity()) {
|
||||
const foundUser = users.find((tempUser) =>
|
||||
tempUser.email === body.email && tempUser.password === body.password);
|
||||
if (foundUser) {
|
||||
localStorage.setItem('CurrentUser', foundUser.id);
|
||||
localStorage.removeItem('localCart');
|
||||
const cartItems = await CartItemsApiService.getAll();
|
||||
const item = cartItems.find((cartItem) =>
|
||||
parseInt(cartItem.userId, 10) === foundUser.id);
|
||||
if (item) {
|
||||
await CartItemsApiService.delete(item.id);
|
||||
const cart = JSON.parse(item.cart);
|
||||
saveCart(cart);
|
||||
}
|
||||
toast.success('Вы успешно вошли в аккаунт!');
|
||||
navigate('/', { replace: true });
|
||||
window.location.reload();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
toast.error('Пользователя с такими данными не существует!');
|
||||
setValidated(true);
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
user,
|
||||
validated,
|
||||
handleSubmit,
|
||||
handleChange,
|
||||
resetValidity,
|
||||
};
|
||||
};
|
||||
|
||||
export default useLoginForm;
|
40
src/components/mainPageRow/MainPageRow.jsx
Normal file
@ -0,0 +1,40 @@
|
||||
import PropTypes from 'prop-types';
|
||||
import Book from './mainPageBook/MainPageBook.jsx';
|
||||
|
||||
const MainPageRow = ({ title, books }) => {
|
||||
return (
|
||||
<div className="row bg-white pb-1 rounded-3 gy-3 my-2">
|
||||
<div className="col-12 ms-2 mt-1">
|
||||
<div className="main-page-section-title block d-flex align-items-end">
|
||||
<img src={title.image} className="me-2" alt="fire" width="25" height="30" id="fire-icon" />
|
||||
<p className="main-page-section-title-text lh-1 m-0">
|
||||
{title.name}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{
|
||||
books.map((book) => {
|
||||
return book.id ? (
|
||||
<Book
|
||||
key={book.id}
|
||||
description={{
|
||||
cover: book.image,
|
||||
price: `${parseInt(book.price, 10)} ₽`,
|
||||
title: book.title,
|
||||
author: book.author,
|
||||
destination: `/pageProductСard/${book.id}`,
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
})
|
||||
}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
MainPageRow.propTypes = {
|
||||
title: PropTypes.object,
|
||||
books: PropTypes.array,
|
||||
};
|
||||
|
||||
export default MainPageRow;
|