This commit is contained in:
Вячеслав Иванов 2023-12-18 23:55:12 +04:00
parent a8937930eb
commit 9cf636b347
20 changed files with 403 additions and 583 deletions

File diff suppressed because one or more lines are too long

View File

@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/logo.png" href="src/Images/logo.png" /> <link rel="icon" type="image/logo.png" href="src/Images/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Каталог</title> <title>Pizza Shop</title>
</head> </head>
<body> <body>
<div id="root" class="h-100 d-flex flex-column"></div> <div id="root" class="h-100 d-flex flex-column"></div>

View File

@ -4,16 +4,19 @@ import { Toaster } from 'react-hot-toast';
import { Outlet } from 'react-router-dom'; import { Outlet } from 'react-router-dom';
import Footer from './components/footer/Footer.jsx'; import Footer from './components/footer/Footer.jsx';
import Navigation from './components/navigation/Navigation.jsx'; import Navigation from './components/navigation/Navigation.jsx';
import { CartProvider } from './components/card/CartContext.jsx';
const App = ({ routes }) => { const App = ({ routes }) => {
return ( return (
<div className="d-flex flex-column min-vh-100"> <div className="d-flex flex-column min-vh-100">
<CartProvider>
<Navigation routes={routes}></Navigation> <Navigation routes={routes}></Navigation>
<Container className="flex-grow-1 p-2" as="main" fluid> <Container className="flex-grow-1 p-2" as="main" fluid>
<Outlet /> <Outlet />
</Container> </Container>
<Footer /> <Footer />
<Toaster position='top-center' reverseOrder={true} /> <Toaster position='top-center' reverseOrder={true} />
</CartProvider>
</div> </div>
); );
}; };

View File

@ -0,0 +1,85 @@
import { Button, ButtonGroup, Card, Col, Row, Form, Container } from 'react-bootstrap';
import { DashLg, PlusLg, XLg } from 'react-bootstrap-icons';
import imgPlaceholder from 'D:/Файлы/УлГТУ/3 семестр/ИП/lab5/src/Images/200.png';
import useCart from './cartHook';
import { Link } from 'react-router-dom';
const Cart = () => {
const {
cart,
getCartSum,
addToCart,
removeFromCart,
clearCart,
} = useCart();
const handleQuantityChange = (cartItem, event) => {
const newQuantity = parseInt(event.target.value, 10);
addToCart({ ...cartItem, count: newQuantity });
};
return (
<Container>
<Row>
<Col className="d-flex justify-content-center align-items-center">
<h1 className="text-warning font-weight-bold">Корзина</h1>
</Col>
</Row>
<Row>
<Col>
<strong className='d-flex justify-content-center mb-2'>
<Button variant='danger' onClick={() => clearCart()}>
<XLg /> Очистить
</Button>
</strong>
{cart.map((cartItem) => (
<Card key={cartItem.id} className='rounded-3 mb-4'>
<Card.Body className='p-4'>
<Row className="d-flex justify-content-between align-items-center">
<Col md={2} lg={2} xl={2}>
<img src={cartItem.image || imgPlaceholder} alt="Cart Image" className="img-fluid rounded-3" />
</Col>
<Col md={3} lg={3} xl={3}>
<p className="lead fw-normal mb-2">{cartItem.typeId}</p>
</Col>
<Col md={4} lg={4} xl={3} className="d-flex align-items-center">
<ButtonGroup className="w-100 align-items-center" aria-label="Cart counter">
<Button variant="link" onClick={() => addToCart(cartItem)}>
<PlusLg />
</Button>
<Form.Control
id={`quantity-${cartItem.id}`}
min="0"
name="quantity"
value={cartItem.count}
type="number"
className="form-control form-control-sm text-center"
onChange={(e) => handleQuantityChange(cartItem, e)}
/>
<Button variant="link" onClick={() => removeFromCart(cartItem)}>
<DashLg />
</Button>
</ButtonGroup>
</Col>
<Col md={3} lg={2} xl={2}>
<h5 className="mb-0">{parseFloat(cartItem.price * cartItem.count).toFixed(2)} </h5>
</Col>
</Row>
</Card.Body>
</Card>
))}
<div className='d-flex justify-content-between mb-2'>
<strong>Итого: {getCartSum()} </strong>
</div>
{getCartSum() > 0 && (
<Link to='/MakingAnOrder' className="btn btn-warning">
К оплате
</Link>
)}
</Col>
</Row>
</Container>
);
};
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

@ -1,20 +1,36 @@
import { Col, Card, Button } from 'react-bootstrap'; import { Col, Card, Button } from 'react-bootstrap';
import PropTypes from 'prop-types';
const ProductCard = ({ line, onAddCart }) => {
const handleAnchorClick = (event, action) => {
event.preventDefault();
action();
};
const ProductCard = () => {
return ( return (
<Col lg={3} md={4} sm={6} xs={12} className="mb-4"> <Col lg={3} md={4} sm={6} xs={12} className="mb-4">
<Card> <Card>
<Card.Img src="./src/Images/pizza.png" alt="Product Image" className="card-img-top" /> <Card.Img src={line.image || "./src/Images/200.png"} alt="Product Image" className="card-img-top" />
<Card.Body> <Card.Body>
<Card.Title>Название</Card.Title> <Card.Title>{line.typeId}</Card.Title>
</Card.Body> </Card.Body>
<Card.Footer> <Card.Footer>
<div className="text-warning font-weight-bold">Цена </div> <div className="text-warning font-weight-bold">Цена {line.price} </div>
<Button variant="warning">В корзину</Button> <Button variant="warning" onClick={(event) => handleAnchorClick(event, onAddCart)}>В корзину</Button>
</Card.Footer> </Card.Footer>
</Card> </Card>
</Col> </Col>
); );
}; };
ProductCard.propTypes = {
line: PropTypes.shape({
image: PropTypes.string,
typeId: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
}).isRequired,
onAddCart: PropTypes.func,
};
export default ProductCard; export default ProductCard;

View File

@ -1,21 +1,39 @@
import { Col, Card } from 'react-bootstrap'; import { Col, Card } from 'react-bootstrap';
import PropTypes from 'prop-types';
import useTypes from '../types/hooks/TypesHook';
const StockCard = ({ stock, lines }) => {
const { typesById } = useTypes();
const StockCard = () => {
return ( return (
<Col lg={4} md={6} sm={12} className="mb-4"> <Col lg={4} md={6} sm={12} className="mb-4">
<Card> <Card>
<Card.Img src="./src/Images/stock.png" alt="Stock Image" className="card-img-top" /> <Card.Img src="./src/Images/stock.png" alt="Stock Image" className="card-img-top" />
<Card.Body> <Card.Body>
<Card.Title>Дарим кибер-призы</Card.Title> <Card.Title>{stock.name}</Card.Title>
<Card.Text> <Card.Text>
Вот так ачивка! Закажите Кибер-комбо и получите доступ к играм от MY.GAMES, а еще кокосовый батончик и Размер акции: {stock.value}
шоколадное печенье «Cyber» от Bite. А также станьте автоматическим участником розыгрыша игровых ключей и
больших пицц 29 июня.
</Card.Text> </Card.Text>
{lines && (
<Card.Text>
Акция применена к товару: {typesById[lines.find(line => line.stock === stock.value)?.typeId]}
</Card.Text>
)}
</Card.Body> </Card.Body>
</Card> </Card>
</Col> </Col>
); );
}; };
StockCard.propTypes = {
stock: PropTypes.shape({
name: PropTypes.string,
value: PropTypes.string.isRequired,
}).isRequired,
lines: PropTypes.oneOfType([
PropTypes.object,
PropTypes.arrayOf(PropTypes.object),
]),
};
export default StockCard; export default StockCard;

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

@ -11,6 +11,7 @@ import LinesTableRow from './LinesTableRow.jsx';
import StocksTable from './StocksTable.jsx'; import StocksTable from './StocksTable.jsx';
import StocksTableRow from './StocksTableRow.jsx'; import StocksTableRow from './StocksTableRow.jsx';
import useStocks from '../hooks/StocksHook.js'; import useStocks from '../hooks/StocksHook.js';
import useCart from '../../card/cartHook.js';
const Lines = () => { const Lines = () => {
const { types, currentFilter, handleFilterChange } = useTypeFilter(); const { types, currentFilter, handleFilterChange } = useTypeFilter();
@ -48,6 +49,8 @@ const Lines = () => {
showDeleteModalStock(id); showDeleteModalStock(id);
}; };
const { addToCart } = useCart();
return ( return (
<> <>
<h1 className="text-warning text-center font-weight-bold">Панель администратора</h1> <h1 className="text-warning text-center font-weight-bold">Панель администратора</h1>
@ -69,6 +72,7 @@ const Lines = () => {
lines.map((line, index) => lines.map((line, index) =>
<LinesTableRow key={line.id} <LinesTableRow key={line.id}
index={index} line={line} index={index} line={line}
onAddCart={() => addToCart(line)}
onDelete={() => handleDelete(line.id)} onDelete={() => handleDelete(line.id)}
onEditInPage={() => showEditPage(line.id)} onEditInPage={() => showEditPage(line.id)}
/>) />)

View File

@ -1,8 +1,8 @@
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { PencilSquare, Trash3 } from 'react-bootstrap-icons'; import { Cart, PencilSquare, Trash3 } from 'react-bootstrap-icons';
const LinesTableRow = ({ const LinesTableRow = ({
index, line, onDelete, onEditInPage, index, line, onAddCart, onDelete, onEditInPage,
}) => { }) => {
const handleAnchorClick = (event, action) => { const handleAnchorClick = (event, action) => {
event.preventDefault(); event.preventDefault();
@ -17,6 +17,7 @@ const LinesTableRow = ({
<td>{line.stock}</td> <td>{line.stock}</td>
<td>{line.count}</td> <td>{line.count}</td>
<td>{parseFloat(line.sum).toFixed(2)}</td> <td>{parseFloat(line.sum).toFixed(2)}</td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onAddCart)}><Cart /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a></td> <td><a href="#" onClick={(event) => handleAnchorClick(event, onEditInPage)}><PencilSquare /></a></td>
<td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td> <td><a href="#" onClick={(event) => handleAnchorClick(event, onDelete)}><Trash3 /></a></td>
</tr> </tr>
@ -26,6 +27,7 @@ const LinesTableRow = ({
LinesTableRow.propTypes = { LinesTableRow.propTypes = {
index: PropTypes.number, index: PropTypes.number,
line: PropTypes.object, line: PropTypes.object,
onAddCart: PropTypes.func,
onDelete: PropTypes.func, onDelete: PropTypes.func,
onEditInPage: PropTypes.func, onEditInPage: PropTypes.func,
}; };

View File

@ -3,8 +3,11 @@ import { Container, Nav, Navbar, Button } from 'react-bootstrap';
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
import Image from 'react-bootstrap/Image'; import Image from 'react-bootstrap/Image';
import './Navigation.css'; import './Navigation.css';
import { Cart2 } from 'react-bootstrap-icons';
import useCart from '../card/cartHook';
const Navigation = ({ routes }) => { const Navigation = ({ routes }) => {
const { getCartSum } = useCart();
const location = useLocation(); const location = useLocation();
const indexPageLink = routes.find((route) => route.index === true); const indexPageLink = routes.find((route) => route.index === true);
const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title')); const pages = routes.filter((route) => Object.prototype.hasOwnProperty.call(route, 'title'));
@ -25,11 +28,11 @@ const Navigation = ({ routes }) => {
))} ))}
</Nav> </Nav>
<Nav> <Nav>
<Button className="custom-btn" as={Link} to="/personalAccountLogin"> <Button className="custom-btn" as={Link} to={localStorage.getItem('nameOfUser') ? "/personalAccount" : "/personalAccountLogin"}>
Войти {localStorage.getItem('nameOfUser') ? localStorage.getItem('nameOfUser') : "Войти"}
</Button> </Button>
<Button variant="warning" as={Link} to="/Basket"> <Button variant="warning" as={Link} to="/Basket">
Корзина <Cart2 className='d-inline-block align-top me-1 logo' /> {getCartSum() ?? ''} &#8381;
</Button> </Button>
</Nav> </Nav>
</Navbar.Collapse> </Navbar.Collapse>

View File

@ -15,6 +15,10 @@ const useTypes = () => {
return { return {
types, types,
typesById: types.reduce((acc, type) => {
acc[type.id] = type.name;
return acc;
}, {}),
}; };
}; };

View File

@ -13,10 +13,10 @@ import PersonalAccount from './pages/PersonalAccount.jsx';
import PersonalAccountRegister from './pages/PersonalAccountRegister.jsx'; import PersonalAccountRegister from './pages/PersonalAccountRegister.jsx';
import PasswordRecovery from './pages/PasswordRecovery.jsx'; import PasswordRecovery from './pages/PasswordRecovery.jsx';
import Administrator from './pages/Administrator.jsx'; import Administrator from './pages/Administrator.jsx';
import Basket from './pages/Basket.jsx';
import MakingAnOrder from './pages/MakingAnOrder.jsx'; import MakingAnOrder from './pages/MakingAnOrder.jsx';
import PageEdit from './pages/PageEdit.jsx'; import PageEdit from './pages/PageEdit.jsx';
import PageEditStocks from './pages/PageEditStocs.jsx'; import PageEditStocks from './pages/PageEditStocs.jsx';
import CartPage from './pages/CartPage.jsx';
const routes = [ const routes = [
{ {
@ -57,7 +57,7 @@ const routes = [
}, },
{ {
path: '/Basket', path: '/Basket',
element: <Basket/>, element: <CartPage/>,
}, },
{ {
path: '/MakingAnOrder', path: '/MakingAnOrder',

View File

@ -0,0 +1,10 @@
import Cart from "../components/card/Cart.jsx";
const CartPage = () => {
return (
<Cart />
);
};
export default CartPage;

View File

@ -1,7 +1,34 @@
import { Container, Row, Col } from 'react-bootstrap'; import { Container, Row, Col } from 'react-bootstrap';
import ProductCard from '../components/card/ProductCard'; import ProductCard from '../components/card/ProductCard';
import { useEffect, useState } from 'react';
import LinesApiService from '../components/lines/service/LinesApiService';
import useTypes from '../components/types/hooks/TypesHook';
import useCart from '../components/card/cartHook';
const Index = () => { const Index = () => {
const { typesById } = useTypes();
const [lines, setLines] = useState([]);
useEffect(() => {
LinesApiService.getAll()
.then(data => {
const mappedLines = data.map((item, index) => ({
typeId: typesById[item.typeId] || 'Тип не найден',
price: parseFloat(item.price),
image: item.image,
id: index + 1,
}));
setLines(mappedLines);
})
.catch(error => {
console.error('Error fetching data from LinesApiService:', error);
});
}, [typesById]);
const { addToCart } = useCart();
return ( return (
<Container> <Container>
<Row> <Row>
@ -10,30 +37,10 @@ const Index = () => {
</Col> </Col>
</Row> </Row>
<Row> <Row>
<ProductCard /> {lines.map(line => (
<ProductCard /> <ProductCard key={line.id} line={line}
<ProductCard /> onAddCart={() => addToCart(line)}/>
<ProductCard /> ))}
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
<ProductCard />
</Row> </Row>
</Container> </Container>
); );

View File

@ -1,4 +1,4 @@
import { useState } from 'react'; import { useEffect, useState } from 'react';
import { Container, Row, Col, Card, Form, Button } from 'react-bootstrap'; import { Container, Row, Col, Card, Form, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
@ -15,6 +15,21 @@ const PersonalAccount = () => {
setValidated(true); setValidated(true);
}; };
const [name, setName] = useState('');
useEffect(() => {
const storedName = localStorage.getItem('nameOfUser');
if (storedName) {
setName(storedName);
}
}, []);
const handleLogout = () => {
localStorage.removeItem('nameOfUser');
history.push('/');
};
return ( return (
<Container className="h-100"> <Container className="h-100">
<Row className="justify-content-center align-items-center h-100"> <Row className="justify-content-center align-items-center h-100">
@ -26,7 +41,7 @@ const PersonalAccount = () => {
<Form noValidate validated={validated} onSubmit={handleSubmit}> <Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-4" controlId="name"> <Form.Group className="mb-4" controlId="name">
<Form.Label>Ваше имя</Form.Label> <Form.Label>Ваше имя</Form.Label>
<Form.Control type="text" required /> <Form.Control type="text" value={name} required onChange={(e) => setName(e.target.value)} />
<Form.Control.Feedback>Имя заполнено</Form.Control.Feedback> <Form.Control.Feedback>Имя заполнено</Form.Control.Feedback>
<Form.Control.Feedback type="invalid">Имя не заполнено</Form.Control.Feedback> <Form.Control.Feedback type="invalid">Имя не заполнено</Form.Control.Feedback>
</Form.Group> </Form.Group>
@ -66,7 +81,7 @@ const PersonalAccount = () => {
</div> </div>
<div className="d-flex justify-content-center mt-2"> <div className="d-flex justify-content-center mt-2">
<Link to='/' className="btn btn-outline-danger" type="button"> <Link className="btn btn-outline-danger" type="button" onClick={handleLogout} to="/">
Выйти Выйти
</Link> </Link>
</div> </div>

View File

@ -15,6 +15,10 @@ const PersonalAccountRegister = () => {
setValidated(true); setValidated(true);
}; };
function setNameOfUser(name) {
localStorage.setItem('nameOfUser', name);
}
return ( return (
<Container className="h-100"> <Container className="h-100">
<Row className="justify-content-center align-items-center h-100"> <Row className="justify-content-center align-items-center h-100">
@ -65,7 +69,7 @@ const PersonalAccountRegister = () => {
<div className="d-flex justify-content-center"> <div className="d-flex justify-content-center">
<Link to='/PersonalAccount' style={{color: 'black', textDecoration: 'none'}}> <Link to='/PersonalAccount' style={{color: 'black', textDecoration: 'none'}}>
<Button variant="success" type="button" className="btn-block btn-warning text-body mb-0"> <Button variant="success" type="button" className="btn-block btn-warning text-body mb-0" onClick={() => setNameOfUser(document.getElementById('name').value)}>
Регистрация Регистрация
</Button> </Button>
</Link> </Link>

View File

@ -1,7 +1,32 @@
import { Container, Row, Col } from 'react-bootstrap'; import { Container, Row, Col } from 'react-bootstrap';
import { useEffect, useState } from 'react';
import StocksApiService from '../components/lines/service/StocksApiService.js'
import StockCard from '../components/card/StockCard'; import StockCard from '../components/card/StockCard';
import LinesApiService from '../components/lines/service/LinesApiService.js';
const Stock = () => { const Stock = () => {
const [stocks, setStocks] = useState([]);
const [lines, setLines] = useState([]);
useEffect(() => {
StocksApiService.getAll()
.then(data => {
setStocks(data);
})
.catch(error => {
console.error('Error fetching data from StockApiService:', error);
});
LinesApiService.getAll()
.then(data => {
setLines(data);
})
.catch(error => {
console.error('Error fetching data from LinesApiService:', error);
});
}, []);
const filteredStocks = stocks.slice(1);
return ( return (
<Container> <Container>
<Row> <Row>
@ -10,25 +35,9 @@ const Stock = () => {
</Col> </Col>
</Row> </Row>
<Row> <Row>
<StockCard /> {filteredStocks.map(stock => (
<StockCard /> <StockCard key={stock.id} stock={stock} lines={lines} />
<StockCard /> ))}
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
<StockCard />
</Row> </Row>
</Container> </Container>
); );

Binary file not shown.