2 Commits

Author SHA1 Message Date
9cb68ecec9 full 2025-10-17 10:16:18 +04:00
8a7eb58d7c LabWork_2.2 2025-10-02 13:27:17 +04:00
55 changed files with 9759 additions and 231 deletions

14
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,14 @@
{
"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 Normal file
View File

@@ -0,0 +1,54 @@
{
"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

@@ -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,18 +14,22 @@ 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.genreId,
price: book.price,
description: book.description,
image: book.image?.replace('images/', '') || ''
title: book.title || '',
author: book.author || '',
genreId: book.genre?.id || genres[0]?.id || '',
price: book.price || '',
description: book.description || '',
image: book.image || ''
});
}).catch(error => {
console.error('Ошибка загрузки книги:', error);
});
} else {
// Сбрасываем форму для новой книги
setFormData({
title: '',
author: '',
@@ -35,55 +39,69 @@ const BookModal = ({ show, onHide, bookId, genres, onSave }) => {
image: ''
});
}
}, [bookId, genres]);
}, [bookId, genres, show]); // Добавил show в зависимости
const handleSubmit = (e) => {
e.preventDefault();
const bookData = {
...formData,
price: Number(formData.price),
price: Number(formData.price) || 0,
genreId: Number(formData.genreId),
image: formData.image.startsWith('http')
? formData.image
: `images/${formData.image}`
// Убираем автоматическое добавление 'images/' - сохраняем как есть
image: formData.image
};
onSave(bookData);
};
const handleClose = () => {
setFormData({
title: '',
author: '',
genreId: '',
price: '',
description: '',
image: ''
});
onHide();
};
return (
<Modal show={show} onHide={onHide} size="lg">
<Modal show={show} onHide={handleClose} 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>
))}
@@ -91,24 +109,27 @@ 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>
@@ -118,17 +139,18 @@ const BookModal = ({ show, onHide, bookId, genres, onSave }) => {
type="text"
value={formData.image}
onChange={(e) => setFormData({...formData, image: e.target.value})}
placeholder="Имя файла (например, book.jpg) или полный URL"
required
placeholder="URL изображения или путь к файлу"
/>
<Form.Text className="text-muted">
Можно указать имя файла из папки images (например, "book.jpg") или полный URL изображения
Можно указать полный URL (https://...) или относительный путь (images/book.jpg)
</Form.Text>
</Form.Group>
<Modal.Footer>
<Button variant="secondary" onClick={onHide}>Отмена</Button>
<Button variant="primary" type="submit">Сохранить</Button>
<Button variant="secondary" onClick={handleClose}>Отмена</Button>
<Button variant="primary" type="submit">
{bookId ? 'Обновить' : 'Добавить'}
</Button>
</Modal.Footer>
</Form>
</Modal.Body>

View File

@@ -1,11 +1,12 @@
import React, { useState, useEffect } from 'react';
import { Modal, Button, Card, Form } from 'react-bootstrap';
import { Modal, Button, Card, Form, Alert } 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) {
@@ -15,25 +16,29 @@ 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.updateCartItem(id, { quantity });
loadCart();
// Используем правильный метод для обновления количества
await api.updateCartItemQuantity(id, quantity);
await loadCart(); // Перезагружаем корзину
} catch (error) {
console.error('Ошибка обновления количества:', error);
}
@@ -42,77 +47,108 @@ const CartModal = ({ show, onHide, onCheckout }) => {
const handleRemoveItem = async (id) => {
try {
await api.removeFromCart(id);
loadCart();
await 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>
{cartItems.length === 0 ? (
<p className="text-muted">Корзина пуста</p>
{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.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 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>
</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>
</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>
</>
)}
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={onHide}>Продолжить покупки</Button>
<Button
variant="success"
onClick={onCheckout}
disabled={cartItems.length === 0}
<Button variant="secondary" onClick={onHide}>
Продолжить покупки
</Button>
<Button
variant="success"
onClick={handleCheckoutClick}
disabled={cartItems.length === 0 || loading}
>
Оформить заказ
</Button>

View File

@@ -1,36 +1,59 @@
import React, { useState } from 'react';
import React, { useState, useEffect } 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()) return;
onSave({ name: genreName });
if (!genreName.trim()) {
alert('Введите название жанра');
return;
}
onSave({ name: genreName.trim() });
setGenreName('');
};
const handleClose = () => {
setGenreName('');
onHide();
};
return (
<Modal show={show} onHide={onHide}>
<Modal show={show} onHide={handleClose}>
<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={onHide}>Отмена</Button>
<Button variant="primary" type="submit">Сохранить</Button>
<Button variant="secondary" onClick={handleClose}>
Отмена
</Button>
<Button variant="primary" type="submit" disabled={!genreName.trim()}>
Добавить жанр
</Button>
</Modal.Footer>
</Form>
</Modal.Body>

64
MyWebSite/dist/assets/main-9YKRXbpb.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

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

View File

@@ -19,54 +19,42 @@ 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 handleDeleteGenre = async (genreId) => {
if (window.confirm('Вы уверены, что хотите удалить этот жанр? Все книги этого жанра будут без жанра.')) {
const fetchData = async () => {
try {
await api.deleteGenre(genreId);
const genresResponse = await api.fetchGenres();
setGenres(genresResponse.data);
await updateState(); // Обновляем книги, так как у некоторых мог измениться жанр
} catch (error) {
console.error('Ошибка удаления жанра:', error);
alert('Нельзя удалить жанр, если есть книги с этим жанром');
}
}
};
// Оптимизированная функция для обновления состояния
const updateState = async () => {
try {
const [booksResponse, cartResponse] = await Promise.all([
setLoading(true);
const [genresResponse, booksResponse, cartResponse] = await Promise.all([
api.fetchGenres(),
api.fetchBooks(),
api.fetchCartItems()
]);
setBooks(booksResponse.data);
setCartCount(cartResponse.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
setGenres(genresResponse.data || []);
setBooks(booksResponse.data || []);
updateCartCount(cartResponse.data || []);
} catch (error) {
console.error('Ошибка обновления данных:', 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('Нельзя удалить жанр, если есть книги с этим жанром');
}
}
};
@@ -84,7 +72,7 @@ const CatalogPage = () => {
if (window.confirm('Вы уверены, что хотите удалить эту книгу?')) {
try {
await api.deleteBook(id);
await updateState();
await fetchData();
} catch (error) {
console.error('Ошибка удаления книги:', error);
}
@@ -95,18 +83,20 @@ const CatalogPage = () => {
try {
// Проверяем, есть ли уже эта книга в корзине
const cartResponse = await api.fetchCartItems();
const existingItem = cartResponse.data.find(item => item.bookId === bookId);
const existingItem = cartResponse.data.find(item => item.book?.id === bookId);
if (existingItem) {
// Обновляем количество существующего элемента
await api.updateCartItemQuantity(existingItem.id, existingItem.quantity + 1);
} else {
// Добавляем новый элемент
await api.addToCart(bookId);
}
// Обновляем счетчик корзины
const updatedCart = await api.fetchCartItems();
setCartCount(updatedCart.data.reduce((sum, item) => sum + (item.quantity || 0), 0));
updateCartCount(updatedCart.data);
} catch (error) {
console.error('Ошибка добавления в корзину:', error);
}
@@ -119,7 +109,7 @@ const CatalogPage = () => {
} else {
await api.createBook(bookData);
}
await updateState();
await fetchData();
setShowBookModal(false);
} catch (error) {
console.error('Ошибка сохранения книги:', error);
@@ -130,7 +120,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);
@@ -142,23 +132,30 @@ const CatalogPage = () => {
await api.clearCart();
setCartCount(0);
setShowCartModal(false);
alert("Заказ оформлен! Спасибо за покупку!");
} catch (error) {
console.error('Ошибка оформления заказа:', error);
}
};
const booksByGenre = (genreId) => {
return books.filter(book => book.genreId === genreId);
return books.filter(book => book.genre?.id === genreId);
};
const genresWithBooks = genres.filter(genre =>
books.some(book => book.genreId === genre.id)
const genresWithBooks = genres.filter(genre =>
books.some(book => book.genre?.id === 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>
);
}
@@ -166,19 +163,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)}
>
Добавить жанр
@@ -186,32 +183,45 @@ const CatalogPage = () => {
</div>
</div>
{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>
<Button
variant="outline-danger"
size="sm"
onClick={() => handleDeleteGenre(genre.id)}
title="Удалить жанр"
>
Удалить
</Button>
</div>
<Row>
{booksByGenre(genre.id).map(book => (
<BookComponent
key={book.id}
book={book}
onEdit={handleEditBook}
onDelete={handleDeleteBook}
onAddToCart={handleAddToCart}
/>
))}
</Row>
</section>
))}
{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>
))
)}
</Container>
</main>

3
MyWebSite/server/.gitattributes vendored Normal file
View File

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

37
MyWebSite/server/.gitignore vendored Normal file
View File

@@ -0,0 +1,37 @@
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

@@ -0,0 +1,54 @@
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}"
}

Binary file not shown.

View File

@@ -0,0 +1,7 @@
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

251
MyWebSite/server/gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/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" "$@"

94
MyWebSite/server/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@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

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

View File

@@ -0,0 +1,68 @@
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

@@ -0,0 +1,59 @@
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

@@ -0,0 +1,73 @@
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

@@ -0,0 +1,84 @@
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

@@ -0,0 +1,75 @@
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

@@ -0,0 +1,29 @@
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

@@ -0,0 +1,39 @@
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

@@ -0,0 +1,48 @@
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

@@ -0,0 +1,18 @@
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

@@ -0,0 +1,29 @@
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

@@ -0,0 +1,9 @@
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

@@ -0,0 +1,19 @@
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

@@ -0,0 +1,15 @@
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

@@ -0,0 +1,72 @@
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

@@ -0,0 +1,32 @@
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

@@ -0,0 +1,21 @@
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

@@ -0,0 +1,26 @@
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

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

View File

@@ -0,0 +1,7 @@
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

@@ -0,0 +1,48 @@
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

@@ -0,0 +1,40 @@
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

@@ -0,0 +1,31 @@
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

@@ -0,0 +1,8 @@
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

@@ -0,0 +1,10 @@
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

@@ -0,0 +1,17 @@
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

@@ -0,0 +1,8 @@
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

@@ -0,0 +1,69 @@
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

@@ -0,0 +1,79 @@
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

@@ -0,0 +1,83 @@
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

@@ -0,0 +1,55 @@
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

@@ -0,0 +1,14 @@
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

@@ -0,0 +1,128 @@
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

@@ -0,0 +1,173 @@
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

@@ -0,0 +1,120 @@
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

@@ -7,7 +7,6 @@ export default {
fetchGenres: () => axios.get(`${API_URL}/genre`),
createGenre: (genreData) => axios.post(`${API_URL}/genre`, genreData),
deleteGenre: (id) => axios.delete(`${API_URL}/genre/${id}`),
// Добавить в кард метод патч(в патче должен отображаться квантити) для количества и добавить удаление жанра
// Книги
fetchBooks: () => axios.get(`${API_URL}/book`),
fetchBooksByGenre: (genreId) => axios.get(`${API_URL}/book?genreId=${genreId}`),
@@ -17,14 +16,15 @@ export default {
deleteBook: (id) => axios.delete(`${API_URL}/book/${id}`),
// Корзина
fetchCartItems: () => axios.get(`${API_URL}/cart?_expand=book`),
fetchCartItems: () => axios.get(`${API_URL}/cart`),
addToCart: (bookId) => axios.post(`${API_URL}/cart`, { bookId, quantity: 1 }),
getCartItemByBookId: (bookId) => axios.get(`${API_URL}/cart?bookId=${bookId}`),
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}`),
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}`)))),
};

7181
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"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": ""
}