This commit is contained in:
2025-05-24 11:06:40 +04:00
parent f4a1992f8d
commit 600eb67f5a
10 changed files with 586 additions and 97 deletions

View File

@@ -1,8 +1,11 @@
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import CatalogPage from './pages/CatalogPage';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import BasketPage from './pages/BasketPage';
import { Route, BrowserRouter as Router, Routes } from 'react-router-dom';
import CatalogPage from './pages/CatalogPage';
import DiscountsPage from './pages/DiscountsPage';
import HomePage from './pages/HomePage';
import ContactUsPage from './pages/ContactUsPage';
function App() {
return (
@@ -10,6 +13,9 @@ function App() {
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/catalog" element={<CatalogPage />} />
<Route path="/discounts" element={<DiscountsPage />} />
<Route path="/basket" element={<BasketPage />} />
<Route path="/contact" element={<ContactUsPage />} />
</Routes>
</Router>
);

View File

@@ -1,34 +1,70 @@
import React from 'react';
import { Link } from 'react-router-dom';
const Navbar = ({ cartCount }) => {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div className="container">
<Link className="navbar-brand d-flex align-items-center" to="/">
<img src="/logo.png" alt="Логотип" className="logo me-2" />
<span className="d-none d-lg-block">Книжный магазин "Тома"</span>
<span className="d-lg-none">"Тома"</span>
</Link>
<div className="collapse navbar-collapse" id="navbarContent">
<ul className="navbar-nav ms-auto">
<li className="nav-item">
<Link className="nav-link" to="/">Главная страница</Link>
<Link className="nav-link" to="/catalog">Каталог</Link>
</li>
<li className="nav-item">
<Link className="nav-link position-relative" to="/cart">
<i className="bi bi-cart3"></i>
<span className="cart-count badge bg-danger rounded-pill position-absolute top-0 start-100 translate-middle">
0
</span>
</Link>
</li>
</ul>
</div>
</div>
</nav>
);
<nav className="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div className="container">
<Link className="navbar-brand d-flex align-items-center" to="/">
<img src="/logo.png" alt="Логотип" className="logo me-2" />
<span className="d-none d-lg-block">Книжный магазин "Тома"</span>
<span className="d-lg-none">"Тома"</span>
</Link>
{/* Кнопка для мобильного меню */}
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbarContent"
aria-controls="navbarContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
{/* Основное меню */}
<div className="collapse navbar-collapse" id="navbarContent">
<ul className="navbar-nav ms-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link className="nav-link" to="/">Главная страница</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/catalog">Каталог</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/discounts">Скидки</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/contact">Связаться с нами</Link>
</li>
<li className="nav-item d-lg-none">
<Link className="nav-link position-relative" to="/basket">
<i className="bi bi-cart3 me-1"></i> Корзина
{cartCount > 0 && (
<span className="cart-count badge bg-danger rounded-pill position-absolute top-0 start-100 translate-middle">
{cartCount}
</span>
)}
</Link>
</li>
</ul>
{/* Иконка корзины для десктопной версии */}
<div className="d-none d-lg-block ms-3">
<Link className="nav-link position-relative" to="/basket">
<i className="bi bi-cart3 fs-5"></i>
{cartCount > 0 && (
<span className="cart-count badge bg-danger rounded-pill position-absolute top-0 start-100 translate-middle">
{cartCount}
</span>
)}
</Link>
</div>
</div>
</div>
</nav>
);
};
export default Navbar;

View File

@@ -91,27 +91,18 @@
"image": "images/foundation.jpg",
"genreId": 2,
"id": 7
},
{
"title": "рл",
"author": "л",
"genreId": 3,
"price": 2,
"description": "иоио",
"image": "https://u.9111s.ru/uploads/202308/21/7a16d872540b76031e7dbc7590bc6c1b.png",
"id": 10
}
],
"cart": [
{
"bookId": 1,
"quantity": 1,
"id": 2
"bookId": 2,
"quantity": 2,
"id": 1
},
{
"bookId": 10,
"quantity": 1,
"id": 3
"bookId": 1,
"quantity": 4,
"id": 2
}
]
}

View File

@@ -0,0 +1,206 @@
import { useEffect, useState } from 'react';
import { Alert, Button, Card, Col, Row, Spinner } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import Footer from '../components/Footer';
import Navbar from '../components/Navbar';
import api from '../services/api';
const BasketPage = () => {
const [cartItems, setCartItems] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
useEffect(() => {
loadCart();
}, []);
const loadCart = async () => {
try {
setLoading(true);
const response = await api.fetchCartItems();
const items = response.data;
setCartItems(items);
const newTotal = items.reduce((sum, item) => {
return sum + (item.book?.price || 0) * (item.quantity || 1);
}, 0);
setTotal(newTotal);
} catch (error) {
console.error('Ошибка загрузки корзины:', error);
} finally {
setLoading(false);
}
};
const handleQuantityChange = async (id, quantity) => {
if (quantity < 1) return;
try {
await api.updateCartItem(id, { quantity });
// Оптимизация: обновляем локальное состояние вместо полной перезагрузки
setCartItems(prevItems =>
prevItems.map(item =>
item.id === id ? { ...item, quantity } : item
)
);
// Пересчитываем итоговую сумму
setCartItems(prevItems => {
const newTotal = prevItems.reduce((sum, item) => {
return sum + (item.book?.price || 0) * (item.quantity || 1);
}, 0);
setTotal(newTotal);
return prevItems;
});
} catch (error) {
console.error('Ошибка обновления количества:', error);
}
};
const handleRemoveItem = async (id) => {
try {
await api.removeFromCart(id);
// Оптимизация: обновляем локальное состояние
setCartItems(prevItems => prevItems.filter(item => item.id !== id));
// Пересчитываем итоговую сумму
setCartItems(prevItems => {
const newTotal = prevItems.reduce((sum, item) => {
return sum + (item.book?.price || 0) * (item.quantity || 1);
}, 0);
setTotal(newTotal);
return prevItems;
});
} catch (error) {
console.error('Ошибка удаления из корзины:', error);
}
};
const handleClearCart = async () => {
if (window.confirm("Вы уверены, что хотите очистить корзину?")) {
try {
await api.clearCart();
setCartItems([]);
setTotal(0);
} catch (error) {
console.error('Ошибка очистки корзины:', error);
}
}
};
const handleCheckout = async () => {
try {
await api.clearCart();
setCartItems([]);
setTotal(0);
alert("Заказ оформлен! Спасибо за покупку!");
} catch (error) {
console.error('Ошибка оформления заказа:', error);
}
};
if (loading) {
return (
<div className="d-flex justify-content-center align-items-center vh-100">
<Spinner animation="border" variant="primary" />
</div>
);
}
return (
<div className="basket-page">
<Navbar cartCount={cartItems.reduce((sum, item) => sum + (item.quantity || 0), 0)} />
<main className="container mt-5 pt-5">
<Row className="justify-content-center">
<Col lg={10}>
<h2 className="text-center mb-4">Ваша корзина</h2>
{cartItems.length === 0 ? (
<Alert variant="info">Корзина пуста</Alert>
) : (
<>
<div className="cart-items">
{cartItems.map(item => (
<Card key={item.id} className="mb-3">
<Card.Body>
<Row className="align-items-center">
<Col md={2}>
<img
src={item.book?.image || "images/default-book.jpg"}
alt={item.book?.title || "Без названия"}
className="img-fluid rounded"
onError={(e) => { e.target.src = 'images/default-book.jpg' }}
/>
</Col>
<Col md={6}>
<h5>{item.book?.title || "Без названия"}</h5>
<p className="text-muted">{item.book?.author || "Автор не указан"}</p>
<p>
Цена: {item.book?.price || 0} руб. × {item.quantity || 1} =
{(item.book?.price || 0) * (item.quantity || 1)} руб.
</p>
</Col>
<Col md={2}>
<input
type="number"
min="1"
value={item.quantity || 1}
onChange={(e) => handleQuantityChange(item.id, parseInt(e.target.value))}
className="form-control cart-item-quantity"
/>
</Col>
<Col md={2} className="text-center">
<Button
variant="outline-danger"
onClick={() => handleRemoveItem(item.id)}
>
Удалить
</Button>
</Col>
</Row>
</Card.Body>
</Card>
))}
</div>
<Card className="mb-4 border-danger">
<Card.Body>
<div className="d-flex justify-content-between align-items-center">
<h4 className="mb-0">Общая стоимость:</h4>
<h4 className="mb-0">{total} руб.</h4>
</div>
</Card.Body>
</Card>
<div className="d-flex justify-content-between mb-5">
<Link to="/catalog" className="btn btn-outline-primary">
Продолжить покупки
</Link>
<div>
<Button
variant="outline-danger"
className="me-2"
onClick={handleClearCart}
>
Очистить корзину
</Button>
<Button
variant="success"
className="px-4"
onClick={handleCheckout}
>
Оформить заказ
</Button>
</div>
</div>
</>
)}
</Col>
</Row>
</main>
<Footer />
</div>
);
};
export default BasketPage;

View File

@@ -1,6 +1,5 @@
import { useEffect, useState } from 'react';
import { Button, Container, Row } from 'react-bootstrap';
import { BiPlusCircle } from 'react-icons/bi';
import { Button, Container, Row, Spinner } from 'react-bootstrap';
import BookComponent from '../components/BookComponent';
import BookModal from '../components/BookModal';
import CartModal from '../components/CartModal';
@@ -17,38 +16,43 @@ const CatalogPage = () => {
const [showCartModal, setShowCartModal] = useState(false);
const [currentBookId, setCurrentBookId] = useState(null);
const [cartCount, setCartCount] = useState(0);
const [loading, setLoading] = useState(true);
useEffect(() => {
loadData();
updateCartCount();
const fetchData = async () => {
try {
setLoading(true);
const [genresResponse, booksResponse, cartResponse] = await Promise.all([
api.fetchGenres(),
api.fetchBooks(),
api.fetchCartItems()
]);
setGenres(genresResponse.data);
setBooks(booksResponse.data);
setCartCount(cartResponse.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
} catch (error) {
console.error('Ошибка загрузки данных:', error);
} finally {
setLoading(false);
}
};
fetchData();
}, []);
// Функция для фильтрации жанров с книгами
const getGenresWithBooks = () => {
return genres.filter(genre =>
books.some(book => book.genreId === genre.id)
);
};
const loadData = async () => {
// Оптимизированная функция для обновления состояния
const updateState = async () => {
try {
const genresResponse = await api.fetchGenres();
setGenres(genresResponse.data);
const booksResponse = await api.fetchBooks();
const [booksResponse, cartResponse] = await Promise.all([
api.fetchBooks(),
api.fetchCartItems()
]);
setBooks(booksResponse.data);
setCartCount(cartResponse.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
} catch (error) {
console.error('Ошибка загрузки данных:', error);
}
};
const updateCartCount = async () => {
try {
const response = await api.fetchCartItems();
const totalItems = response.data.reduce((sum, item) => sum + (item.quantity || 0), 0);
setCartCount(totalItems);
} catch (error) {
console.error('Ошибка обновления счетчика корзины:', error);
console.error('Ошибка обновления данных:', error);
}
};
@@ -66,7 +70,7 @@ const CatalogPage = () => {
if (window.confirm('Вы уверены, что хотите удалить эту книгу?')) {
try {
await api.deleteBook(id);
loadData();
await updateState();
} catch (error) {
console.error('Ошибка удаления книги:', error);
}
@@ -75,12 +79,22 @@ const CatalogPage = () => {
const handleAddToCart = async (bookId) => {
try {
await api.addToCart(bookId);
updateCartCount();
alert('Книга добавлена в корзину!');
// Проверяем, есть ли уже эта книга в корзине
const cartResponse = await api.fetchCartItems();
const existingItem = cartResponse.data.find(item => item.bookId === bookId);
if (existingItem) {
await api.updateCartItemQuantity(existingItem.id, existingItem.quantity + 1);
} else {
await api.addToCart(bookId);
}
// Обновляем счетчик корзины
const updatedCart = await api.fetchCartItems();
setCartCount(updatedCart.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
} catch (error) {
console.error('Ошибка добавления в корзину:', error);
alert('Не удалось добавить книгу в корзину');
}
};
@@ -91,35 +105,31 @@ const CatalogPage = () => {
} else {
await api.createBook(bookData);
}
loadData();
await updateState();
setShowBookModal(false);
} catch (error) {
console.error('Ошибка сохранения книги:', error);
alert('Не удалось сохранить книгу');
}
};
const handleSaveGenre = async (genreData) => {
try {
await api.createGenre(genreData);
loadData();
const genresResponse = await api.fetchGenres();
setGenres(genresResponse.data);
setShowGenreModal(false);
alert('Жанр успешно добавлен!');
} catch (error) {
console.error('Ошибка сохранения жанра:', error);
alert('Не удалось сохранить жанр');
}
};
const handleCheckout = async () => {
try {
await api.clearCart();
updateCartCount();
setCartCount(0);
setShowCartModal(false);
alert('Заказ оформлен! Спасибо за покупку!');
} catch (error) {
console.error('Ошибка оформления заказа:', error);
alert('Не удалось оформить заказ');
}
};
@@ -127,6 +137,18 @@ const CatalogPage = () => {
return books.filter(book => book.genreId === genreId);
};
const genresWithBooks = genres.filter(genre =>
books.some(book => book.genreId === genre.id)
);
if (loading) {
return (
<div className="d-flex justify-content-center align-items-center vh-100">
<Spinner animation="border" variant="primary" />
</div>
);
}
return (
<div className="catalog-page">
<Navbar cartCount={cartCount} onShowCart={() => setShowCartModal(true)} />
@@ -138,19 +160,19 @@ const CatalogPage = () => {
<div className="d-flex justify-content-between mb-4">
<div>
<Button variant="success" onClick={handleAddBook}>
<BiPlusCircle /> Добавить книгу
Добавить книгу
</Button>
<Button
variant="primary"
className="ms-2"
onClick={() => setShowGenreModal(true)}
>
<BiPlusCircle /> Добавить жанр
Добавить жанр
</Button>
</div>
</div>
{getGenresWithBooks().map(genre => (
{genresWithBooks.map(genre => (
<section key={genre.id} className="mb-5">
<div className="genre-title bg-light p-3 rounded text-center mb-4">
<h3>{genre.name}</h3>
@@ -173,7 +195,6 @@ const CatalogPage = () => {
<Footer />
{/* Модальные окна */}
<BookModal
show={showBookModal}
onHide={() => setShowBookModal(false)}

View File

@@ -0,0 +1,123 @@
import { useState } from 'react';
import { Container, Form, Button, Card } from 'react-bootstrap';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
const ContactUsPage = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
purchaseCode: '',
problemDescription: ''
});
const [validated, setValidated] = useState(false);
const handleChange = (e) => {
const { id, value } = e.target;
setFormData(prev => ({
...prev,
[id]: value
}));
};
const handleSubmit = (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
} else {
// Здесь можно добавить логику отправки формы
console.log('Форма отправлена:', formData);
alert('Ваше сообщение отправлено! Мы свяжемся с вами в ближайшее время.');
setFormData({
name: '',
email: '',
purchaseCode: '',
problemDescription: ''
});
}
setValidated(true);
};
return (
<div className="contact-page">
<Navbar />
<main className="container mt-5 pt-5">
<section className="my-5">
<div className="row justify-content-center">
<div className="col-lg-8">
<h2 className="text-center mb-4">Свяжитесь с нами</h2>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Form.Group className="mb-3" controlId="name">
<Form.Label>Имя</Form.Label>
<Form.Control
type="text"
value={formData.name}
onChange={handleChange}
required
/>
<Form.Control.Feedback type="invalid">
Пожалуйста, введите ваше имя.
</Form.Control.Feedback>
</Form.Group>
<Form.Group className="mb-3" controlId="email">
<Form.Label>Электронная почта</Form.Label>
<Form.Control
type="email"
value={formData.email}
onChange={handleChange}
required
/>
<Form.Control.Feedback type="invalid">
Пожалуйста, введите корректный email.
</Form.Control.Feedback>
</Form.Group>
<Form.Group className="mb-3" controlId="purchaseCode">
<Form.Label>Код покупки (если есть)</Form.Label>
<Form.Control
type="text"
value={formData.purchaseCode}
onChange={handleChange}
/>
</Form.Group>
<Form.Group className="mb-3" controlId="problemDescription">
<Form.Label>Описание проблемы</Form.Label>
<Form.Control
as="textarea"
rows={6}
value={formData.problemDescription}
onChange={handleChange}
required
/>
<Form.Control.Feedback type="invalid">
Пожалуйста, опишите вашу проблему.
</Form.Control.Feedback>
</Form.Group>
<div className="text-center">
<Button variant="primary" size="lg" type="submit">
Отправить
</Button>
</div>
</Form>
</div>
</div>
</section>
</main>
<Footer />
</div>
);
};
export default ContactUsPage;

View File

@@ -0,0 +1,107 @@
import React from 'react';
import { Container, Row, Col, Card, Button, Alert } from 'react-bootstrap';
import { BiCart } from 'react-icons/bi';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
const DiscountsPage = () => {
const discountedBooks = [
{
id: 1,
title: "Девушка с татуировкой дракона",
author: "Стиг Ларссон",
image: "images/the_girl_with_the_dragon_tattoo.jpg",
originalPrice: 700,
discountPrice: 525,
discountPercent: 25
},
{
id: 2,
title: "Хоббит",
author: "Дж.Р.Р. Толкин",
image: "images/the_hobbit.webp",
originalPrice: 750,
discountPrice: 563,
discountPercent: 25
},
{
id: 3,
title: "Дюна",
author: "Фрэнк Герберт",
image: "images/dune.jpg",
originalPrice: 500,
discountPrice: 375,
discountPercent: 25
}
];
const handleAddToCart = (bookId) => {
// Логика добавления в корзину
alert(`Книга ${bookId} добавлена в корзину`);
};
return (
<div className="discounts-page">
<Navbar cartCount={0} />
<main className="container mt-5 pt-5">
<section className="my-5">
<h2 className="text-center mb-4">Скидки</h2>
<hr className="mb-4" />
<Row className="g-4 justify-content-center">
{discountedBooks.map(book => (
<Col key={book.id} md={6} lg={4}>
<Card className="h-100 border-0 shadow-sm">
<Card.Img
variant="top"
src={book.image}
className="p-3"
alt={book.title}
onError={(e) => { e.target.src = 'images/default-book.jpg' }}
/>
<Card.Body className="text-center d-flex flex-column">
<Card.Title>{book.title}</Card.Title>
<Card.Text>{book.author}</Card.Text>
<Card.Text className="text-muted">
<s>{book.originalPrice} р.</s>
</Card.Text>
<Card.Text className="text-danger fs-4 fw-bold">
{book.discountPrice} р.
</Card.Text>
<Card.Text className="small text-muted">
Экономия {book.originalPrice - book.discountPrice} р. ({book.discountPercent}%)
</Card.Text>
<Button
variant="primary"
className="mt-2"
onClick={() => handleAddToCart(book.id)}
>
<BiCart /> В корзину
</Button>
</Card.Body>
</Card>
</Col>
))}
</Row>
<hr className="my-4" />
<Alert variant="success" className="text-center">
<h3>Условия получения скидки:</h3>
<p className="lead mb-0">
При покупке трех книг одновременно Вы получаете скидку 25%!<br />
Скидка действует с 1 по 15 число каждого месяца. Не упустите возможность!
</p>
</Alert>
</section>
</main>
<Footer />
</div>
);
};
export default DiscountsPage;

View File

@@ -1,10 +1,9 @@
import React from 'react';
import { Container, Row, Col, Card, Button } from 'react-bootstrap';
import { BiCart } from 'react-icons/bi';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import { Button, Card, Col, Row } from 'react-bootstrap';
import { BiCart } from 'react-icons/bi';
import Footer from '../components/Footer';
import Navbar from '../components/Navbar';
const HomePage = () => {
const bestsellers = [

View File

@@ -1,4 +1,3 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import axios from "axios";
const API_URL = "http://localhost:3001";
@@ -21,9 +20,10 @@ export default {
addToCart: (bookId) => axios.post(`${API_URL}/cart`, { bookId, quantity: 1 }),
getCartItemByBookId: (bookId) => axios.get(`${API_URL}/cart?bookId=${bookId}`),
updateCartItem: (id, data) => axios.patch(`${API_URL}/cart/${id}`, data),
updateCartItemQuantity: (id, quantity) => axios.patch(`${API_URL}/cart/${id}`, { quantity }),
removeFromCart: (id) => axios.delete(`${API_URL}/cart/${id}`),
clearCart: () =>
axios.get(`${API_URL}/cart`).then((response) => {
return Promise.all(response.data.map((item) => axios.delete(`${API_URL}/cart/${item.id}`)));
}),
axios
.get(`${API_URL}/cart`)
.then((response) => Promise.all(response.data.map((item) => axios.delete(`${API_URL}/cart/${item.id}`)))),
};