This commit is contained in:
bulatova_karina 2024-01-15 01:15:31 +03:00
parent 426e4cd2cc
commit c310cee1fb
133 changed files with 10587 additions and 0 deletions

30
laba5/.eslintrc.cjs Normal file
View File

@ -0,0 +1,30 @@
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",
eslint: "off",
quotes: "off",
"linebreak-style": "off",
"max-len": "off",
camelcase: "off",
"comma-dangle": "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?

47
laba5/README.md Normal file
View File

@ -0,0 +1,47 @@
### Окружение:
- [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. Updating Objects in State - https://react.dev/learn/updating-objects-in-state
2. Sharing State Between Components - https://react.dev/learn/sharing-state-between-components
3. React Hot Toast - https://react-hot-toast.com
4. Axios - https://axios-http.com
5. Axios & Error handling like a boss - https://dev.to/mperon/axios-error-handling-like-a-boss-333d
6. Separation of Concerns in React How to Use Container and Presentational Components - https://www.freecodecamp.org/news/separation-of-concerns-react-container-and-presentational-components/
7. Separation of concerns in React and React Native - https://dev.to/sathishskdev/separation-of-concerns-in-react-and-react-native-45b7
8. React Bootstrap - https://react-bootstrap.netlify.app
9. React Bootstrap Icons - https://github.com/ismamz/react-bootstrap-icons
10. JSON Server - https://www.npmjs.com/package/json-server

110
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 @@
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Салон красоты</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"
}

5936
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"
}
}

3
laba5/public/favicon.svg Normal file
View 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

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

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

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: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

BIN
laba5/src/assets/nails.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,39 @@
import { Card, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import useCart from "./cart/CartHook";
const CardOfRoom = ({ name, price, image, card }) => {
const { cart, addToCart } = useCart();
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<div className="objects_in_main">
<Card>
<img src={image} className="card-img-top" alt="..." />
<div className="card-body">
<p className="card-title card_name">{name}</p>
<div className="caption_basket_price">
<p className="card-title card_price" style={{ padding: "0" }}>
{parseInt(price) + "₽"}
</p>
</div>
<div className="d-flex justify-content-center">
<Link to="/Page4" className="btn btn-sign">
Записаться
</Link>
</div>
</div>
</Card>
</div>
);
};
export default CardOfRoom;
CardOfRoom.propTypes = {
name: PropTypes.string,
info: PropTypes.string,
image: PropTypes.string,
};

View File

@ -0,0 +1,48 @@
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
const CardInShow = ({ name, image }) => {
return (
<div className="container table">
<div className="row">
<div className="col">
<Link to="/PageAdmin">
{" "}
<img src={image} className="objects_basket" alt="..." />
</Link>
</div>
<div className="col">
<div className="caption_basket">
<p className="card-title card_name">{name}</p>
</div>
</div>
<div className="col">
<div className="caption_basket_price">
<p
className="card-title card_price"
style={{ padding: "0", fontWeight: "bold" }}
>
{parseInt(item.price) + "₽"}
</p>
</div>
</div>
<div className="col">
<button
className="btn btn-primary add_object-button w-100"
type="submit"
>
Перейти к оплате
</button>
</div>
</div>
</div>
);
};
CardInShow.propTypes = {
name: PropTypes.string,
price: PropTypes.string,
image: PropTypes.string,
};
export default CardInShow;

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,73 @@
.cart-image {
/*width: 12.1rem;*/
/*padding: .25rem;*/
width: 20vh;
margin-right: 2vw;
}
.cart-item {
height: 20vh;
}
.card {
width: 17vw;
height: auto;
}
.add_to_cart{
justify-content: center;
text-align: center;
}
.align-items-center{
margin-top: 4vh;
}
.busket{
font-size: 5vh;
font-weight: lighter;
}
.card_object{
width: 50%;
}
.price_in_cart{
display: flex;
justify-content: center;
}
.item1{
border-radius: 30%;
display: flex;
justify-content: center;
}
.item2{
font-size: 4vh;
font-weight: lighter;
display: flex;
flex-direction: column;
justify-content: center;
}
.item3{
font-size: 3vh;
font-weight: lighter;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.item4{
display: flex;
align-items: center;
justify-content: center;
margin-left: 5vw;
}
.card_object_1{
margin-left: 25vw;
}
.item5{
margin-top: 5vh;
font-size: 3vh;
font-weight: lighter;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}

View File

@ -0,0 +1,118 @@
import { Button, ButtonGroup, Card } from "react-bootstrap";
import { DashLg, PlusLg, XLg } from "react-bootstrap-icons";
import Tab from "react-bootstrap/Tab";
import Tabs from "react-bootstrap/Tabs";
import imgPlaceholder from "../../assets/200.png";
import "./Cart.css";
import useCart from "./CartHook";
import Modal from "./Modal.jsx";
import { useNavigate, useParams } from "react-router-dom";
import { useState } from "react";
import { useUser } from "../types/hooks/UsersHook.js";
const Cart = () => {
const { cart, getCartSum, addToCart, removeFromCart, clearCart } = useCart();
const { tab } = useParams();
const [key, setKey] = useState(tab || "home");
const user = useUser(JSON.parse(localStorage.getItem("yohoho")));
const navigate = useNavigate();
const handlerLogOut = () => {
localStorage.setItem("yohoho", null);
navigate("/Autorization");
};
return (
<div className="d-flex flex-column align-items-left">
<div className="mb-2 col-12 col-md-8 col-lg-6 d-flex align-items-center"></div>
<div className="d-flex flex-column align-items-center">
<Tabs
defaultActiveKey="home"
id="uncontrolled-tab-example"
className="mb-3 card_object_1"
>
<Tab eventKey="home" title="Корзина">
<div className="row">
{cart.map((cartItem) => (
<div key={cartItem.id} className="col-12 mb-2 card_object_1">
<div className="card_object no-gutters">
<div className="card-body d-flex flex-row">
<div className="col-4 item1">
<img
className="cart-image"
src={cartItem.image || imgPlaceholder}
width="300"
alt="Cart Image"
/>
</div>
<div className="col-4 item2">{cartItem.type.name}</div>
{/* <div className='col-4 item3'>
{cartItem.price} * {cartItem.count}шт. = {parseFloat(cartItem.price * cartItem.count).toFixed(0)}
</div> */}
<ButtonGroup
className="mt-2 item4"
aria-label="Cart counter"
>
<Button
variant="success"
onClick={() => addToCart(cartItem)}
>
<PlusLg />
</Button>
<Button
variant="danger"
onClick={() => removeFromCart(cartItem)}
>
<DashLg />
</Button>
</ButtonGroup>
</div>
</div>
</div>
))}
</div>
<div className="item5">
<strong>Итого: {getCartSum()} &#8381;</strong>
</div>
<div className="item5">
{" "}
<Modal Clear={clearCart} />
<button
type="button"
className="btn btn-primary btn-lg"
onClick={handlerLogOut}
>
Выйти
</button>
</div>
</Tab>
<Tab eventKey="profile" title="История Заказов">
<div className="row">
{cart.map((cartItem) => (
<div key={cartItem.id} className="col-12 mb-2 card_object_1">
<div className="card_object no-gutters">
<div className="card-body d-flex flex-row">
<div className="col-4 item1">
<img
className="cart-image"
src={cartItem.image || imgPlaceholder}
width="300"
alt="Cart Image"
/>
</div>
<div className="col-4 item2">{cartItem.type.name}</div>
<div className="col-4 item3">
{cartItem.price} * {cartItem.count}шт. ={" "}
{parseFloat(cartItem.price * cartItem.count).toFixed(0)}
</div>
</div>
</div>
</div>
))}
</div>
</Tab>
</Tabs>
</div>
</div>
);
};
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,26 @@
import { useContext } from 'react';
import CartContext from './CartContext.jsx';
import { cartAdd, cartClear, cartRemove } from './CartReducer';
const useCart = () => {
const { cart, dispatch } = useContext(CartContext);
const cartSum = () => {
return parseFloat(
cart?.reduce((sum, cartItem) => {
return sum + (cartItem.price * cartItem.count);
}, 0)
?? 0,
).toFixed(2);
};
return {
cart,
getCartSum: () => cartSum(),
addToCart: (item) => dispatch(cartAdd(item)),
removeFromCart: (item) => dispatch(cartRemove(item)),
clearCart: () => dispatch(cartClear()),
};
};
export default useCart;

View File

@ -0,0 +1,71 @@
const setCartCount = (cart, item, value) => {
return cart.map((cartItem) => {
if (cartItem.id === item.id) {
return { ...cartItem, count: cartItem.count + value };
}
return cartItem;
});
};
const addToCart = (cart, item) => {
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined) {
return setCartCount(cart, item, 1);
}
return [...cart, { ...item, count: 1 }];
};
const removeFromCart = (cart, item) => {
const existsItem = cart.find((cartItem) => cartItem.id === item.id);
if (existsItem !== undefined && existsItem.count > 1) {
return setCartCount(cart, item, -1);
}
return cart.filter((cartItem) => cartItem.id !== item.id);
};
const CART_KEY = 'localCart';
const CART_ADD = 'cart/add';
const CART_REMOVE = 'cart/remove';
const CART_CLEAR = 'cart/clear';
export const saveCart = (cart) => {
localStorage.setItem(CART_KEY, JSON.stringify(cart));
};
export const loadCart = (initialValue = []) => {
const cartData = localStorage.getItem(CART_KEY);
if (cartData) {
return JSON.parse(cartData);
}
return initialValue;
};
export const cartReducer = (cart, action) => {
const { item } = action;
switch (action.type) {
case CART_ADD: {
return addToCart(cart, item);
}
case CART_REMOVE: {
return removeFromCart(cart, item);
}
case CART_CLEAR: {
return [];
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const cartAdd = (item) => ({
type: CART_ADD, item,
});
export const cartRemove = (item) => ({
type: CART_REMOVE, item,
});
export const cartClear = () => ({
type: CART_CLEAR,
});

View File

@ -0,0 +1,16 @@
import useInputValue from './Local.jsx';
const InputComponent = () => {
const input = useInputValue('');
return (
<input
type="text"
value={input.value}
onChange={input.onChange}
id='input'
/>
);
};
export default InputComponent;

View File

@ -0,0 +1,32 @@
import { useState, useEffect } from 'react';
const useInputValue = (initialValue) => {
const [value, setValue] = useState(initialValue);
// useEffect(() => {
// const storedValue = localStorage.getItem('inputValue');
// if (storedValue) {
// setValue(storedValue);
// }
// }, []);
const handleInputChange = (e) => {
setValue(e.target.value);
};
useEffect(() => {
localStorage.clear();
localStorage.setItem('inputValue', value);
}, [value]);
const ClearStor = () => {
localStorage.clear();
};
return {
value,
onChange: handleInputChange,
Clear: ClearStor,
};
};
export default useInputValue;

View File

@ -0,0 +1,47 @@
import { useState } from 'react';
import { Button } from 'react-bootstrap';
import Modal from 'react-bootstrap/Modal';
import InputComponent from './Local copy.jsx';
function Example({Clear}) {
const [show, setShow] = useState(false);
const handleClose = () => {
setShow(false);
document.getElementById('input').value = ' ';
console.log(document.getElementById('input').value);
};
const handleShow = () => setShow(true);
const Close = () =>{
handleClose();
Clear();
};
return (
<>
<Button variant="primary" onClick={handleShow}>
Оплатить
</Button>
<Modal show={show} onHide={handleClose} >
<Modal.Header closeButton>
<Modal.Title>Оплата</Modal.Title>
</Modal.Header>
<Modal.Body>
<strong className='flex-fill me-4'>Введите ваш номер телефона</strong>
<InputComponent/>
<p>Спасибо, что выбрали нас! В ближайшее время с
Вами свяжется оператор для подтверждения заказа</p> </Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Отмена
</Button>
<Button variant="primary" onClick={Close}>
Отправить
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default Example;

View File

@ -0,0 +1,29 @@
import React from "react";
import { Button } from "react-bootstrap";
// eslint-disable-next-line react/prop-types
const Pagination = ({ currentPage, totalPages, handlePageChange }) => {
return (
<div className="pagination">
<Button
className="mybutton"
onClick={() => handlePageChange(currentPage - 1)}
>
Предыдущий
</Button>
<span className="pagination-text">
Страница {currentPage} из {totalPages}
</span>
<Button
className="mybutton"
onClick={() => handlePageChange(currentPage + 1)}
>
Следующий
</Button>
</div>
);
};
export default Pagination;

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,58 @@
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="table_pageadmin">
<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>
</div>
</>
);
};
LinesForm.propTypes = {
id: PropTypes.string,
};
export default LinesForm;

View File

@ -0,0 +1,48 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useLinesItemForm2 from '../hooks/LinesItemFormHook2';
import LinesItemForm2 from './LinesItemForm2.jsx';
const LinesForm2 = ({ id }) => {
const navigate = useNavigate();
const {
item2,
validated2,
handleSubmit2,
handleChange,
} = useLinesItemForm2(id);
const onBack = () => {
navigate(-1);
};
const onSubmit = async (event) => {
if (await handleSubmit2(event)) {
onBack();
}
};
return (
<>
<Form className='m-0 p-2' noValidate validated={validated2} onSubmit={onSubmit}>
<LinesItemForm2 item={item2} 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>
</>
);
};
LinesForm2.propTypes = {
id: PropTypes.string,
};
export default LinesForm2;

View File

@ -0,0 +1,48 @@
import PropTypes from 'prop-types';
import { Button, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import useLinesItemForm3 from '../hooks/LinesItemFormHook3';
import LinesItemForm2 from './LinesItemForm2.jsx';
const LinesForm3 = ({ id }) => {
const navigate = useNavigate();
const {
item3,
validated3,
handleSubmit3,
handleChange,
} = useLinesItemForm3(id);
const onBack = () => {
navigate(-1);
};
const onSubmit = async (event) => {
if (await handleSubmit3(event)) {
onBack();
}
};
return (
<>
<Form className='m-0 p-2' noValidate validated={validated3} onSubmit={onSubmit}>
<LinesItemForm2 item={item3} 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>
</>
);
};
LinesForm3.propTypes = {
id: PropTypes.string,
};
export default LinesForm3;

View File

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

View File

@ -0,0 +1,55 @@
import PropTypes from "prop-types";
import imgPlaceholder from "../../../assets/200.png";
import Input from "../../input/Input.jsx";
import Select from "../../input/Select.jsx";
import useTypes from "../../types/hooks/TypesHook";
import "./LinesItemForm.css";
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
return (
<>
<div className="text-center">
<img
id="image-preview"
className="rounded"
alt="placeholder"
src={item.image || imgPlaceholder}
/>
</div>
<Select
values={types}
name="typeId"
label="Товары"
value={item.typeId}
onChange={handleChange}
required
/>
<Input
name="price"
label="Цена"
value={item.price}
onChange={handleChange}
type="number"
min="1000.0"
step="0.50"
required
/>
<Input
name="image"
label="Изображение"
onChange={handleChange}
type="file"
accept="image/*"
/>
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

View File

@ -0,0 +1,63 @@
import PropTypes from "prop-types";
import Input from "../../input/Input.jsx";
import "./LinesItemForm.css";
// eslint-disable-next-line react/prop-types
const LinesItemForm2 = ({ item2, handleChange }) => {
return (
<>
<Input
name="name"
label="Имя"
value={item2.name}
onChange={handleChange}
type="text"
placeholder="Введите Имя"
required
/>
<Input
name="phone"
label="Телефон"
value={item2.phone}
onChange={handleChange}
type="text"
placeholder="Введите Телефон"
required
/>
<Input
name="mail"
label="E-mail"
value={item2.mail}
onChange={handleChange}
type="text"
placeholder="Введите E-mail"
required
/>
<Input
name="date"
label="Date"
value={item2.date}
onChange={handleChange}
type="date"
placeholder="Введите дату"
required
/>
<Input
name="service"
label="Service"
value={item2.service}
onChange={handleChange}
type="text"
placeholder="Введите услугу"
required
/>
</>
);
};
LinesItemForm2.propTypes = {
item2: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm2;

View File

@ -0,0 +1,22 @@
import PropTypes from 'prop-types';
import Input from '../../input/Input.jsx';
import './LinesItemForm.css';
// eslint-disable-next-line react/prop-types
const LinesItemForm3 = ({ item, handleChange }) => {
return (
<>
<Input name='name' label='Имя' value={item.name} onChange={handleChange}
type='text' placeholder='Введите Имя' required />
<Input name='history' label='Отзыв' value={item.history} onChange={handleChange}
type='text' placeholder='Введите Отзыв' required />
</>
);
};
LinesItemForm3.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm3;

View File

@ -0,0 +1,6 @@
const getRandomColor = () => {
const colors = ['#98A2F7', '#EF844C', '#F1D454']; // Add more colors if needed
const randomIndex = Math.floor(Math.random() * colors.length);
return colors[randomIndex];
};
export default getRandomColor;

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,34 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import useModal from '../../modal/ModalHook';
import LinesApiService2 from '../service/LinesApiService2';
const useLinesDeleteModal2 = (linesChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const showModalDialog = (id) => {
showModal();
setCurrentId(id);
};
const onClose = () => {
hideModal();
};
const onDelete = async () => {
await LinesApiService2.delete(currentId);
linesChangeHandle();
toast.success('Элемент успешно удален', { id: 'LinesTable' });
onClose();
};
return {
isDeleteModalShow2: isModalShow,
showDeleteModal2: showModalDialog,
handleDeleteConfirm2: onDelete,
handleDeleteCancel2: onClose,
};
};
export default useLinesDeleteModal2;

View File

@ -0,0 +1,34 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import useModal from '../../modal/ModalHook';
import LinesApiService3 from '../service/LinesApiService3';
const useLinesDeleteModal2 = (linesChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const showModalDialog = (id) => {
showModal();
setCurrentId(id);
};
const onClose = () => {
hideModal();
};
const onDelete = async () => {
await LinesApiService3.delete(currentId);
linesChangeHandle();
toast.success('Элемент успешно удален', { id: 'LinesTable' });
onClose();
};
return {
isDeleteModalShow3: isModalShow,
showDeleteModal3: showModalDialog,
handleDeleteConfirm3: onDelete,
handleDeleteCancel3: onClose,
};
};
export default useLinesDeleteModal2;

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,75 @@
import { useState } from 'react';
import useModal from '../../modal/ModalHook';
import useLinesItemForm2 from './LinesItemFormHook2';
import CursApiService2 from '../../types/service/CursApiService2';
const useLinesFormModal2 = (linesChangeHandle) => {
const { showModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const { resetValidity } = useLinesItemForm2(currentId, linesChangeHandle);
const showModalDialog = async (id) => {
setCurrentId(id);
resetValidity();
showModal();
alert(`Modal for ID ${id} is shown!`);
// eslint-disable-next-line react-hooks/rules-of-hooks
const [validated, setValidated] = useState(false);
// eslint-disable-next-line react-hooks/rules-of-hooks
const [lines2] = useState([]);
// eslint-disable-next-line react-hooks/rules-of-hooks
const [lines4, setLines4] = useState([]);
const handleSubmit = async (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
setValidated(true);
if (form.checkValidity()) {
const userData = {
phone: lines2[0]?.phone,
name: lines2[0]?.name,
mail: lines2[0]?.mail,
};
console.log('Отправка данных:', userData);
try {
await CursApiService2.create(userData);
console.log('Регистрация успешна!');
const updatedUsers = await CursApiService2.getAll();
setLines4(updatedUsers.map((user) => ({
name: user.typeName,
phone: user.phoneNumber,
mail: user.typeEmailX2,
id: user.id,
})));
} catch (error) {
console.error('Ошибка при регистрации:', error);
}
}
};
// Возвращаем объект с нужными функциями и состояниями
return {
validated,
lines4,
handleSubmit,
};
};
return {
showFormModal2: showModalDialog,
};
};
export default useLinesFormModal2;

View File

@ -0,0 +1,45 @@
import { useState } from 'react';
import useModal from '../../modal/ModalHook';
import useLinesItemForm3 from './LinesItemFormHook3';
const useLinesFormModal3 = (linesChangeHandle) => {
const { isModalShow, showModal, hideModal } = useModal();
const [currentId, setCurrentId] = useState(0);
const {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
} = useLinesItemForm3(currentId, linesChangeHandle);
const showModalDialog = (id) => {
setCurrentId(id);
resetValidity();
showModal();
};
const onClose = () => {
setCurrentId(-1);
hideModal();
};
const onSubmit = async (event) => {
if (await handleSubmit(event)) {
onClose();
}
};
return {
isFormModalShow3: isModalShow,
isFormValidated3: validated,
showFormModal3: showModalDialog,
currentItem3: item,
handleItemChange3: handleChange,
handleFormSubmit3: onSubmit,
handleFormClose3: onClose,
};
};
export default useLinesFormModal3;

View File

@ -0,0 +1,29 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLines = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
let expand = '?_expand=type';
if (typeFilter) {
expand = `${expand}&typeId=${typeFilter}`;
}
const data = await LinesApiService.getAll(expand);
setLines(data ?? []);
};
useEffect(() => {
getLines();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [linesRefresh, typeFilter]);
return {
lines,
handleLinesChange,
};
};
export default useLines;

View File

@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
import LinesApiService2 from '../service/LinesApiService2';
const useLines2 = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines2, setLines2] = useState([]);
const handleLinesChange2 = () => setLinesRefresh(!linesRefresh);
const getLines2 = async () => {
const expand = '?_expand=lines2';
const data = await LinesApiService2.getAll(expand);
setLines2(data ?? []);
};
useEffect(() => {
getLines2();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [linesRefresh, typeFilter]);
return {
lines2,
handleLinesChange2,
};
};
export default useLines2;

View File

@ -0,0 +1,26 @@
import { useEffect, useState } from 'react';
import LinesApiService3 from '../service/LinesApiService3';
const useLines3 = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines3, setLines3] = useState([]);
const handleLinesChange3 = () => setLinesRefresh(!linesRefresh);
const getLines3 = async () => {
const expand = '?_expand=lines3';
const data = await LinesApiService3.getAll(expand);
setLines3(data ?? []);
};
useEffect(() => {
getLines3();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [linesRefresh, typeFilter]);
return {
lines3,
handleLinesChange3,
};
};
export default useLines3;

View File

@ -0,0 +1,80 @@
import { useState } from "react";
import toast from "react-hot-toast";
import getBase64FromFile from "../../utils/Base64";
import LinesApiService from "../service/LinesApiService";
import useLinesItem from "./LinesItemHook";
const useLinesItemForm = (id, linesChangeHandle) => {
const { item, setItem } = useLinesItem(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
const typeId = parseInt(formData.typeId, 10);
const price = parseFloat(formData.price).toFixed(2);
const image = formData.image.startsWith("data:image") ? formData.image : "";
return {
typeId: typeId.toString(),
price: price.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,67 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import LinesApiService2 from '../service/LinesApiService2';
import useLinesItem2 from './LinesItemHook2';
const useLinesItemForm2 = (id, linesChangeHandle2) => {
const { item, setItem } = useLinesItem2(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
if (!formData || typeof formData !== 'object') {
console.error('Invalid formData');
return null; // or handle the error accordingly
}
const { name } = formData;
const { phone } = formData;
const { mail } = formData;
return {
name: name.toString(),
phone: phone.toString(),
mail: mail.toString(),
};
};
const handleChange = (event) => {
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 LinesApiService2.create(body);
} else {
await LinesApiService2.update(id, body);
}
if (linesChangeHandle2) linesChangeHandle2();
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemForm2;

View File

@ -0,0 +1,65 @@
import { useState } from 'react';
import toast from 'react-hot-toast';
import LinesApiService3 from '../service/LinesApiService3';
import useLinesItem3 from './LinesItemHook3';
const useLinesItemForm3 = (id, linesChangeHandle3) => {
const { item, setItem } = useLinesItem3(id);
const [validated, setValidated] = useState(false);
const resetValidity = () => {
setValidated(false);
};
const getLineObject = (formData) => {
if (!formData || typeof formData !== 'object') {
console.error('Invalid formData');
return null; // or handle the error accordingly
}
const { name } = formData;
const { history } = formData;
return {
name: name.toString(),
history: history.toString(),
};
};
const handleChange = (event) => {
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 LinesApiService3.create(body);
} else {
await LinesApiService3.update(id, body);
}
if (linesChangeHandle3) linesChangeHandle3();
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemForm3;

View File

@ -0,0 +1,33 @@
import { useEffect, useState } from "react";
import LinesApiService from "../service/LinesApiService";
const useLinesItem = (id) => {
const emptyItem = {
id: "",
typeId: "",
price: "0",
image: "",
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useLinesItem;

View File

@ -0,0 +1,33 @@
import { useEffect, useState } from 'react';
import LinesApiService2 from '../service/LinesApiService2';
const useLinesItem2 = (id) => {
const emptyItem = {
id: '',
name: '',
phone: '',
mail: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService2.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useLinesItem2;

View File

@ -0,0 +1,32 @@
import { useEffect, useState } from 'react';
import LinesApiService3 from '../service/LinesApiService3';
const useLinesItem3 = (id) => {
const emptyItem = {
id: '',
name: '',
history: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService3.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useLinesItem3;

View File

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

View File

@ -0,0 +1,5 @@
import ApiService from "../../api/ApiService";
const LinesApiService2 = new ApiService("lines2");
export default LinesApiService2;

View File

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

View File

@ -0,0 +1,11 @@
import LinesTableRow from "./LinesTableRowForCatalog.jsx";
const Lines = () => {
return (
<>
<LinesTableRow />
</>
);
};
export default Lines;

View File

@ -0,0 +1,178 @@
import { Button, ButtonGroup } from "react-bootstrap";
import Select from "../../input/Select.jsx";
import ModalConfirm from "../../modal/ModalConfirm.jsx";
import ModalForm from "../../modal/ModalForm.jsx";
import ModalForm2 from "../../modal/ModalForm2.jsx";
import LinesItemForm from "../form/LinesItemForm.jsx";
import LinesItemForm3 from "../form/LinesItemForm3.jsx";
import useLinesDeleteModal from "../hooks/LinesDeleteModalHook";
import useLinesDeleteModal2 from "../hooks/LinesDeleteModalHook2";
import useLinesDeleteModal3 from "../hooks/LinesDeleteModalHook3";
import useTypeFilter from "../hooks/LinesFilterHook";
import useLinesFormModal from "../hooks/LinesFormModalHook";
import useLinesFormModal2 from "../hooks/LinesFormModalHook2";
import useLinesFormModal3 from "../hooks/LinesFormModalHook3";
import useLines from "../hooks/LinesHook";
import useLines2 from "../hooks/LinesHook2";
import useLines3 from "../hooks/LinesHook3";
import LinesTable from "./LinesTable.jsx";
import LinesTable3 from "./LinesTable3.jsx";
import LinesTable2 from "./LinesTable2.jsx";
import LinesTableRow from "./LinesTableRow.jsx";
import LinesTableRow3 from "./LinesTableRow3.jsx";
import LinesTableRow2 from "./LinesTableRow2.jsx";
const Lines = () => {
const { types, currentFilter, handleFilterChange } = useTypeFilter();
const { lines, handleLinesChange } = useLines(currentFilter);
const { lines2, handleLinesChange2 } = useLines2(currentFilter);
const { lines3, handleLinesChange3 } = useLines3(currentFilter);
const {
isDeleteModalShow,
showDeleteModal,
handleDeleteConfirm,
handleDeleteCancel,
} = useLinesDeleteModal(handleLinesChange);
const {
isDeleteModalShow2,
showDeleteModal2,
handleDeleteConfirm2,
handleDeleteCancel2,
} = useLinesDeleteModal2(handleLinesChange2);
const {
isDeleteModalShow3,
showDeleteModal3,
handleDeleteConfirm3,
handleDeleteCancel3,
} = useLinesDeleteModal3(handleLinesChange3);
const {
isFormModalShow,
isFormValidated,
showFormModal,
currentItem,
handleItemChange,
handleFormSubmit,
handleFormClose,
} = useLinesFormModal(handleLinesChange);
const {
isFormModalShow3,
isFormValidated3,
showFormModal3,
currentItem3,
handleItemChange3,
handleFormSubmit3,
handleFormClose3,
} = useLinesFormModal3(handleLinesChange3);
const { showFormModal2 } = useLinesFormModal2(handleLinesChange2);
return (
<>
<div className="PageEditContainer">
<div className="content">
<ButtonGroup>
<Button variant="info" onClick={() => showFormModal()}>
Добавить товар (диалог)
</Button>
</ButtonGroup>
</div>
<Select
className="mt-2"
values={types}
label="Фильтр по товарам"
value={currentFilter}
onChange={handleFilterChange}
/>
<LinesTable>
{lines.map((line, index) => (
<LinesTableRow
key={line.id}
index={index}
line={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>
<h4>Заявки</h4>
</div>
<LinesTable2>
{lines2.map((line, index) => (
<LinesTableRow2
key={line.id}
index={index}
line={line}
onDelete={() => showDeleteModal2(line.id)}
onEdit={() => showFormModal2(line.id)}
/>
))}
</LinesTable2>
<ModalConfirm
show={isDeleteModalShow2}
onConfirm={handleDeleteConfirm2}
onClose={handleDeleteCancel2}
title="Удаление"
message="Удалить элемент?"
/>
<div>
<h4>Отзывы</h4>
</div>
<LinesTable3>
{lines3.map((line, index) => (
<LinesTableRow3
key={line.id}
index={index}
line={line}
onDelete={() => showDeleteModal3(line.id)}
onEdit={() => showFormModal3(line.id)}
/>
))}
</LinesTable3>
<ModalConfirm
show={isDeleteModalShow3}
onConfirm={handleDeleteConfirm3}
onClose={handleDeleteCancel3}
title="Удаление"
message="Удалить элемент?"
/>
<ModalForm2
show={isFormModalShow3}
validated={isFormValidated3}
onSubmit={handleFormSubmit3}
onClose={handleFormClose3}
title="Редактирование"
>
<LinesItemForm3
item={currentItem3}
handleChange={handleItemChange3}
/>
</ModalForm2>
</div>
</>
);
};
export default Lines;

View File

@ -0,0 +1,30 @@
import PropTypes from "prop-types";
import { Table } from "react-bootstrap";
import "../../../index.css";
const LinesTable = ({ children }) => {
return (
<Table className="lines_table mt-2" striped responsive>
<thead>
<tr>
<th scope="col"></th>
<th scope="col" className="w-25">
Товар
</th>
<th scope="col" className="w-25">
Цена
</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>{children}</tbody>
</Table>
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,37 @@
import PropTypes from "prop-types";
import { Table } from "react-bootstrap";
const LinesTable2 = ({ children }) => {
return (
<Table className="mt-2" striped tesponsive="true">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col" className="w-25">
ФИО
</th>
<th scope="col" className="w-25">
Номер телефона
</th>
<th scope="col" className="w-25">
Почта
</th>
<th scope="col" className="w-25">
Дата записи
</th>
<th scope="col" className="w-25">
Услуга
</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>{children}</tbody>
</Table>
);
};
LinesTable2.propTypes = {
children: PropTypes.node,
};
export default LinesTable2;

View File

@ -0,0 +1,29 @@
import PropTypes from "prop-types";
import { Table } from "react-bootstrap";
const LinesTable3 = ({ children }) => {
return (
<Table className="mt-2" striped tesponsive="true">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col" className="w-25">
Имя пользователя
</th>
<th scope="col" className="w-25">
Отзыв
</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>{children}</tbody>
</Table>
);
};
LinesTable3.propTypes = {
children: PropTypes.node,
};
export default LinesTable3;

View File

@ -0,0 +1,23 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<Table className='mt-2' striped bordered hover variant>
<thead>
<tr>
</tr>
</thead>
<tbody>
{children}
</tbody>
</Table >
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

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

View File

@ -0,0 +1,34 @@
import PropTypes from "prop-types";
import { XCircle } from "react-bootstrap-icons";
const LinesTableRow2 = ({ index, line, onDelete }) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.name}</td>
<td>{line.phone}</td>
<td>{line.mail}</td>
<td>{line.date}</td>
<td>{line.service}</td>
<td>
<a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}>
<XCircle style={{ color: "red" }} />
</a>
</td>
</tr>
);
};
LinesTableRow2.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onEdit: PropTypes.func,
};
export default LinesTableRow2;

View File

@ -0,0 +1,30 @@
import PropTypes from 'prop-types';
import { PencilFill, Trash3 } from 'react-bootstrap-icons';
const LinesTableRow3 = ({
index, line, onDelete, onEdit,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.name}</td>
<td>{line.history}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEdit)}><PencilFill /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr>
);
};
LinesTableRow3.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onEdit: PropTypes.func,
};
export default LinesTableRow3;

View File

@ -0,0 +1,47 @@
import PropTypes from "prop-types";
import { Row } from "react-bootstrap";
import CardOfRoom from "../../Card.jsx";
import useLines from "../hooks/LinesHook";
import useTypeFilter from "../hooks/LinesFilterHook";
import Select from "../../input/Select.jsx";
const LinesTableRow = () => {
const { types, currentFilter, handleFilterChange } = useTypeFilter();
const { lines } = useLines(currentFilter);
function allCards() {
return lines.map((card) => (
<CardOfRoom
key={card.id}
name={card.type.name}
price={card.price}
image={card.image}
card={card}
/>
));
}
return (
<>
<Select
className="col-2 mt-0 mb-4 mx-4 ms-auto"
values={types}
label="Фильтр по товарам"
value={currentFilter}
onChange={handleFilterChange}
/>
<div className="container main_pannel ">
<div id="catalog">
<Row className="justify-content-start objects_card">{allCards()}</Row>
</div>
</div>
</>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onAddCart: 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,47 @@
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="primary"
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,60 @@
import PropTypes from 'prop-types';
import { useState } from 'react';
import {
Button, Form, Modal, Alert,
} from 'react-bootstrap';
import { createPortal } from 'react-dom';
import './Modal.css';
const ModalForm = ({
show, title, validated, onSubmit, onClose, children,
}) => {
const [showAlert, setShowAlert] = useState(false);
const showFormModal3WithAlert = () => {
setShowAlert(true);
setTimeout(() => {
setShowAlert(false);
}, 3000);
};
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' onClick={() => showFormModal3WithAlert()} className='col-5 m-0 ms-2' type='submit'>
Сохранить
</Button>
</Modal.Footer>
{showAlert && (
<Alert variant="success" onClose={() => setShowAlert(false)} dismissible>
Отзыв успешно добавлен!
</Alert>
)}
</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,14 @@
.my-navbar {
background-color: #775860 !important;
font-size: 20px;
backdrop-filter: blur(30px);
}
.my-navbar .link a:hover {
text-decoration: underline !important;
}
.my-navbar-brand {
font-size: 25px;
text-align: center;
}

View File

@ -0,0 +1,54 @@
import PropTypes from "prop-types";
import { Container, Nav, Navbar } from "react-bootstrap";
import { Link, useLocation } from "react-router-dom";
import "./Navigation.css";
const Navigation = ({ routes }) => {
const location = useLocation();
const indexPageLink = routes.filter((route) => route.index === false).shift();
return (
<header>
<div className="NavigationClass">
<Navbar
expand="md"
bg="dark"
data-bs-theme="dark"
className="my-navbar"
>
<Container fluid>
<Navbar.Brand as={Link} to={indexPageLink?.path ?? "/"}>
Тяжелый люкс
</Navbar.Brand>
<Navbar.Toggle aria-controls="main-navbar" />
<Navbar.Collapse id="main-navbar">
<Nav className="me-auto link" activeKey={location.pathname}>
<Nav.Link as={Link} to="/Page2">
Услуги
</Nav.Link>
<Nav.Link as={Link} to="/Page3">
О нас
</Nav.Link>
<Nav.Link as={Link} to="/Page6">
Отзывы
</Nav.Link>
<Nav.Link as={Link} to="/Page4">
Связаться с нами
</Nav.Link>
<Nav.Link as={Link} to="/PageEdit">
Режим администратора
</Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
</div>
</header>
);
};
Navigation.propTypes = {
routes: PropTypes.array,
};
export default Navigation;

View 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="table_pageadmin">
<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>
</div>
</>
);
};
LinesForm.propTypes = {
id: PropTypes.string,
};
export default LinesForm;

View File

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

View File

@ -0,0 +1,34 @@
import PropTypes from 'prop-types';
import imgPlaceholder from '../../../assets/200.png';
import Input from '../../input/Input.jsx';
import Select from '../../input/Select.jsx';
import useTypes from '../../types/hooks/TypesHook';
import './LinesItemForm.css';
const LinesItemForm = ({ item, handleChange }) => {
const { types } = useTypes();
return (
<>
<div className='text-center'>
<img id='image-preview' className='rounded' alt='placeholder'
src={item.image || imgPlaceholder} />
</div>
<Select values={types} name='typeId' label='Товары' value={item.typeId} onChange={handleChange}
required />
<Input name='price' label='Цена' value={item.price} onChange={handleChange}
type='number' min='1000.0' step='0.50' required />
<Input name='count' label='Количество' value={item.count} onChange={handleChange}
type='number' min='1' step='1' required />
<Input name='image' label='Изображение' onChange={handleChange}
type='file' accept='image/*' />
</>
);
};
LinesItemForm.propTypes = {
item: PropTypes.object,
handleChange: PropTypes.func,
};
export default LinesItemForm;

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,29 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLines = (typeFilter) => {
const [linesRefresh, setLinesRefresh] = useState(false);
const [lines, setLines] = useState([]);
const handleLinesChange = () => setLinesRefresh(!linesRefresh);
const getLines = async () => {
let expand = '?_expand=type';
if (typeFilter) {
expand = `${expand}&typeId=${typeFilter}`;
}
const data = await LinesApiService.getAll(expand);
setLines(data ?? []);
};
useEffect(() => {
getLines();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [linesRefresh, typeFilter]);
return {
lines,
handleLinesChange,
};
};
export default useLines;

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 typeId = parseInt(formData.typeId, 10);
const price = parseFloat(formData.price).toFixed(2);
const count = parseInt(formData.count, 10);
const sum = parseFloat(price * count).toFixed(2);
const image = formData.image.startsWith('data:image') ? formData.image : '';
return {
typeId: typeId.toString(),
price: price.toString(),
count: count.toString(),
sum: sum.toString(),
image,
};
};
const handleImageChange = async (event) => {
const { files } = event.target;
const file = await getBase64FromFile(files.item(0));
setItem({
...item,
image: file,
});
};
const handleChange = (event) => {
if (event.target.type === 'file') {
handleImageChange(event);
return;
}
const inputName = event.target.name;
const inputValue = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
setItem({
...item,
[inputName]: inputValue,
});
};
const handleSubmit = async (event) => {
const form = event.currentTarget;
event.preventDefault();
event.stopPropagation();
const body = getLineObject(item);
if (form.checkValidity()) {
if (id === undefined) {
await LinesApiService.create(body);
} else {
await LinesApiService.update(id, body);
}
if (linesChangeHandle) linesChangeHandle();
toast.success('Элемент успешно сохранен', { id: 'LinesTable' });
return true;
}
setValidated(true);
return false;
};
return {
item,
validated,
handleSubmit,
handleChange,
resetValidity,
};
};
export default useLinesItemForm;

View File

@ -0,0 +1,34 @@
import { useEffect, useState } from 'react';
import LinesApiService from '../service/LinesApiService';
const useLinesItem = (id) => {
const emptyItem = {
id: '',
typeId: '',
price: '0',
count: '0',
image: '',
};
const [item, setItem] = useState({ ...emptyItem });
const getItem = async (itemId = undefined) => {
if (itemId && itemId > 0) {
const data = await LinesApiService.get(itemId);
setItem(data);
} else {
setItem({ ...emptyItem });
}
};
useEffect(() => {
getItem(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);
return {
item,
setItem,
};
};
export default useLinesItem;

View File

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

View File

@ -0,0 +1,12 @@
import LinesTableRow from './LinesTableRowForCatalog.jsx';
const Lines = () => {
return (
<>
<h4> <i> Клубника в шоколаде</i></h4>
<LinesTableRow />
</>
);
};
export default Lines;

View File

@ -0,0 +1,84 @@
import { Button, ButtonGroup } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
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 navigate = useNavigate();
const showEditPage = (id) => {
navigate(`/PageAdmin/${id}`);
};
return (
<>
<div className="PageEditContainer">
<div className="content">
<ButtonGroup>
<Button variant='info' onClick={() => showFormModal()}>
Добавить товар (диалог)
</Button>
<Button as={Link} to='/page-edit' variant='success'>
Добавить товар (страница)
</Button>
</ButtonGroup>
</div>
<Select className='mt-2' values={types} label='Фильтр по товарам'
value={currentFilter} onChange={handleFilterChange} />
<LinesTable>
{
lines.map((line, index) =>
<LinesTableRow key={line.id}
index={index} line={line}
onDelete={() => showDeleteModal(line.id)}
onEdit={() => showFormModal(line.id)}
onEditInPage={() => showEditPage(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,31 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
import '../../../index.css';
const LinesTable = ({ children }) => {
return (
<Table className='lines_table mt-2' striped responsive>
<thead>
<tr>
<th scope='col'></th>
<th scope='col' className='w-25'>Товар</th>
<th scope='col' className='w-25'>Цена</th>
<th scope='col' className='w-25'>Колич.</th>
<th scope='col' className='w-25'>Сумма</th>
<th scope='col'></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,23 @@
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
const LinesTable = ({ children }) => {
return (
<Table className='mt-2' striped bordered hover variant>
<thead>
<tr>
</tr>
</thead>
<tbody>
{children}
</tbody>
</Table >
);
};
LinesTable.propTypes = {
children: PropTypes.node,
};
export default LinesTable;

View File

@ -0,0 +1,34 @@
import PropTypes from 'prop-types';
import { PencilFill, PencilSquare, Trash3 } from 'react-bootstrap-icons';
const LinesTableRow = ({
index, line, onDelete, onEdit, onEditInPage,
}) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
return (
<tr>
<th scope="row">{index + 1}</th>
<td>{line.type.name}</td>
<td>{parseFloat(line.price).toFixed(2)}</td>
<td>{line.count}</td>
<td>{parseFloat(line.sum).toFixed(2)}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEdit)}><PencilFill /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onDelete: PropTypes.func,
onEdit: PropTypes.func,
onEditInPage: PropTypes.func,
};
export default LinesTableRow;

View File

@ -0,0 +1,35 @@
import PropTypes from 'prop-types';
import { Row } from 'react-bootstrap';
import CardOfRoom from '../../Card.jsx';
import useLines from '../hooks/LinesHook';
const LinesTableRow = () => {
const { lines } = useLines();
function allCards() {
return lines.map((card) =>
<CardOfRoom key={card.id}
name={card.type.name}
price={card.price} image={card.image} card={card} />)
}
return (
<>
<div className="container main_pannel ">
<h1>Клубника в шоколаде</h1>
<div id="catalog">
<Row className="justify-content-start objects_card">
{allCards()}
</Row>
</div>
</div>
</>
);
};
LinesTableRow.propTypes = {
index: PropTypes.number,
line: PropTypes.object,
onAddCart: PropTypes.func,
};
export default LinesTableRow;

Some files were not shown because too many files have changed in this diff Show More