2 Commits

Author SHA1 Message Date
6994c92de0 Новый отчёт 2025-05-28 15:38:06 +04:00
a6f201cffe Удаление старого отчёта 2025-05-28 15:37:32 +04:00
75 changed files with 1526 additions and 9791 deletions

14
.vscode/launch.json vendored
View File

@@ -1,14 +0,0 @@
{
"configurations": [
{
"type": "java",
"name": "Spring Boot-ServerApplication<server>",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.server.ServerApplication",
"projectName": "server",
"args": "",
"envFile": "${workspaceFolder}/.env"
}
]
}

54
.vscode/settings.json vendored
View File

@@ -1,54 +0,0 @@
{
"files.autoSave": "onFocusChange",
"files.eol": "\n",
"editor.detectIndentation": false,
"editor.formatOnType": false,
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.sortImports": "explicit"
},
"editor.snippetSuggestions": "bottom",
"debug.toolBarLocation": "commandCenter",
"debug.showVariableTypes": true,
"errorLens.gutterIconsEnabled": true,
"errorLens.messageEnabled": false,
"prettier.tabWidth": 4,
"prettier.singleQuote": false,
"prettier.printWidth": 120,
"prettier.trailingComma": "es5",
"prettier.useTabs": false,
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"java.compile.nullAnalysis.mode": "automatic",
"java.configuration.updateBuildConfiguration": "automatic",
"[java]": {
"editor.pasteAs.enabled": false,
"editor.codeActionsOnSave": {
"source.organizeImports": "never",
"source.sortImports": "explicit"
}
},
"gradle.nestedProjects": true,
"java.saveActions.organizeImports": true,
"java.dependency.packagePresentation": "hierarchical",
"java.codeGeneration.hashCodeEquals.useJava7Objects": true,
"spring-boot.ls.problem.boot2.JAVA_CONSTRUCTOR_PARAMETER_INJECTION": "WARNING",
"spring.initializr.defaultLanguage": "Java"
}

View File

@@ -1,14 +1,18 @@
{
"configurations": [
{
"type": "java",
"name": "Spring Boot-ServerApplication<server>",
"type": "chrome",
"name": "Debug",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.server.ServerApplication",
"projectName": "server",
"args": "",
"envFile": "${workspaceFolder}/.env"
"url": "http://localhost:5173"
},
{
"type": "node",
"name": "Start",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": ["run-script", "start"],
"console": "integratedTerminal"
}
]
}

View File

@@ -35,9 +35,5 @@
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"java.configuration.updateBuildConfiguration": "interactive",
"java.compile.nullAnalysis.mode": "automatic",
"java.import.gradle.buildServer.enabled": false,
"java.import.gradle.enabled": true
}
}

View File

@@ -31,23 +31,23 @@ const BookComponent = ({ book, onEdit, onDelete, onAddToCart }) => {
{displayPrice}
</Card.Text>
<div>
<Button
variant="primary"
className="me-2 mb-2"
<Button
variant="primary"
className="me-2 mb-2"
onClick={() => onAddToCart(book.id)}
>
<BiCart /> В корзину
</Button>
<Button
variant="outline-secondary"
className="me-2 mb-2"
<Button
variant="outline-secondary"
className="me-2 mb-2"
onClick={() => onEdit(book.id)}
>
<BiEdit /> Редактировать
</Button>
<Button
variant="outline-danger"
className="mb-2"
<Button
variant="outline-danger"
className="mb-2"
onClick={() => onDelete(book.id)}
>
<BiTrash /> Удалить

View File

@@ -14,22 +14,18 @@ const BookModal = ({ show, onHide, bookId, genres, onSave }) => {
useEffect(() => {
if (bookId) {
// Загружаем данные книги для редактирования
api.fetchBook(bookId).then(response => {
const book = response.data;
setFormData({
title: book.title || '',
author: book.author || '',
genreId: book.genre?.id || genres[0]?.id || '',
price: book.price || '',
description: book.description || '',
image: book.image || ''
title: book.title,
author: book.author,
genreId: book.genreId,
price: book.price,
description: book.description,
image: book.image?.replace('images/', '') || ''
});
}).catch(error => {
console.error('Ошибка загрузки книги:', error);
});
} else {
// Сбрасываем форму для новой книги
setFormData({
title: '',
author: '',
@@ -39,69 +35,55 @@ const BookModal = ({ show, onHide, bookId, genres, onSave }) => {
image: ''
});
}
}, [bookId, genres, show]); // Добавил show в зависимости
}, [bookId, genres]);
const handleSubmit = (e) => {
e.preventDefault();
const bookData = {
...formData,
price: Number(formData.price) || 0,
price: Number(formData.price),
genreId: Number(formData.genreId),
// Убираем автоматическое добавление 'images/' - сохраняем как есть
image: formData.image
image: formData.image.startsWith('http')
? formData.image
: `images/${formData.image}`
};
onSave(bookData);
};
const handleClose = () => {
setFormData({
title: '',
author: '',
genreId: '',
price: '',
description: '',
image: ''
});
onHide();
};
return (
<Modal show={show} onHide={handleClose} size="lg">
<Modal show={show} onHide={onHide} size="lg">
<Modal.Header closeButton>
<Modal.Title>{bookId ? 'Редактировать книгу' : 'Добавить книгу'}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Название книги *</Form.Label>
<Form.Label>Название книги</Form.Label>
<Form.Control
type="text"
value={formData.title}
onChange={(e) => setFormData({...formData, title: e.target.value})}
required
placeholder="Введите название книги"
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Автор *</Form.Label>
<Form.Label>Автор</Form.Label>
<Form.Control
type="text"
value={formData.author}
onChange={(e) => setFormData({...formData, author: e.target.value})}
required
placeholder="Введите автора"
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Жанр *</Form.Label>
<Form.Label>Жанр</Form.Label>
<Form.Select
value={formData.genreId}
onChange={(e) => setFormData({...formData, genreId: e.target.value})}
required
>
<option value="">Выберите жанр</option>
{genres.map(genre => (
<option key={genre.id} value={genre.id}>{genre.name}</option>
))}
@@ -109,27 +91,24 @@ const BookModal = ({ show, onHide, bookId, genres, onSave }) => {
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Цена *</Form.Label>
<Form.Label>Цена</Form.Label>
<Form.Control
type="number"
value={formData.price}
onChange={(e) => setFormData({...formData, price: e.target.value})}
required
min="0"
step="1"
placeholder="0"
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Описание *</Form.Label>
<Form.Label>Описание</Form.Label>
<Form.Control
as="textarea"
rows={3}
value={formData.description}
onChange={(e) => setFormData({...formData, description: e.target.value})}
required
placeholder="Введите описание книги"
/>
</Form.Group>
@@ -139,18 +118,17 @@ const BookModal = ({ show, onHide, bookId, genres, onSave }) => {
type="text"
value={formData.image}
onChange={(e) => setFormData({...formData, image: e.target.value})}
placeholder="URL изображения или путь к файлу"
placeholder="Имя файла (например, book.jpg) или полный URL"
required
/>
<Form.Text className="text-muted">
Можно указать полный URL (https://...) или относительный путь (images/book.jpg)
Можно указать имя файла из папки images (например, "book.jpg") или полный URL изображения
</Form.Text>
</Form.Group>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>Отмена</Button>
<Button variant="primary" type="submit">
{bookId ? 'Обновить' : 'Добавить'}
</Button>
<Button variant="secondary" onClick={onHide}>Отмена</Button>
<Button variant="primary" type="submit">Сохранить</Button>
</Modal.Footer>
</Form>
</Modal.Body>

View File

@@ -1,12 +1,11 @@
import React, { useState, useEffect } from 'react';
import { Modal, Button, Card, Form, Alert } from 'react-bootstrap';
import { Modal, Button, Card, Form } from 'react-bootstrap';
import { BiTrash } from 'react-icons/bi';
import api from '../services/api';
const CartModal = ({ show, onHide, onCheckout }) => {
const [cartItems, setCartItems] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (show) {
@@ -16,29 +15,25 @@ const CartModal = ({ show, onHide, onCheckout }) => {
const loadCart = async () => {
try {
setLoading(true);
const response = await api.fetchCartItems();
const items = response.data || [];
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.updateCartItemQuantity(id, quantity);
await loadCart(); // Перезагружаем корзину
await api.updateCartItem(id, { quantity });
loadCart();
} catch (error) {
console.error('Ошибка обновления количества:', error);
}
@@ -47,108 +42,77 @@ const CartModal = ({ show, onHide, onCheckout }) => {
const handleRemoveItem = async (id) => {
try {
await api.removeFromCart(id);
await loadCart(); // Перезагружаем корзину
loadCart();
} catch (error) {
console.error('Ошибка удаления из корзины:', error);
}
};
const handleCheckoutClick = async () => {
try {
await onCheckout();
setCartItems([]);
setTotal(0);
} catch (error) {
console.error('Ошибка оформления заказа:', error);
}
};
return (
<Modal show={show} onHide={onHide} size="lg">
<Modal.Header closeButton>
<Modal.Title>🛒 Ваша корзина</Modal.Title>
<Modal.Title>Ваша корзина</Modal.Title>
</Modal.Header>
<Modal.Body>
{loading ? (
<div className="text-center py-3">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Загрузка...</span>
</div>
</div>
) : cartItems.length === 0 ? (
<Alert variant="info" className="text-center">
Корзина пуста
</Alert>
{cartItems.length === 0 ? (
<p className="text-muted">Корзина пуста</p>
) : (
<>
<div className="cart-items">
{cartItems.map(item => (
<Card key={item.id} className="mb-3">
<Card.Body>
<div className="row align-items-center">
<div className="col-3 col-md-2">
<img
src={item.book?.image || "/images/default-book.jpg"}
alt={item.book?.title || "Без названия"}
className="img-fluid rounded"
style={{ maxHeight: '60px', objectFit: 'cover' }}
onError={(e) => {
e.target.src = '/images/default-book.jpg';
e.target.onerror = null;
}}
/>
</div>
<div className="col-9 col-md-6">
<h6 className="mb-1">{item.book?.title || "Без названия"}</h6>
<p className="text-muted small mb-1">{item.book?.author || "Автор не указан"}</p>
<p className="small mb-0">
<strong>Цена:</strong> {item.book?.price || 0} руб.
</p>
</div>
<div className="col-6 col-md-2 mt-2 mt-md-0">
<Form.Control
type="number"
min="1"
value={item.quantity || 1}
onChange={(e) => handleQuantityChange(item.id, parseInt(e.target.value) || 1)}
size="sm"
/>
</div>
<div className="col-6 col-md-2 text-end mt-2 mt-md-0">
<p className="fw-bold mb-1">
{(item.book?.price || 0) * (item.quantity || 1)} руб.
</p>
<Button
variant="outline-danger"
size="sm"
onClick={() => handleRemoveItem(item.id)}
>
<BiTrash />
</Button>
</div>
{cartItems.map(item => (
<Card key={item.id} className="mb-3">
<Card.Body>
<div className="row align-items-center">
<div className="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' }}
/>
</div>
</Card.Body>
</Card>
))}
</div>
<div className="border-top pt-3">
<div className="d-flex justify-content-between align-items-center">
<h5 className="mb-0">Общая стоимость:</h5>
<h5 className="mb-0 text-primary">{total} руб.</h5>
</div>
<div className="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>
</div>
<div className="col-md-2">
<Form.Control
type="number"
min="1"
value={item.quantity || 1}
onChange={(e) => handleQuantityChange(item.id, parseInt(e.target.value))}
className="cart-item-quantity"
/>
</div>
<div className="col-md-2 text-center">
<Button
variant="outline-danger"
onClick={() => handleRemoveItem(item.id)}
>
<BiTrash />
</Button>
</div>
</div>
</Card.Body>
</Card>
))}
<div className="d-flex justify-content-between align-items-center mt-3">
<h4>Итого:</h4>
<h4>{total} руб.</h4>
</div>
</>
)}
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={onHide}>
Продолжить покупки
</Button>
<Button
variant="success"
onClick={handleCheckoutClick}
disabled={cartItems.length === 0 || loading}
<Button variant="secondary" onClick={onHide}>Продолжить покупки</Button>
<Button
variant="success"
onClick={onCheckout}
disabled={cartItems.length === 0}
>
Оформить заказ
</Button>

View File

@@ -1,59 +1,36 @@
import React, { useState, useEffect } from 'react';
import React, { useState } from 'react';
import { Modal, Button, Form } from 'react-bootstrap';
const GenreModal = ({ show, onHide, onSave }) => {
const [genreName, setGenreName] = useState('');
// Сбрасываем форму при открытии/закрытии
useEffect(() => {
if (show) {
setGenreName('');
}
}, [show]);
const handleSubmit = (e) => {
e.preventDefault();
if (!genreName.trim()) {
alert('Введите название жанра');
return;
}
onSave({ name: genreName.trim() });
setGenreName('');
};
const handleClose = () => {
if (!genreName.trim()) return;
onSave({ name: genreName });
setGenreName('');
onHide();
};
return (
<Modal show={show} onHide={handleClose}>
<Modal show={show} onHide={onHide}>
<Modal.Header closeButton>
<Modal.Title> Добавить жанр</Modal.Title>
<Modal.Title>Добавить жанр</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Название жанра *</Form.Label>
<Form.Label>Название жанра</Form.Label>
<Form.Control
type="text"
value={genreName}
onChange={(e) => setGenreName(e.target.value)}
placeholder="Например: Фантастика, Детектив, Роман"
required
autoFocus
/>
<Form.Text className="text-muted">
Введите уникальное название для нового жанра
</Form.Text>
</Form.Group>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Отмена
</Button>
<Button variant="primary" type="submit" disabled={!genreName.trim()}>
Добавить жанр
</Button>
<Button variant="secondary" onClick={onHide}>Отмена</Button>
<Button variant="primary" type="submit">Сохранить</Button>
</Modal.Footer>
</Form>
</Modal.Body>

156
MyWebSite/contactUs.html Normal file
View File

@@ -0,0 +1,156 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Свяжитесь с нами | Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<!-- Ваш CSS -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Навигация -->
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="logo.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<section class="my-5">
<div class="row justify-content-center">
<div class="col-lg-8">
<h2 class="text-center mb-4">Свяжитесь с нами</h2>
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="name" class="form-label">Имя</label>
<input type="text" class="form-control" id="name" required />
<div class="invalid-feedback">Пожалуйста, введите ваше имя.</div>
</div>
<div class="mb-3">
<label for="email" class="form-label">Электронная почта</label>
<input type="email" class="form-control" id="email" required />
<div class="invalid-feedback">Пожалуйста, введите корректный email.</div>
</div>
<div class="mb-3">
<label for="purchase-code" class="form-label">Код покупки (если есть)</label>
<input type="text" class="form-control" id="purchase-code" />
</div>
<div class="mb-3">
<label for="problem-description" class="form-label">Описание проблемы</label>
<textarea class="form-control" id="problem-description" rows="6" required></textarea>
<div class="invalid-feedback">Пожалуйста, опишите вашу проблему.</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-lg px-4">Отправить</button>
</div>
</form>
<!-- Контактная информация -->
<div class="card mt-5">
<div class="card-body">
<h5 class="card-title">Контактная информация</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Книжный магазин "Тома"</h5>
<p>Ваш надежный партнер в мире литературы с 2025 года.</p>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
<!-- Валидация формы -->
<script>
(function () {
"use strict";
const forms = document.querySelectorAll(".needs-validation");
Array.from(forms).forEach((form) => {
form.addEventListener(
"submit",
(event) => {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
},
false
);
});
})();
</script>
</body>
</html>

155
MyWebSite/discounts.html Normal file
View File

@@ -0,0 +1,155 @@
<!-- Сделать кнопку в фантастике "добавить книгу", вводим данные в форму, и карточка книги добавляется в Фантастику-->
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Скидки | Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<!-- Ваш CSS -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="logo.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<section class="my-5">
<h2 class="text-center mb-4">Скидки</h2>
<hr class="mb-4" />
<div class="row g-4 justify-content-center">
<!-- Книга 1 -->
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img
src="images/the_girl_with_the_dragon_tattoo.jpg"
class="card-img-top p-3"
alt="Девушка с татуировкой дракона"
/>
<div class="card-body text-center">
<h5 class="card-title">Девушка с татуировкой дракона</h5>
<p class="card-text">Стиг Ларссон</p>
<p class="text-muted"><s>700 р.</s></p>
<p class="text-danger fs-4 fw-bold">525 р.</p>
<p class="small text-muted">Экономия 175 р. (25%)</p>
<button class="btn btn-primary mt-2">В корзину</button>
</div>
</div>
</div>
<!-- Книга 2 -->
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="images/the_hobbit.webp" class="card-img-top p-3" alt="Хоббит" />
<div class="card-body text-center">
<h5 class="card-title">Хоббит</h5>
<p class="card-text">Дж.Р.Р. Толкин</p>
<p class="text-muted"><s>750 р.</s></p>
<p class="text-danger fs-4 fw-bold">563 р.</p>
<p class="small text-muted">Экономия 187 р. (25%)</p>
<button class="btn btn-primary mt-2">В корзину</button>
</div>
</div>
</div>
<!-- Книга 3 -->
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="images/dune.jpg" class="card-img-top p-3" alt="Дюна" />
<div class="card-body text-center">
<h5 class="card-title">Дюна</h5>
<p class="card-text">Фрэнк Герберт</p>
<p class="text-muted"><s>500 р.</s></p>
<p class="text-danger fs-4 fw-bold">375 р.</p>
<p class="small text-muted">Экономия 125 р. (25%)</p>
<button class="btn btn-primary mt-2">В корзину</button>
</div>
</div>
</div>
</div>
<hr class="my-4" />
<div class="alert alert-success text-center">
<h3>Условия получения скидки:</h3>
<p class="lead mb-0">
При покупке трех книг одновременно Вы получаете скидку 25%!<br />
Скидка действует с 1 по 15 число каждого месяца. Не упустите возможность!
</p>
</div>
</section>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Контакты</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
</body>
</html>

BIN
MyWebSite/dist/assets/Book1-BdJql_-B.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

BIN
MyWebSite/dist/assets/Book2-BEB7Ih2u.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

BIN
MyWebSite/dist/assets/Book3-bPojlso8.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

BIN
MyWebSite/dist/assets/dune-Co1F1vkB.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 817 KiB

BIN
MyWebSite/dist/assets/logo-DsrEtJYJ.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
body{background-color:#fff;background-image:url(/assets/background-oYp1cNqc.png);background-size:100% auto;background-repeat:no-repeat;background-position:center center;background-attachment:fixed;color:#036;font-family:Arial,sans-serif;padding-top:56px;image-rendering:crisp-edges;image-rendering:high-quality;-ms-interpolation-mode:bicubic}.logo{border-radius:50%;width:50px;height:50px;object-fit:cover}.navbar-brand{font-weight:600}.card{transition:transform .3s ease;background-color:#ffffffe6}.card:hover{transform:translateY(-5px)}.btn-primary{background-color:#036;border-color:#036}.btn-primary:hover{background-color:#024;border-color:#024}@media (max-width: 768px){.navbar-brand span{font-size:1rem}body{background-size:auto;background-position:center}}.social-media a{color:#036;transition:color .3s ease}.social-media a:hover{color:#024}.card-img-top{height:300px;object-fit:contain}@media (max-width: 576px){.card{margin-bottom:20px}footer .col-md-6{text-align:center!important;margin-bottom:20px}}

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

200
MyWebSite/dist/basket.html vendored Normal file
View File

@@ -0,0 +1,200 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Корзина | Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<!-- Ваш CSS -->
<link rel="stylesheet" crossorigin href="/assets/style-CVNOuhRW.css">
</head>
<body>
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="/assets/logo-DsrEtJYJ.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link position-relative show-cart-btn" href="#">
<i class="bi bi-cart3"></i>
<span
class="cart-count badge bg-danger rounded-pill position-absolute top-0 start-100 translate-middle"
style="display: none"
></span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<div class="row justify-content-center">
<div class="col-lg-10">
<h2 class="text-center mb-4">Ваша корзина</h2>
<!-- Список товаров -->
<div id="cartItemsContainer">
<!-- Товары будут загружены через JavaScript -->
</div>
<!-- Итоговая информация -->
<div class="card mb-4 border-danger">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center">
<h4 class="mb-0">Общая стоимость:</h4>
<h4 class="mb-0" id="cartTotal">0 руб.</h4>
</div>
</div>
</div>
<!-- Кнопки действий -->
<div class="d-flex justify-content-between mb-5">
<a href="catalog.html" class="btn btn-outline-primary">
<i class="bi bi-arrow-left me-2"></i>Продолжить покупки
</a>
<div>
<button id="clearCartBtn" class="btn btn-outline-danger me-2">
<i class="bi bi-trash me-2"></i>Очистить корзину
</button>
<button id="checkoutBtn" class="btn btn-success btn-lg px-4">
<i class="bi bi-credit-card me-2"></i>Оформить заказ
</button>
</div>
</div>
</div>
</div>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Контакты</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
<!-- Наш компонент -->
<script src="bookComponent.js"></script>
<script>
// Инициализация корзины на странице basket.html
document.addEventListener("DOMContentLoaded", async () => {
const model = new BookModel();
const view = new BookView();
const controller = new BookController(model, view);
// Загружаем и отображаем корзину при загрузке страницы
const cartItems = await model.fetchCartItems();
view.renderCart(cartItems);
// Обновляем счетчик в навигации
await controller.updateCartCount();
// Обработчики для кнопок на странице корзины
document.getElementById("clearCartBtn").addEventListener("click", async () => {
if (confirm("Вы уверены, что хотите очистить корзину?")) {
await model.clearCart();
view.renderCart([]);
await controller.updateCartCount();
}
});
document.getElementById("checkoutBtn").addEventListener("click", () => {
alert("Заказ оформлен! Спасибо за покупку!");
model.clearCart();
view.renderCart([]);
controller.updateCartCount();
});
// Обработчик изменения количества товаров
document.addEventListener("change", async (event) => {
if (event.target.classList.contains("cart-item-quantity")) {
const id = parseInt(event.target.dataset.id);
const quantity = parseInt(event.target.value);
if (quantity > 0) {
await model.updateCartItem(id, { quantity });
const cartItems = await model.fetchCartItems();
view.renderCart(cartItems);
await controller.updateCartCount();
} else {
event.target.value = 1;
}
}
});
// Обработчик удаления товаров
document.addEventListener("click", async (event) => {
if (
event.target.classList.contains("remove-from-cart") ||
event.target.closest(".remove-from-cart")
) {
const id = parseInt(
event.target.dataset.id || event.target.closest(".remove-from-cart").dataset.id
);
await model.removeFromCart(id);
const cartItems = await model.fetchCartItems();
view.renderCart(cartItems);
await controller.updateCartCount();
}
});
});
</script>
</body>

211
MyWebSite/dist/catalog.html vendored Normal file
View File

@@ -0,0 +1,211 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Каталог | Книжный интернет-магазин "Тома"</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<link rel="stylesheet" crossorigin href="/assets/style-CVNOuhRW.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="/assets/logo-DsrEtJYJ.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link position-relative show-cart-btn" href="#">
<i class="bi bi-cart3"></i>
<span
class="cart-count badge bg-danger rounded-pill position-absolute top-0 start-100 translate-middle"
style="display: none"
></span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<main class="container mt-5 pt-5">
<h2 class="text-center mb-5">Каталог книг</h2>
<div class="d-flex justify-content-between mb-2">
<div>
<button class="btn btn-success add-book-btn">
<i class="bi bi-plus-circle"></i> Добавить книгу
</button>
<button class="btn btn-primary add-genre-btn ms-2">
<i class="bi bi-plus-circle"></i> Добавить жанр
</button>
</div>
</div>
<section class="mb-5">
<div class="row g-4" id="fantasy-books"></div>
</section>
<section class="mb-5">
<div class="row g-4" id="detective-books"></div>
</section>
<section class="mb-5">
<div class="row g-4" id="novel-books"></div>
</section>
<section class="mb-5">
<div class="row g-4" id="fantasy2-books"></div>
</section>
</main>
<!-- Модальное окно для добавления/редактирования книги -->
<div class="modal fade" id="bookModal" tabindex="-1" aria-labelledby="bookModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="bookModalLabel">Добавить книгу</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="bookForm">
<input type="hidden" id="bookId" />
<div class="mb-3">
<label for="bookTitle" class="form-label">Название книги</label>
<input type="text" class="form-control" id="bookTitle" required />
</div>
<div class="mb-3">
<label for="bookAuthor" class="form-label">Автор</label>
<input type="text" class="form-control" id="bookAuthor" required />
</div>
<div class="mb-3">
<label for="bookGenre" class="form-label">Жанр</label>
<select class="form-select" id="bookGenre" required></select>
</div>
<div class="mb-3">
<label for="bookPrice" class="form-label">Цена</label>
<input type="number" class="form-control" id="bookPrice" required />
</div>
<div class="mb-3">
<label for="bookDescription" class="form-label">Описание</label>
<textarea class="form-control" id="bookDescription" rows="3" required></textarea>
</div>
<div class="mb-3">
<label for="bookImage" class="form-label">Изображение</label>
<input
type="text"
class="form-control"
id="bookImage"
placeholder="Имя файла (например, book.jpg) или полный URL"
required
/>
<div class="form-text">
Можно указать имя файла из папки images (например, "book.jpg") или полный URL
изображения
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Модальное окно для добавления жанра -->
<div class="modal fade" id="genreModal" tabindex="-1" aria-labelledby="genreModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="genreModalLabel">Добавить жанр</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="genreForm">
<div class="mb-3">
<label for="genreName" class="form-label">Название жанра</label>
<input type="text" class="form-control" id="genreName" required />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Модальное окно корзины -->
<div class="modal fade" id="cartModal" tabindex="-1" aria-labelledby="cartModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="cartModalLabel">Ваша корзина</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="cartItems"></div>
<div class="d-flex justify-content-between align-items-center mt-3">
<h4>Итого:</h4>
<h4 id="cartTotal">0 руб.</h4>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Продолжить покупки
</button>
<button id="checkoutBtnModal" class="btn btn-success">Оформить заказ</button>
</div>
</div>
</div>
</div>
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Контакты</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
<script src="bookComponent.js"></script>
</body>

156
MyWebSite/dist/contactUs.html vendored Normal file
View File

@@ -0,0 +1,156 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Свяжитесь с нами | Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<!-- Ваш CSS -->
<link rel="stylesheet" crossorigin href="/assets/style-CVNOuhRW.css">
</head>
<body>
<!-- Навигация -->
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="/assets/logo-DsrEtJYJ.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<section class="my-5">
<div class="row justify-content-center">
<div class="col-lg-8">
<h2 class="text-center mb-4">Свяжитесь с нами</h2>
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="name" class="form-label">Имя</label>
<input type="text" class="form-control" id="name" required />
<div class="invalid-feedback">Пожалуйста, введите ваше имя.</div>
</div>
<div class="mb-3">
<label for="email" class="form-label">Электронная почта</label>
<input type="email" class="form-control" id="email" required />
<div class="invalid-feedback">Пожалуйста, введите корректный email.</div>
</div>
<div class="mb-3">
<label for="purchase-code" class="form-label">Код покупки (если есть)</label>
<input type="text" class="form-control" id="purchase-code" />
</div>
<div class="mb-3">
<label for="problem-description" class="form-label">Описание проблемы</label>
<textarea class="form-control" id="problem-description" rows="6" required></textarea>
<div class="invalid-feedback">Пожалуйста, опишите вашу проблему.</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-lg px-4">Отправить</button>
</div>
</form>
<!-- Контактная информация -->
<div class="card mt-5">
<div class="card-body">
<h5 class="card-title">Контактная информация</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Книжный магазин "Тома"</h5>
<p>Ваш надежный партнер в мире литературы с 2025 года.</p>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
<!-- Валидация формы -->
<script>
(function () {
"use strict";
const forms = document.querySelectorAll(".needs-validation");
Array.from(forms).forEach((form) => {
form.addEventListener(
"submit",
(event) => {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
},
false
);
});
})();
</script>
</body>

155
MyWebSite/dist/discounts.html vendored Normal file
View File

@@ -0,0 +1,155 @@
<!-- Сделать кнопку в фантастике "добавить книгу", вводим данные в форму, и карточка книги добавляется в Фантастику-->
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Скидки | Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<!-- Ваш CSS -->
<link rel="stylesheet" crossorigin href="/assets/style-CVNOuhRW.css">
</head>
<body>
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="/assets/logo-DsrEtJYJ.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<section class="my-5">
<h2 class="text-center mb-4">Скидки</h2>
<hr class="mb-4" />
<div class="row g-4 justify-content-center">
<!-- Книга 1 -->
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img
src="/assets/the_girl_with_the_dragon_tattoo-CgrgasX2.jpg"
class="card-img-top p-3"
alt="Девушка с татуировкой дракона"
/>
<div class="card-body text-center">
<h5 class="card-title">Девушка с татуировкой дракона</h5>
<p class="card-text">Стиг Ларссон</p>
<p class="text-muted"><s>700 р.</s></p>
<p class="text-danger fs-4 fw-bold">525 р.</p>
<p class="small text-muted">Экономия 175 р. (25%)</p>
<button class="btn btn-primary mt-2">В корзину</button>
</div>
</div>
</div>
<!-- Книга 2 -->
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="/assets/the_hobbit-CkJ8H01T.webp" class="card-img-top p-3" alt="Хоббит" />
<div class="card-body text-center">
<h5 class="card-title">Хоббит</h5>
<p class="card-text">Дж.Р.Р. Толкин</p>
<p class="text-muted"><s>750 р.</s></p>
<p class="text-danger fs-4 fw-bold">563 р.</p>
<p class="small text-muted">Экономия 187 р. (25%)</p>
<button class="btn btn-primary mt-2">В корзину</button>
</div>
</div>
</div>
<!-- Книга 3 -->
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="/assets/dune-Co1F1vkB.jpg" class="card-img-top p-3" alt="Дюна" />
<div class="card-body text-center">
<h5 class="card-title">Дюна</h5>
<p class="card-text">Фрэнк Герберт</p>
<p class="text-muted"><s>500 р.</s></p>
<p class="text-danger fs-4 fw-bold">375 р.</p>
<p class="small text-muted">Экономия 125 р. (25%)</p>
<button class="btn btn-primary mt-2">В корзину</button>
</div>
</div>
</div>
</div>
<hr class="my-4" />
<div class="alert alert-success text-center">
<h3>Условия получения скидки:</h3>
<p class="lead mb-0">
При покупке трех книг одновременно Вы получаете скидку 25%!<br />
Скидка действует с 1 по 15 число каждого месяца. Не упустите возможность!
</p>
</div>
</section>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Контакты</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
</body>

View File

@@ -1,21 +1,136 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<script type="module" crossorigin src="/assets/main-9YKRXbpb.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-BLg3Q5Rn.css">
<!-- Ваш CSS -->
<link rel="stylesheet" crossorigin href="/assets/style-CVNOuhRW.css">
</head>
<div id="root"></div>
<body>
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="/assets/logo-DsrEtJYJ.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<!-- Подключение React и Bootstrap JS -->
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<section class="my-5">
<div class="row justify-content-center">
<div class="col-lg-8 text-center">
<h2 class="mb-4">Описание:</h2>
<p class="lead">
Погрузитесь в незабываемые рукописные миры!<br />
Бесчисленные литературные направления ждут вас!<br />
Познакомьтесь с популярными работами известных<br />
писателей! Мы Вам рады!
</p>
</div>
</div>
</section>
<section class="my-5">
<h2 class="text-center mb-4">Хиты продаж</h2>
<div class="row g-4 justify-content-center">
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="/assets/Book1-BdJql_-B.jpg" class="card-img-top p-3" alt="Книга 1" />
<div class="card-body text-center">
<h5 class="card-title">Тимоти Брук «Шляпа Вермеера»</h5>
<button class="btn btn-primary mt-3">В корзину</button>
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="/assets/Book2-BEB7Ih2u.jpg" class="card-img-top p-3" alt="Книга 2" />
<div class="card-body text-center">
<h5 class="card-title">Пол Линч «Песнь пророка»</h5>
<button class="btn btn-primary mt-3">В корзину</button>
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="/assets/Book3-bPojlso8.jpg" class="card-img-top p-3" alt="Книга 3" />
<div class="card-body text-center">
<h5 class="card-title">Яна Вагнер «Тоннель»</h5>
<button class="btn btn-primary mt-3">В корзину</button>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Контакты</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<!-- Подключение скриптов приложения -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
</body>

136
MyWebSite/home.html Normal file
View File

@@ -0,0 +1,136 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Книжный интернет-магазин "Тома"</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<!-- Ваш CSS -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- Навигация -->
<nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top shadow-sm">
<div class="container">
<a class="navbar-brand d-flex align-items-center" href="index.html">
<img src="logo.png" alt="Логотип" class="logo me-2" />
<span class="d-none d-lg-block">Книжный магазин "Тома"</span>
<span class="d-lg-none">"Тома"</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
Страницы
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="index.html">Главная</a></li>
<li><a class="dropdown-item" href="catalog.html">Каталог</a></li>
<li><a class="dropdown-item" href="discounts.html">Скидки</a></li>
<li><a class="dropdown-item" href="basket.html">Корзина</a></li>
<li><a class="dropdown-item" href="contactUs.html">Контакты</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!-- Основной контент -->
<main class="container mt-5 pt-5">
<section class="my-5">
<div class="row justify-content-center">
<div class="col-lg-8 text-center">
<h2 class="mb-4">Описание:</h2>
<p class="lead">
Погрузитесь в незабываемые рукописные миры!<br />
Бесчисленные литературные направления ждут вас!<br />
Познакомьтесь с популярными работами известных<br />
писателей! Мы Вам рады!
</p>
</div>
</div>
</section>
<section class="my-5">
<h2 class="text-center mb-4">Хиты продаж</h2>
<div class="row g-4 justify-content-center">
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="images/Book1.jpg" class="card-img-top p-3" alt="Книга 1" />
<div class="card-body text-center">
<h5 class="card-title">Тимоти Брук «Шляпа Вермеера»</h5>
<button class="btn btn-primary mt-3">В корзину</button>
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="images/Book2.jpg" class="card-img-top p-3" alt="Книга 2" />
<div class="card-body text-center">
<h5 class="card-title">Пол Линч «Песнь пророка»</h5>
<button class="btn btn-primary mt-3">В корзину</button>
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="card h-100 border-0 shadow-sm">
<img src="images/Book3.jpg" class="card-img-top p-3" alt="Книга 3" />
<div class="card-body text-center">
<h5 class="card-title">Яна Вагнер «Тоннель»</h5>
<button class="btn btn-primary mt-3">В корзину</button>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- Подвал -->
<footer class="bg-light py-4 mt-5">
<div class="container">
<div class="row">
<div class="col-md-6 mb-4 mb-md-0">
<h5 class="mb-3">Контакты</h5>
<ul class="list-unstyled">
<li><i class="bi bi-envelope me-2"></i> info@toma.ru</li>
<li><i class="bi bi-phone me-2"></i> +7 (123) 456-78-90</li>
<li><i class="bi bi-clock me-2"></i> Пн-Пт 9:00-18:00</li>
<li><i class="bi bi-geo-alt me-2"></i> г. Москва, ул. Литераторов, д. 1</li>
</ul>
</div>
<div class="col-md-6 text-md-end">
<h5 class="mb-3">Социальные сети</h5>
<div class="social-media">
<a href="#" class="text-decoration-none me-3"><i class="bi bi-facebook fs-3"></i></a>
<a href="#" class="text-decoration-none me-3"><i class="bi bi-vk fs-3"></i></a>
<a href="#" class="text-decoration-none"><i class="bi bi-telegram fs-3"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
</body>
</html>

View File

@@ -21,8 +21,10 @@ const BasketPage = () => {
const items = response.data;
setCartItems(items);
// Пересчитываем сумму
calculateTotal(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 {
@@ -30,40 +32,43 @@ const BasketPage = () => {
}
};
const calculateTotal = (items) => {
const newTotal = items.reduce((sum, item) => {
return sum + (item.book?.price || 0) * (item.quantity || 1);
}, 0);
setTotal(newTotal);
};
const handleQuantityChange = async (id, quantity) => {
if (quantity < 1) return;
try {
// Используем правильный метод API
await api.updateCartItemQuantity(id, quantity);
// Обновляем локальное состояние
const updatedItems = cartItems.map(item =>
item.id === id ? { ...item, quantity } : item
await api.updateCartItem(id, { quantity });
// Оптимизация: обновляем локальное состояние вместо полной перезагрузки
setCartItems(prevItems =>
prevItems.map(item =>
item.id === id ? { ...item, quantity } : item
)
);
setCartItems(updatedItems);
calculateTotal(updatedItems);
// Пересчитываем итоговую сумму
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);
// Перезагружаем корзину при ошибке
loadCart();
}
};
const handleRemoveItem = async (id) => {
try {
await api.removeFromCart(id);
// Обновляем локальное состояние
const updatedItems = cartItems.filter(item => item.id !== id);
setCartItems(updatedItems);
calculateTotal(updatedItems);
// Оптимизация: обновляем локальное состояние
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);
}
@@ -103,21 +108,14 @@ const BasketPage = () => {
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" className="text-center">
Корзина пуста
<div className="mt-3">
<Link to="/catalog" className="btn btn-primary">
Перейти к покупкам
</Link>
</div>
</Alert>
<Alert variant="info">Корзина пуста</Alert>
) : (
<>
<div className="cart-items">
@@ -127,50 +125,32 @@ const BasketPage = () => {
<Row className="align-items-center">
<Col md={2}>
<img
src={item.book?.image || "/images/default-book.jpg"}
src={item.book?.image || "images/default-book.jpg"}
alt={item.book?.title || "Без названия"}
className="img-fluid rounded"
style={{ maxHeight: '100px', objectFit: 'cover' }}
onError={(e) => {
e.target.src = '/images/default-book.jpg';
e.target.onerror = null;
}}
onError={(e) => { e.target.src = 'images/default-book.jpg' }}
/>
</Col>
<Col md={6}>
<h5 className="mb-2">{item.book?.title || "Без названия"}</h5>
<p className="text-muted mb-1">{item.book?.author || "Автор не указан"}</p>
<p className="mb-1">
<strong>Цена:</strong> {item.book?.price || 0} руб.
</p>
<p className="mb-0">
<strong>Сумма:</strong> {(item.book?.price || 0) * (item.quantity || 1)} руб.
<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}>
<div className="d-flex align-items-center">
<Button
variant="outline-secondary"
size="sm"
onClick={() => handleQuantityChange(item.id, (item.quantity || 1) - 1)}
disabled={(item.quantity || 1) <= 1}
>
-
</Button>
<span className="mx-2">{item.quantity || 1}</span>
<Button
variant="outline-secondary"
size="sm"
onClick={() => handleQuantityChange(item.id, (item.quantity || 1) + 1)}
>
+
</Button>
</div>
<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"
size="sm"
onClick={() => handleRemoveItem(item.id)}
>
Удалить
@@ -182,11 +162,11 @@ const BasketPage = () => {
))}
</div>
<Card className="mb-4 border-primary">
<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 text-primary">{total} руб.</h4>
<h4 className="mb-0">{total} руб.</h4>
</div>
</Card.Body>
</Card>

View File

@@ -19,42 +19,40 @@ const CatalogPage = () => {
const [loading, setLoading] = useState(true);
useEffect(() => {
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 fetchData = async () => {
// Оптимизированная функция для обновления состояния
const updateState = async () => {
try {
setLoading(true);
const [genresResponse, booksResponse, cartResponse] = await Promise.all([
api.fetchGenres(),
const [booksResponse, cartResponse] = await Promise.all([
api.fetchBooks(),
api.fetchCartItems()
]);
setGenres(genresResponse.data || []);
setBooks(booksResponse.data || []);
updateCartCount(cartResponse.data || []);
setBooks(booksResponse.data);
setCartCount(cartResponse.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
} catch (error) {
console.error('Ошибка загрузки данных:', error);
} finally {
setLoading(false);
}
};
const updateCartCount = (cartItems) => {
const count = cartItems.reduce((sum, item) => sum + (item.quantity || 0), 0);
setCartCount(count);
};
const handleDeleteGenre = async (genreId) => {
if (window.confirm('Вы уверены, что хотите удалить этот жанр? Все книги этого жанра будут без жанра.')) {
try {
await api.deleteGenre(genreId);
await fetchData(); // Полная перезагрузка данных
} catch (error) {
console.error('Ошибка удаления жанра:', error);
alert('Нельзя удалить жанр, если есть книги с этим жанром');
}
console.error('Ошибка обновления данных:', error);
}
};
@@ -72,7 +70,7 @@ const CatalogPage = () => {
if (window.confirm('Вы уверены, что хотите удалить эту книгу?')) {
try {
await api.deleteBook(id);
await fetchData();
await updateState();
} catch (error) {
console.error('Ошибка удаления книги:', error);
}
@@ -83,20 +81,18 @@ const CatalogPage = () => {
try {
// Проверяем, есть ли уже эта книга в корзине
const cartResponse = await api.fetchCartItems();
const existingItem = cartResponse.data.find(item => item.book?.id === bookId);
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();
updateCartCount(updatedCart.data);
setCartCount(updatedCart.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
} catch (error) {
console.error('Ошибка добавления в корзину:', error);
}
@@ -109,7 +105,7 @@ const CatalogPage = () => {
} else {
await api.createBook(bookData);
}
await fetchData();
await updateState();
setShowBookModal(false);
} catch (error) {
console.error('Ошибка сохранения книги:', error);
@@ -120,7 +116,7 @@ const CatalogPage = () => {
try {
await api.createGenre(genreData);
const genresResponse = await api.fetchGenres();
setGenres(genresResponse.data || []);
setGenres(genresResponse.data);
setShowGenreModal(false);
} catch (error) {
console.error('Ошибка сохранения жанра:', error);
@@ -132,30 +128,23 @@ const CatalogPage = () => {
await api.clearCart();
setCartCount(0);
setShowCartModal(false);
alert("Заказ оформлен! Спасибо за покупку!");
} catch (error) {
console.error('Ошибка оформления заказа:', error);
}
};
const booksByGenre = (genreId) => {
return books.filter(book => book.genre?.id === genreId);
return books.filter(book => book.genreId === genreId);
};
const genresWithBooks = genres.filter(genre =>
books.some(book => book.genre?.id === genre.id)
const genresWithBooks = genres.filter(genre =>
books.some(book => book.genreId === genre.id)
);
// Добавляем жанры без книг
const allGenres = [...genresWithBooks, ...genres.filter(genre =>
!genresWithBooks.some(g => g.id === genre.id)
)];
if (loading) {
return (
<div className="d-flex justify-content-center align-items-center vh-100">
<Spinner animation="border" variant="primary" />
<span className="ms-2">Загрузка...</span>
</div>
);
}
@@ -163,19 +152,19 @@ const CatalogPage = () => {
return (
<div className="catalog-page">
<Navbar cartCount={cartCount} onShowCart={() => setShowCartModal(true)} />
<main className="mt-5 pt-5">
<Container>
<h2 className="text-center mb-5">Каталог книг</h2>
<div className="d-flex justify-content-between mb-4">
<div>
<Button variant="success" onClick={handleAddBook}>
Добавить книгу
</Button>
<Button
variant="primary"
className="ms-2"
<Button
variant="primary"
className="ms-2"
onClick={() => setShowGenreModal(true)}
>
Добавить жанр
@@ -183,45 +172,24 @@ const CatalogPage = () => {
</div>
</div>
{allGenres.length === 0 ? (
<div className="text-center py-5">
<h4>Нет данных для отображения</h4>
<p className="text-muted">Добавьте жанры и книги для начала работы</p>
</div>
) : (
allGenres.map(genre => (
<section key={genre.id} className="mb-5">
<div className="genre-title bg-light p-3 rounded text-center mb-4">
<h3 className="mb-2">{genre.name}</h3>
<Button
variant="outline-danger"
size="sm"
onClick={() => handleDeleteGenre(genre.id)}
title="Удалить жанр"
>
Удалить жанр
</Button>
</div>
<Row>
{booksByGenre(genre.id).length > 0 ? (
booksByGenre(genre.id).map(book => (
<BookComponent
key={book.id}
book={book}
onEdit={handleEditBook}
onDelete={handleDeleteBook}
onAddToCart={handleAddToCart}
/>
))
) : (
<div className="text-center py-3">
<p className="text-muted">В этом жанре пока нет книг</p>
</div>
)}
</Row>
</section>
))
)}
{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>
</div>
<Row>
{booksByGenre(genre.id).map(book => (
<BookComponent
key={book.id}
book={book}
onEdit={handleEditBook}
onDelete={handleDeleteBook}
onAddToCart={handleAddToCart}
/>
))}
</Row>
</section>
))}
</Container>
</main>

View File

@@ -1,3 +0,0 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

View File

@@ -1,37 +0,0 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@@ -1,54 +0,0 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.5'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
description = 'Demo project for Spring Boot'
jar {
enabled = false
}
bootJar {
archiveFileName = String.format("%s-%s.jar", rootProject.name, version)
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
ext {
springdocVersion = "2.8.11"
mockitoVersion = "5.19.0"
}
configurations {
mockitoAgent
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:${springdocVersion}"
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation "org.mockito:mockito-core:${mockitoVersion}"
mockitoAgent("org.mockito:mockito-core:${mockitoVersion}") {
transitive = false
}
}
tasks.named('test') {
useJUnitPlatform()
jvmArgs += "-Xshare:off"
jvmArgs += "-javaagent:${configurations.mockitoAgent.asPath}"
}

View File

@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -1,94 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,2 +0,0 @@
rootProject.name = 'server'

View File

@@ -1,68 +0,0 @@
package com.example.server;
import com.example.server.mapper.BookMapper;
import com.example.server.mapper.CartItemMapper;
import com.example.server.mapper.GenreMapper;
import com.example.server.service.BookService;
import com.example.server.service.CartItemService;
import com.example.server.service.GenreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Objects;
@SpringBootApplication
public class ServerApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(ServerApplication.class);
private final BookService bookService;
private final GenreService genreService;
private final CartItemService cartItemService;
private final BookMapper bookMapper;
private final GenreMapper genreMapper;
private final CartItemMapper cartItemMapper;
public ServerApplication(BookService bookService, GenreService genreService,
CartItemService cartItemService, BookMapper bookMapper,
GenreMapper genreMapper, CartItemMapper cartItemMapper) {
this.bookService = bookService;
this.bookMapper = bookMapper;
this.genreService = genreService;
this.genreMapper = genreMapper;
this.cartItemService = cartItemService;
this.cartItemMapper = cartItemMapper;
}
private void populateData() {
log.info("Create default genres");
final var genre1 = genreService.create(genreMapper.toRqDto("Роман"));
final var genre2 = genreService.create(genreMapper.toRqDto("Фантастика"));
final var genre3 = genreService.create(genreMapper.toRqDto("Ужасы"));
log.info("Create default books");
bookService.create(bookMapper.toRqDto("Основание", "Айзек Азимов",
700, "Сага о падении и возрождении галактической империи, основанная на научных принципах.", "images/foundation.jpg", genre1.getId()));
bookService.create(bookMapper.toRqDto("Дюна", "Фрэнк Герберт",
900, "Эпическая история о борьбе за контроль над планетой Арракис, источником самого ценного вещества во вселенной.", "images/dune.jpg", genre2.getId()));
bookService.create(bookMapper.toRqDto("Убийство в Восточном экспрессе", "Агата Кристи",
750, "Загадочное убийство на поезде, где каждый пассажир может быть подозреваемым.", "images/murder_on_the_orient_express.jpg", genre3.getId()));
}
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length == 0) {
return;
}
if (Objects.equals("--populate", args[0])) {
populateData();
}
}
}

View File

@@ -1,59 +0,0 @@
package com.example.server.api.book;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.example.server.api.genre.GenreController;
import com.example.server.error.NotFoundException;
import com.example.server.service.BookService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import com.example.server.configuration.Constants;
@RestController
@RequestMapping(Constants.API_URL + BookController.URL)
public class BookController {
public static final String URL = "/book";
private final BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
/* @GetMapping
public List<BookRs> getAll() {
return bookService.getAll();
}*/
@GetMapping
public List<BookRs> getAll(@RequestParam(required = false) Long genreId) {
if (genreId != null) {
return bookService.getByGenre(genreId);
}
return bookService.getAll();
}
@GetMapping("/{id}")
public BookRs get(@PathVariable Long id) {
return bookService.get(id);
}
@PostMapping
public BookRs create(@RequestBody @Valid BookRq dto) {
return bookService.create(dto);
}
@PutMapping("/{id}")
public BookRs update(@PathVariable Long id, @RequestBody @Valid BookRq dto) {
return bookService.update(id, dto);
}
@DeleteMapping("/{id}")
public BookRs delete(@PathVariable Long id) {
return bookService.delete(id);
}
}

View File

@@ -1,73 +0,0 @@
package com.example.server.api.book;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class BookRq {
@JsonProperty("title")
@NotBlank(message = "название обязателен")
@Size(min = 2, max = 50, message = "Название должно быть от 2 до 50 символов")
private String title;
@JsonProperty("author")
@NotBlank(message = "автор обязателен")
@Size(min = 2, max = 50, message = "ФИО должно быть от 2 до 50 символов")
private String author;
@NotNull
@Min(value = 1, message = "Цена не может быть меньше 1 рубля")
private int price;
private String description;
@NotNull
private Long genreId;
private String image;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Long getGenreId() {
return genreId;
}
public void setGenreId(Long genreId) {
this.genreId = genreId;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}

View File

@@ -1,84 +0,0 @@
package com.example.server.api.book;
import com.example.server.api.genre.GenreRs;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class BookRs {
@NotBlank(message = "id обязательно")
private Long Id;
@JsonProperty("title")
@NotBlank(message = "Название обязательно")
@Size(min = 2, max = 50, message = "Название должно быть от 2 до 50 символов")
private String title;
@JsonProperty("author")
@NotBlank(message = "автор обязателен")
@Size(min = 2, max = 50, message = "ФИО должно быть от 2 до 50 символов")
private String author;
@NotNull
@Min(value = 1, message = "Цена не может быть меньше 1 рубля")
private int price;
private String description;
@NotNull
private GenreRs genre;
private String image;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public GenreRs getGenre() {
return genre;
}
public void setGenre(GenreRs genre) {
this.genre = genre;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}

View File

@@ -1,75 +0,0 @@
package com.example.server.api.cartItem;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.example.server.api.book.BookController;
import com.example.server.entity.CartItemEntity;
import com.example.server.service.CartItemService;
import jakarta.validation.Valid;
import org.slf4j.*;
import org.springframework.web.bind.annotation.*;
import com.example.server.error.NotFoundException;
import com.example.server.configuration.Constants;
@RestController
@RequestMapping(Constants.API_URL + CartController.URL)
public class CartController {
public static final String URL = "/cart";
private final Logger log = LoggerFactory.getLogger(CartController.class);
private final CartItemService cartItemService;
public CartController(CartItemService cartItemService) {
this.cartItemService = cartItemService;
}
@GetMapping
public List<CartItemRs> getAll() {
log.debug("Get all cart items");
return cartItemService.getAll();
}
@GetMapping("/{id}")
public CartItemRs get(@PathVariable Long id) {
log.debug("Get cart item with id {}", id);
return cartItemService.get(id);
}
@GetMapping("/search")
public CartItemRs getByBookId(@RequestParam Long bookId) {
return cartItemService.getByBookId(bookId)
.orElseThrow(() -> new NotFoundException(CartItemEntity.class, bookId));
}
@PostMapping
public CartItemRs addToCart(@RequestBody @Valid CartItemRq newItem) {
log.debug("Add to cart: {}", newItem);
return cartItemService.create(newItem);
}
@PutMapping("/{id}")
public CartItemRs updateCartItem(@PathVariable Long id, @RequestBody @Valid CartItemRq updatedItem) {
log.debug("Update cart item with id {}: {}", id, updatedItem);
return cartItemService.update(id, updatedItem);
}
@DeleteMapping("/{id}")
public CartItemRs removeFromCart(@PathVariable Long id) {
log.debug("Remove from cart: {}", id);
return cartItemService.delete(id);
}
@PatchMapping("/{id}/{quantity}")
public CartItemRs updateQuantity(@PathVariable Long id, @PathVariable int quantity) {
log.debug("Update quantity for cart item with id {} to {}", id, quantity);
return cartItemService.updateQuantity(id, quantity);
}
@DeleteMapping
public void clearCart() {
log.debug("Clear cart");
cartItemService.deleteAll();
}
}

View File

@@ -1,29 +0,0 @@
package com.example.server.api.cartItem;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class CartItemRq {
@NotNull
private Long bookId;
@NotNull
@Min(value = 0, message = "Кол-во не может быть меньше 0")
private int quantity;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
}

View File

@@ -1,39 +0,0 @@
package com.example.server.api.cartItem;
import com.example.server.api.book.BookRs;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class CartItemRs {
@NotNull
private Long id;
@NotNull
private BookRs book;
@NotNull
@Min(value = 0, message = "Кол-во не может быть меньше 0")
private int quantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public BookRs getBook() {
return book;
}
public void setBook(BookRs book) {
this.book = book;
}
}

View File

@@ -1,48 +0,0 @@
package com.example.server.api.genre;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.example.server.error.NotFoundException;
import com.example.server.service.GenreService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import com.example.server.configuration.Constants;
@RestController
@RequestMapping(Constants.API_URL + GenreController.URL)
public class GenreController {
public static final String URL = "/genre";
private final GenreService genreService;
public GenreController(GenreService genreService) {
this.genreService = genreService;
}
@GetMapping
public List<GenreRs> getAll() {
return genreService.getAll();
}
@GetMapping("/{id}")
public GenreRs get(@PathVariable Long id) {
return genreService.get(id);
}
@PostMapping
public GenreRs create(@RequestBody @Valid GenreRq dto) {
return genreService.create(dto);
}
@PutMapping("/{id}")
public GenreRs update(@PathVariable Long id, @RequestBody @Valid GenreRq dto) {
return genreService.update(id, dto);
}
@DeleteMapping("/{id}")
public GenreRs delete(@PathVariable Long id) {
return genreService.delete(id);
}
}

View File

@@ -1,18 +0,0 @@
package com.example.server.api.genre;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class GenreRq {
@NotBlank(message = "Название обязательно")
@Size(min = 2, max = 50, message = "Название должно быть от 2 до 50 символов")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -1,29 +0,0 @@
package com.example.server.api.genre;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class GenreRs {
@NotNull
private Long id;
@NotBlank(message = "Название обязательно")
@Size(min = 2, max = 50, message = "Название должно быть от 2 до 50 символов")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -1,9 +0,0 @@
package com.example.server.configuration;
public class Constants {
public static final String DEV_ORIGIN = "http://localhost:5173";
public static final String API_URL = "/api/1.0";
private Constants() {
}
}

View File

@@ -1,19 +0,0 @@
package com.example.server.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer{
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry
.addMapping("/api/**") // Более широкий паттерн
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowedOrigins("http://localhost:5173", "http://127.0.0.1:5173")
.allowedHeaders("*")
.allowCredentials(true);
}
}

View File

@@ -1,15 +0,0 @@
package com.example.server.entity;
public abstract class BaseEntity {
protected Long Id;
protected BaseEntity() {}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
}

View File

@@ -1,72 +0,0 @@
package com.example.server.entity;
public class BookEntity extends BaseEntity{
private String title;
private String author;
private int price;
private String description;
private GenreEntity genre;
private String image;
public BookEntity() {
super();
}
public BookEntity(String title, String author, int price, String description, GenreEntity gente, String image) {
this();
this.title = title;
this.author = author;
this.price = price;
this.description = description;
this.genre = gente;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public GenreEntity getGenre() {
return genre;
}
public void setGenre(GenreEntity genre) {
this.genre = genre;
}
}

View File

@@ -1,32 +0,0 @@
package com.example.server.entity;
public class CartItemEntity extends BaseEntity{
private BookEntity book;
private int quantity;
public CartItemEntity() {
super();
}
public CartItemEntity(BookEntity book, int quantity) {
this();
this.book = book;
this.quantity = quantity;
}
public BookEntity getBook() {
return book;
}
public void setBook(BookEntity book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}

View File

@@ -1,21 +0,0 @@
package com.example.server.entity;
public class GenreEntity extends BaseEntity{
private String name;
public GenreEntity() {
super();
}
public GenreEntity(String name) {
this();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -1,26 +0,0 @@
package com.example.server.error;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class AdviceController {
private HttpStatus getStatus(HttpServletRequest request) {
final Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
final HttpStatus status = (code != null) ? HttpStatus.resolve(code) : null;
return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<AdviceErrorBody> handleAnyException(HttpServletRequest request, Throwable ex) {
final HttpStatus status = getStatus(request);
return new ResponseEntity<>(new AdviceErrorBody(status.value(), ex.getMessage()), status);
}
}

View File

@@ -1,5 +0,0 @@
package com.example.server.error;
public record AdviceErrorBody(int status, String message) {
}

View File

@@ -1,7 +0,0 @@
package com.example.server.error;
public class NotFoundException extends RuntimeException {
public <T> NotFoundException(Class<T> clazz, Long id){
super(String.format("%s with id %s is not found", clazz.getSimpleName(), id));
}
}

View File

@@ -1,48 +0,0 @@
package com.example.server.mapper;
import com.example.server.api.book.BookRq;
import com.example.server.api.book.BookRs;
import com.example.server.entity.BookEntity;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.StreamSupport;
@Component
public class BookMapper {
private final GenreMapper genreMapper;
public BookMapper(GenreMapper genreMapper) {
this.genreMapper = genreMapper;
}
public BookRq toRqDto(
String title, String author, int price, String description, String image, Long genreId) {
final BookRq dto = new BookRq();
dto.setTitle(title);
dto.setAuthor(author);
dto.setPrice(price);
dto.setDescription(description);
dto.setImage(image);
dto.setGenreId(genreId);
return dto;
}
public BookRs toRsDto(BookEntity entity) {
final BookRs dto = new BookRs();
dto.setId(entity.getId());
dto.setTitle(entity.getTitle());
dto.setAuthor(entity.getAuthor());
dto.setPrice(entity.getPrice());
dto.setDescription(entity.getDescription());
dto.setGenre(genreMapper.toRsDto(entity.getGenre()));
dto.setImage(entity.getImage());
return dto;
}
public List<BookRs> toRsListDto(Iterable<BookEntity> entities) {
return StreamSupport.stream(entities.spliterator(), false)
.map(this::toRsDto)
.toList();
}
}

View File

@@ -1,40 +0,0 @@
package com.example.server.mapper;
import com.example.server.api.cartItem.CartItemRq;
import com.example.server.api.cartItem.CartItemRs;
import com.example.server.entity.CartItemEntity;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.StreamSupport;
@Component
public class CartItemMapper {
private final BookMapper bookMapper;
public CartItemMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public CartItemRq toRqDto(Long bookId, int quantity) {
final CartItemRq dto = new CartItemRq();
dto.setBookId(bookId);
dto.setQuantity(quantity);
return dto;
}
public CartItemRs toRsDto(CartItemEntity entity) {
final CartItemRs dto = new CartItemRs();
dto.setId(entity.getId());
dto.setBook(bookMapper.toRsDto(entity.getBook()));
dto.setQuantity(entity.getQuantity());
return dto;
}
public List<CartItemRs> toRsListDto(Iterable<CartItemEntity> entities) {
return StreamSupport.stream(entities.spliterator(), false)
.map(this::toRsDto)
.toList();
}
}

View File

@@ -1,31 +0,0 @@
package com.example.server.mapper;
import com.example.server.api.genre.GenreRq;
import com.example.server.api.genre.GenreRs;
import com.example.server.entity.GenreEntity;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.StreamSupport;
@Component
public class GenreMapper {
public GenreRq toRqDto(String name) {
final GenreRq dto = new GenreRq();
dto.setName(name);
return dto;
}
public GenreRs toRsDto(GenreEntity entity) {
final GenreRs dto = new GenreRs();
dto.setId(entity.getId());
dto.setName(entity.getName());
return dto;
}
public List<GenreRs> toRsDtoList(Iterable<GenreEntity> entities) {
return StreamSupport.stream(entities.spliterator(), false)
.map(this::toRsDto)
.toList();
}
}

View File

@@ -1,8 +0,0 @@
package com.example.server.repository;
import com.example.server.entity.BookEntity;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepository extends MapRepository<BookEntity> {
}

View File

@@ -1,10 +0,0 @@
package com.example.server.repository;
import com.example.server.entity.CartItemEntity;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class CartItemRepository extends MapRepository<CartItemEntity> {
}

View File

@@ -1,17 +0,0 @@
package com.example.server.repository;
import com.example.server.entity.CartItemEntity;
import java.util.Optional;
public interface CommonRepository<E, T> {
Iterable<E> findAll();
Optional<E> findById(T id);
E save(E entity);
void delete(E entity);
void deleteAll();
}

View File

@@ -1,8 +0,0 @@
package com.example.server.repository;
import com.example.server.entity.GenreEntity;
import org.springframework.stereotype.Repository;
@Repository
public class GenreRepository extends MapRepository<GenreEntity> {
}

View File

@@ -1,69 +0,0 @@
package com.example.server.repository;
import com.example.server.entity.BaseEntity;
import com.example.server.entity.CartItemEntity;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final ConcurrentNavigableMap<Long, E> entities = new ConcurrentSkipListMap<>();
private final AtomicLong idGenerator = new AtomicLong(0L);
protected MapRepository() {
}
private boolean isNew(E entity) {
return Objects.isNull(entity.getId());
}
private E create(E entity) {
final Long lastId = idGenerator.incrementAndGet();
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
private E update(E entity) {
if (findById(entity.getId()).isEmpty()) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public Iterable<E> findAll() {
return entities.values();
}
@Override
public Optional<E> findById(Long id) {
return Optional.ofNullable(entities.get(id));
}
@Override
public E save(E entity) {
if (isNew(entity)) {
return create(entity);
}
return update(entity);
}
@Override
public void delete(E entity) {
if (findById(entity.getId()).isEmpty()) {
return;
}
entities.remove(entity.getId());
}
@Override
public void deleteAll() {
entities.clear();
idGenerator.set(0L);
}
}

View File

@@ -1,79 +0,0 @@
package com.example.server.service;
import com.example.server.api.book.BookRq;
import com.example.server.api.book.BookRs;
import com.example.server.entity.BookEntity;
import com.example.server.entity.GenreEntity;
import com.example.server.error.NotFoundException;
import com.example.server.mapper.BookMapper;
import com.example.server.repository.BookRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@Service
public class BookService {
private final BookRepository repository;
private final GenreService typeService;
private final BookMapper mapper;
public BookService(BookRepository repository, GenreService typeService, BookMapper mapper) {
this.repository = repository;
this.typeService = typeService;
this.mapper = mapper;
}
public BookEntity getEntity(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(BookEntity.class, id));
}
public List<BookRs> getAll() {
return mapper.toRsListDto(repository.findAll());
}
public List<BookRs> getByGenre(Long genreId) {
return StreamSupport.stream(repository.findAll().spliterator(), false)
.filter(book -> book.getGenre().getId().equals(genreId))
.map(mapper::toRsDto)
.collect(Collectors.toList());
}
public BookRs get(Long id) {
final BookEntity entity = getEntity(id);
return mapper.toRsDto(entity);
}
public BookRs create(BookRq dto) {
final GenreEntity genre = typeService.getEntity(dto.getGenreId());
BookEntity entity = new BookEntity(
dto.getTitle(),
dto.getAuthor(),
dto.getPrice(),
dto.getDescription(),
genre,
dto.getImage());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public BookRs update(Long id, BookRq dto) {
BookEntity entity = getEntity(id);
entity.setTitle(dto.getTitle());
entity.setAuthor(dto.getAuthor());
entity.setPrice(dto.getPrice());
entity.setDescription(dto.getDescription());
entity.setGenre(typeService.getEntity(dto.getGenreId()));
entity.setImage(dto.getImage());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public BookRs delete(Long id) {
final BookEntity entity = getEntity(id);
repository.delete(entity);
return mapper.toRsDto(entity);
}
}

View File

@@ -1,83 +0,0 @@
package com.example.server.service;
import com.example.server.api.cartItem.CartItemRq;
import com.example.server.api.cartItem.CartItemRs;
import com.example.server.entity.BookEntity;
import com.example.server.entity.CartItemEntity;
import com.example.server.error.NotFoundException;
import com.example.server.mapper.CartItemMapper;
import com.example.server.repository.CartItemRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
@Service
public class CartItemService {
private final CartItemRepository repository;
private final BookService bookService;
private final CartItemMapper mapper;
public CartItemService(CartItemRepository repository, BookService bookService, CartItemMapper mapper) {
this.repository = repository;
this.bookService = bookService;
this.mapper = mapper;
}
public CartItemEntity getEntity(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(CartItemEntity.class, id));
}
public List<CartItemRs> getAll() {
return mapper.toRsListDto(repository.findAll());
}
public CartItemRs get(Long id) {
final CartItemEntity entity = getEntity(id);
return mapper.toRsDto(entity);
}
public Optional<CartItemRs> getByBookId(Long bookId) {
return StreamSupport.stream(repository.findAll().spliterator(), false)
.filter(item -> item.getBook().getId().equals(bookId))
.findFirst()
.map(mapper::toRsDto);
}
public CartItemRs create(CartItemRq dto) {
final BookEntity book = bookService.getEntity(dto.getBookId());
CartItemEntity entity = new CartItemEntity(
book,
dto.getQuantity());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public CartItemRs update(Long id, CartItemRq dto) {
CartItemEntity entity = getEntity(id);
entity.setBook(bookService.getEntity(dto.getBookId()));
entity.setQuantity(dto.getQuantity());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public CartItemRs updateQuantity(Long id, int quantity) {
CartItemEntity entity = getEntity(id);
entity.setQuantity(quantity);
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public CartItemRs delete(Long id) {
final CartItemEntity entity = getEntity(id);
repository.delete(entity);
return mapper.toRsDto(entity);
}
public void deleteAll() {
repository.deleteAll();
}
}

View File

@@ -1,55 +0,0 @@
package com.example.server.service;
import com.example.server.api.genre.GenreRq;
import com.example.server.api.genre.GenreRs;
import com.example.server.entity.GenreEntity;
import com.example.server.error.NotFoundException;
import com.example.server.mapper.GenreMapper;
import com.example.server.repository.GenreRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GenreService {
private final GenreRepository repository;
private final GenreMapper mapper;
public GenreService(GenreRepository repository, GenreMapper mapper) {
this.repository = repository;
this.mapper = mapper;
}
public GenreEntity getEntity(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(GenreEntity.class, id));
}
public List<GenreRs> getAll() {
return mapper.toRsDtoList(repository.findAll());
}
public GenreRs get(Long id) {
final GenreEntity entity = getEntity(id);
return mapper.toRsDto(entity);
}
public GenreRs create(GenreRq dto) {
GenreEntity entity = new GenreEntity(dto.getName());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public GenreRs update(Long id, GenreRq dto) {
GenreEntity entity = getEntity(id);
entity.setName(dto.getName());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
public GenreRs delete(Long id) {
final GenreEntity entity = getEntity(id);
repository.delete(entity);
return mapper.toRsDto(entity);
}
}

View File

@@ -1,14 +0,0 @@
spring.application.name=server
spring.main.banner-mode=off
bootRun.args=--populate
logging.level.com.server=DEBUG
# ???????? ??? ????????? ????????
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
# ?????????? ??? HTTP ???????
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log

View File

@@ -1,128 +0,0 @@
package com.example.server.service;
import com.example.server.api.book.BookRs;
import com.example.server.error.NotFoundException;
import com.example.server.mapper.BookMapper;
import com.example.server.mapper.GenreMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class BookServiceTests {
@Autowired
private BookService service;
@Autowired
private GenreService genreService;
@Autowired
private BookMapper mapper;
@Autowired
private GenreMapper genreMapper;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test
@Order(1)
void createTest() {
var genre1 = genreService.create(genreMapper.toRqDto("Роман"));
var genre2 = genreService.create(genreMapper.toRqDto("Фантастика"));
service.create(mapper.toRqDto("Книга 1", "Автор 1", 500, "Описание 1", "image1.jpg", 1L));
service.create(mapper.toRqDto("Книга 2", "Автор 2", 600, "Описание 2", "image2.jpg", 2L));
final BookRs last = service.create(mapper.toRqDto("Книга 3", "Автор 3", 700, "Описание 3", "image3.jpg", 1L));
Assertions.assertEquals(3, service.getAll().size());
final BookRs cmpEntity = service.get(3L);
Assertions.assertEquals(last.getId(), cmpEntity.getId());
Assertions.assertEquals(last.getTitle(), cmpEntity.getTitle());
}
@Test
@Order(2)
void updateTest() {
final String newTitle = "Обновленная книга";
final BookRs entity = service.get(3L);
final String oldTitle = entity.getTitle();
final BookRs newEntity = service.update(3L, mapper.toRqDto(newTitle, "Автор 3", 750, "Новое описание", "new_image.jpg", 1L));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(newTitle, newEntity.getTitle());
Assertions.assertNotEquals(oldTitle, newEntity.getTitle());
final BookRs cmpEntity = service.get(3L);
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
Assertions.assertEquals(newEntity.getTitle(), cmpEntity.getTitle());
}
@Test
@Order(3)
void getByGenreTest() {
List<BookRs> booksByGenre1 = service.getByGenre(1L);
List<BookRs> booksByGenre2 = service.getByGenre(2L);
Assertions.assertEquals(2, booksByGenre1.size()); // 2 книги в жанре 1
Assertions.assertEquals(1, booksByGenre2.size()); // 1 книга в жанре 2
booksByGenre1.forEach(book ->
Assertions.assertEquals(1L, book.getGenre().getId())
);
}
@Test
@Order(4)
void deleteTest() {
service.delete(3L);
Assertions.assertEquals(2, service.getAll().size());
final BookRs last = service.get(2L);
Assertions.assertEquals(2L, last.getId());
final BookRs newEntity = service.create(mapper.toRqDto("Новая книга", "Новый автор", 800, "Описание", "image.jpg", 2L));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
@Test
@Order(5)
void getAllTest() {
Assertions.assertEquals(3, service.getAll().size());
final BookRs first = service.get(1L);
final BookRs second = service.get(2L);
final BookRs third = service.get(4L);
Assertions.assertEquals("Книга 1", first.getTitle());
Assertions.assertEquals("Книга 2", second.getTitle());
Assertions.assertEquals("Новая книга", third.getTitle());
}
@Test
void getNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(999L));
}
@Test
void updateNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () ->
service.update(999L, mapper.toRqDto("Несуществующая", "Автор", 100, "Описание", "image.jpg", 1L)));
}
@Test
void deleteNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.delete(999L));
}
}

View File

@@ -1,173 +0,0 @@
package com.example.server.service;
import com.example.server.api.cartItem.CartItemRs;
import com.example.server.error.NotFoundException;
import com.example.server.mapper.BookMapper;
import com.example.server.mapper.CartItemMapper;
import com.example.server.mapper.GenreMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Optional;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class CartItemServiceTests {
@Autowired
private CartItemService service;
@Autowired
private BookService bookService;
@Autowired
private GenreService genreService;
@Autowired
private CartItemMapper mapper;
@Autowired
private BookMapper bookMapper;
@Autowired
private GenreMapper genreMapper;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test
@Order(1)
void createTest() {
var genre1 = genreService.create(genreMapper.toRqDto("Роман"));
var genre2 = genreService.create(genreMapper.toRqDto("Фантастика"));
bookService.create(bookMapper.toRqDto("Книга 1", "Автор 1", 500, "Описание 1", "image1.jpg", 1L));
bookService.create(bookMapper.toRqDto("Книга 2", "Автор 2", 600, "Описание 2", "image2.jpg", 2L));
bookService.create(bookMapper.toRqDto("Книга 3", "Автор 3", 600, "Описание 3", "image3.jpg", 1L));
bookService.create(bookMapper.toRqDto("Книга 4", "Автор 4", 500, "Описание 4", "image4.jpg", 2L));
service.create(mapper.toRqDto(1L, 2));
service.create(mapper.toRqDto(2L, 1));
final CartItemRs last = service.create(mapper.toRqDto(4L, 3));
Assertions.assertEquals(3, service.getAll().size());
final CartItemRs cmpEntity = service.get(3L);
Assertions.assertEquals(last.getId(), cmpEntity.getId());
Assertions.assertEquals(last.getQuantity(), cmpEntity.getQuantity());
}
@Test
@Order(2)
void updateTest() {
final CartItemRs entity = service.get(3L);
final int oldQuantity = entity.getQuantity();
final CartItemRs newEntity = service.update(3L, mapper.toRqDto(4L, 5));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(5, newEntity.getQuantity());
Assertions.assertNotEquals(oldQuantity, newEntity.getQuantity());
final CartItemRs cmpEntity = service.get(3L);
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
Assertions.assertEquals(newEntity.getQuantity(), cmpEntity.getQuantity());
}
@Test
@Order(3)
void updateQuantityTest() {
final CartItemRs updated = service.updateQuantity(1L, 10);
Assertions.assertEquals(10, updated.getQuantity());
final CartItemRs entity = service.get(1L);
Assertions.assertEquals(10, entity.getQuantity());
}
@Test
@Order(4)
void getByBookIdTest() {
Optional<CartItemRs> cartItem = service.getByBookId(4L);
Assertions.assertTrue(cartItem.isPresent());
Assertions.assertEquals(4L, cartItem.get().getBook().getId());
Assertions.assertEquals(5, cartItem.get().getQuantity());
Optional<CartItemRs> nonExistent = service.getByBookId(999L);
Assertions.assertFalse(nonExistent.isPresent());
}
@Test
@Order(5)
void deleteTest() {
service.delete(3L);
Assertions.assertEquals(2, service.getAll().size());
final CartItemRs last = service.get(2L);
Assertions.assertEquals(2L, last.getId());
final CartItemRs newEntity = service.create(mapper.toRqDto(1L, 1));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
@Test
@Order(6)
void clearCartTest() {
service.deleteAll();
Assertions.assertEquals(0, service.getAll().size());
// Создаем новый элемент после очистки
final CartItemRs newEntity = service.create(mapper.toRqDto(2L, 2));
Assertions.assertEquals(1, service.getAll().size());
Assertions.assertEquals(1L, newEntity.getId()); // ID продолжает инкрементироваться
}
@Test
void getNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(999L));
}
@Test
void updateNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () ->
service.update(999L, mapper.toRqDto(1L, 1)));
}
@Test
void updateQuantityNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () ->
service.updateQuantity(999L, 5));
}
@Test
void deleteNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.delete(999L));
}
@Test
@Order(7)
void createDuplicateBookTest() {
// Можно добавить одну и ту же книгу в корзину несколько раз
final CartItemRs item1 = service.create(mapper.toRqDto(1L, 1));
final CartItemRs item2 = service.create(mapper.toRqDto(1L, 2));
Assertions.assertNotEquals(item1.getId(), item2.getId());
Assertions.assertEquals(1L, item1.getBook().getId());
Assertions.assertEquals(1L, item2.getBook().getId());
}
@Test
@Order(8)
void updateQuantityToZeroTest() {
// Обновление количества до 0 должно удалить элемент
final CartItemRs deleted = service.updateQuantity(1L, 0);
Assertions.assertEquals(0, deleted.getQuantity());
// Элемент должен быть удален
Assertions.assertThrows(NotFoundException.class, () -> service.get(5L));
}
}

View File

@@ -1,120 +0,0 @@
package com.example.server.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.server.api.genre.GenreRq;
import com.example.server.api.genre.GenreRs;
import com.example.server.error.NotFoundException;
import com.example.server.mapper.GenreMapper;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class GenreServiceTests {
@Autowired
private GenreService service;
@Autowired
private GenreMapper mapper;
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test
@Order(1)
void createTest() {
service.create(mapper.toRqDto("Роман"));
service.create(mapper.toRqDto("Фантастика"));
final GenreRs last = service.create(mapper.toRqDto("Детектив"));
Assertions.assertEquals(3, service.getAll().size());
final GenreRs cmpEntity = service.get(3L);
Assertions.assertEquals(last.getId(), cmpEntity.getId());
Assertions.assertEquals(last.getName(), cmpEntity.getName());
}
@Test
@Order(2)
void updateTest() {
final String test = "Ужасы";
final GenreRs entity = service.get(3L);
final String oldName = entity.getName();
final GenreRs newEntity = service.update(3L, mapper.toRqDto(test));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
final GenreRs cmpEntity = service.get(3L);
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
}
@Test
@Order(3)
void deleteTest() {
service.delete(3L);
Assertions.assertEquals(2, service.getAll().size());
final GenreRs last = service.get(2L);
Assertions.assertEquals(2L, last.getId());
final GenreRs newEntity = service.create(mapper.toRqDto("Приключения"));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
@Test
@Order(4)
void getAllTest() {
Assertions.assertEquals(3, service.getAll().size());
final GenreRs first = service.get(1L);
final GenreRs second = service.get(2L);
final GenreRs third = service.get(4L);
Assertions.assertEquals("Роман", first.getName());
Assertions.assertEquals("Фантастика", second.getName());
Assertions.assertEquals("Приключения", third.getName());
}
@Test
@Order(5)
void createDuplicateTest() {
final GenreRs duplicate = service.create(mapper.toRqDto("Роман"));
Assertions.assertEquals(4, service.getAll().size());
Assertions.assertEquals("Роман", duplicate.getName());
}
@Test
void getNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(999L));
}
@Test
void updateNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () ->
service.update(999L, mapper.toRqDto("Несуществующий")));
}
@Test
void deleteNonExistentTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.delete(999L));
}
@Test
void createWithEmptyNameTest() {
GenreRq dto = new GenreRq();
dto.setName(""); // Пустое имя
Assertions.assertDoesNotThrow(() -> service.create(dto));
}
}

View File

@@ -1,30 +1,29 @@
import axios from "axios";
const API_URL = "http://localhost:8080/api/1.0";
const API_URL = "http://localhost:3001";
export default {
// Жанры
fetchGenres: () => axios.get(`${API_URL}/genre`),
createGenre: (genreData) => axios.post(`${API_URL}/genre`, genreData),
deleteGenre: (id) => axios.delete(`${API_URL}/genre/${id}`),
fetchGenres: () => axios.get(`${API_URL}/genres`),
createGenre: (genreData) => axios.post(`${API_URL}/genres`, genreData),
// Книги
fetchBooks: () => axios.get(`${API_URL}/book`),
fetchBooksByGenre: (genreId) => axios.get(`${API_URL}/book?genreId=${genreId}`),
fetchBook: (id) => axios.get(`${API_URL}/book/${id}`),
createBook: (bookData) => axios.post(`${API_URL}/book`, bookData),
updateBook: (id, bookData) => axios.put(`${API_URL}/book/${id}`, bookData),
deleteBook: (id) => axios.delete(`${API_URL}/book/${id}`),
fetchBooks: () => axios.get(`${API_URL}/books`),
fetchBooksByGenre: (genreId) => axios.get(`${API_URL}/books?genreId=${genreId}`),
fetchBook: (id) => axios.get(`${API_URL}/books/${id}`),
createBook: (bookData) => axios.post(`${API_URL}/books`, bookData),
updateBook: (id, bookData) => axios.put(`${API_URL}/books/${id}`, bookData),
deleteBook: (id) => axios.delete(`${API_URL}/books/${id}`),
// Корзина
fetchCartItems: () => axios.get(`${API_URL}/cart`),
fetchCartItems: () => axios.get(`${API_URL}/cart?_expand=book`),
addToCart: (bookId) => axios.post(`${API_URL}/cart`, { bookId, quantity: 1 }),
getCartItemByBookId: (bookId) => axios.get(`${API_URL}/cart/search?bookId=${bookId}`),
updateCartItem: (id, data) => axios.put(`${API_URL}/cart/${id}`, data),
updateCartItemQuantity: (id, quantity) => axios.patch(`${API_URL}/cart/${id}/${quantity}`),
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) => Promise.all(response.data.map((item) =>
axios.delete(`${API_URL}/cart/${item.id}`)))),
.then((response) => Promise.all(response.data.map((item) => axios.delete(`${API_URL}/cart/${item.id}`)))),
};

View File

@@ -10,6 +10,7 @@ export default defineConfig({
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
catalog: resolve(__dirname, "catalog.html"),
},
},
},

Binary file not shown.

7181
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +0,0 @@
{
"name": "mywebsite",
"version": "1.0.0",
"main": "vite.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "vite build",
"lint": "eslint . --ext js --report-unused-disable-directives --max-warnings 0",
"dev": "vite",
"start": "npm-run-all -p dev"
},
"dependencies": {
"@popperjs/core": "^2.11.8",
"axios": "^1.9.0",
"bootstrap": "^5.3.6",
"bootstrap-icons": "1.11.3",
"json-server": "^0.17.4",
"react": "^19.1.0",
"react-bootstrap": "^2.10.10",
"react-dom": "^19.1.0",
"react-icons": "^5.5.0",
"react-router-dom": "^7.6.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.4.1",
"eslint": "8.56.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-config-prettier": "10.0.2",
"eslint-plugin-html": "8.1.2",
"eslint-plugin-import": "2.31.0",
"eslint-plugin-prettier": "5.2.3",
"http-server": "14.1.1",
"npm-run-all": "4.1.5",
"vite": "^6.3.5"
},
"keywords": [],
"author": "denis",
"license": "ISC",
"description": ""
}