Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 092a020059 | |||
| 8708686994 |
+3
-26
@@ -1,42 +1,19 @@
|
|||||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
import { Routes, Route } from 'react-router-dom';
|
||||||
import Layout from './components/Layout';
|
import Layout from './components/Layout';
|
||||||
import Home from './pages/Home';
|
import Home from './pages/Home';
|
||||||
import Books from './pages/Books';
|
import Books from './pages/Books';
|
||||||
import Orders from './pages/Orders';
|
import Orders from './pages/Orders';
|
||||||
import Profile from './pages/Profile';
|
import Profile from './pages/Profile';
|
||||||
import NotFound from './pages/NotFound';
|
import NotFound from './pages/NotFound';
|
||||||
import AddBook from './pages/AddBook';
|
|
||||||
import BookDetail from './pages/BookDetail';
|
|
||||||
import Customers from './pages/Customers';
|
|
||||||
import Login from './pages/Login';
|
|
||||||
import Reservations from './pages/Reservations';
|
|
||||||
import { useAuth } from './context/AuthContext';
|
|
||||||
|
|
||||||
function RequireAuth({ children }) {
|
|
||||||
const { user } = useAuth();
|
|
||||||
return user ? children : <Navigate to="/login" replace />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function RequireAdmin({ children }) {
|
|
||||||
const { user } = useAuth();
|
|
||||||
if (!user) return <Navigate to="/login" replace />;
|
|
||||||
if (user.role !== 'admin') return <Navigate to="/" replace />;
|
|
||||||
return children;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<Login />} />
|
|
||||||
<Route path="/" element={<Layout />}>
|
<Route path="/" element={<Layout />}>
|
||||||
<Route index element={<Home />} />
|
<Route index element={<Home />} />
|
||||||
<Route path="books" element={<Books />} />
|
<Route path="books" element={<Books />} />
|
||||||
<Route path="books/:bookId" element={<RequireAuth><BookDetail /></RequireAuth>} />
|
<Route path="orders" element={<Orders />} />
|
||||||
<Route path="books/new" element={<RequireAdmin><AddBook /></RequireAdmin>} />
|
<Route path="profile" element={<Profile />} />
|
||||||
<Route path="orders" element={<RequireAuth><Orders /></RequireAuth>} />
|
|
||||||
<Route path="reservations" element={<RequireAuth><Reservations /></RequireAuth>} />
|
|
||||||
<Route path="profile" element={<RequireAuth><Profile /></RequireAuth>} />
|
|
||||||
<Route path="customers" element={<RequireAdmin><Customers /></RequireAdmin>} />
|
|
||||||
<Route path="*" element={<NotFound />} />
|
<Route path="*" element={<NotFound />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
import client from './client';
|
|
||||||
|
|
||||||
export function getBooks(page = 0, size = 20) {
|
|
||||||
return client.get('/api/books', { params: { page, size } });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function registerBook(book) {
|
|
||||||
return client.post('/api/books', book);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getBookById(id) {
|
|
||||||
return client.get(`/api/books/${id}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function reserveBook(bookId, reservation) {
|
|
||||||
return client.post(`/api/books/${bookId}/reservations`, reservation);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import client from './client';
|
||||||
|
|
||||||
|
export function getBooks(page = 0, size = 20) {
|
||||||
|
return client.get('/api/books', { params: { page, size } });
|
||||||
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import client from './client';
|
|
||||||
|
|
||||||
export function registerCustomer(customer) {
|
|
||||||
return client.post('/api/customers', customer);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function findCustomerByPhone(phoneNumber) {
|
|
||||||
return client.get(`/api/customers/phone/${encodeURIComponent(phoneNumber)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function addLoyaltyPoints(customerId, points) {
|
|
||||||
return client.post(`/api/customers/${customerId}/loyalty/add`, null, { params: { points } });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function subtractLoyaltyPoints(customerId, points) {
|
|
||||||
return client.post(`/api/customers/${customerId}/loyalty/subtract`, null, { params: { points } });
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,7 @@
|
|||||||
import { Link, useNavigate } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { useAuth } from '../context/AuthContext';
|
|
||||||
import '../styles/navbar.css';
|
import '../styles/navbar.css';
|
||||||
|
|
||||||
export default function Navbar() {
|
export default function Navbar() {
|
||||||
const { user, logout } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
function handleLogout() {
|
|
||||||
logout();
|
|
||||||
navigate('/login');
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav className="navbar">
|
<nav className="navbar">
|
||||||
<Link to="/" className="navbar__logo">Biblio</Link>
|
<Link to="/" className="navbar__logo">Biblio</Link>
|
||||||
@@ -18,21 +9,13 @@ export default function Navbar() {
|
|||||||
<ul className="navbar__links">
|
<ul className="navbar__links">
|
||||||
<li><Link to="/">Accueil</Link></li>
|
<li><Link to="/">Accueil</Link></li>
|
||||||
<li><Link to="/books">Catalogue</Link></li>
|
<li><Link to="/books">Catalogue</Link></li>
|
||||||
{user && <li><Link to="/orders">Commandes</Link></li>}
|
<li><Link to="/orders">Commandes</Link></li>
|
||||||
{user?.role === 'user' && <li><Link to="/reservations">Mes réservations</Link></li>}
|
<li><Link to="/profile">Mon compte</Link></li>
|
||||||
{user && <li><Link to="/profile">Mon compte</Link></li>}
|
|
||||||
{user?.role === 'admin' && <li><Link to="/customers">Clients</Link></li>}
|
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<div className="navbar__actions">
|
<div className="navbar__actions">
|
||||||
{user ? (
|
<button className="btn-ghost">Connexion</button>
|
||||||
<>
|
<button className="btn-cta">S'inscrire</button>
|
||||||
<span>{user.username} ({user.role})</span>
|
|
||||||
<button onClick={handleLogout}>Déconnexion</button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Link to="/login"><button>Connexion</button></Link>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
import { createContext, useContext, useState } from 'react';
|
|
||||||
|
|
||||||
const USERS = [
|
|
||||||
{ username: 'admin', password: 'admin', role: 'admin' },
|
|
||||||
{ username: 'alice', password: 'bob', role: 'user' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const AuthContext = createContext(null);
|
|
||||||
|
|
||||||
export function AuthProvider({ children }) {
|
|
||||||
const [user, setUser] = useState(() => {
|
|
||||||
const saved = localStorage.getItem('auth');
|
|
||||||
return saved ? JSON.parse(saved) : null;
|
|
||||||
});
|
|
||||||
|
|
||||||
function login(username, password) {
|
|
||||||
const found = USERS.find(u => u.username === username && u.password === password);
|
|
||||||
if (!found) return false;
|
|
||||||
const { password: _, ...safe } = found;
|
|
||||||
setUser(safe);
|
|
||||||
localStorage.setItem('auth', JSON.stringify(safe));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function logout() {
|
|
||||||
setUser(null);
|
|
||||||
localStorage.removeItem('auth');
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AuthContext.Provider value={{ user, login, logout }}>
|
|
||||||
{children}
|
|
||||||
</AuthContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useAuth() {
|
|
||||||
return useContext(AuthContext);
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import { createContext, useContext, useState } from 'react';
|
|
||||||
|
|
||||||
const ReservationContext = createContext(null);
|
|
||||||
|
|
||||||
export function ReservationProvider({ children }) {
|
|
||||||
const [reservations, setReservations] = useState(() => {
|
|
||||||
const saved = localStorage.getItem('reservations');
|
|
||||||
return saved ? JSON.parse(saved) : [];
|
|
||||||
});
|
|
||||||
|
|
||||||
function addReservation(book, phoneNumber) {
|
|
||||||
const reservation = {
|
|
||||||
reservationId: crypto.randomUUID(),
|
|
||||||
bookId: book.isbn,
|
|
||||||
bookTitle: book.title,
|
|
||||||
bookAuthor: book.author,
|
|
||||||
phoneNumber,
|
|
||||||
status: 'CONFIRMED',
|
|
||||||
reservedAt: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
const updated = [...reservations, reservation];
|
|
||||||
setReservations(updated);
|
|
||||||
localStorage.setItem('reservations', JSON.stringify(updated));
|
|
||||||
return reservation;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cancelReservation(reservationId) {
|
|
||||||
const updated = reservations.filter(r => r.reservationId !== reservationId);
|
|
||||||
setReservations(updated);
|
|
||||||
localStorage.setItem('reservations', JSON.stringify(updated));
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ReservationContext.Provider value={{ reservations, addReservation, cancelReservation }}>
|
|
||||||
{children}
|
|
||||||
</ReservationContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useReservations() {
|
|
||||||
return useContext(ReservationContext);
|
|
||||||
}
|
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import ReactDOM from 'react-dom/client';
|
import ReactDOM from 'react-dom/client';
|
||||||
import { BrowserRouter } from 'react-router-dom';
|
import { BrowserRouter } from 'react-router-dom';
|
||||||
import { AuthProvider } from './context/AuthContext';
|
|
||||||
import { ReservationProvider } from './context/ReservationContext';
|
|
||||||
import App from './App';
|
import App from './App';
|
||||||
import './styles/global.css';
|
import './styles/global.css';
|
||||||
|
|
||||||
@@ -10,11 +8,7 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
|
|||||||
root.render(
|
root.render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<AuthProvider>
|
<App />
|
||||||
<ReservationProvider>
|
|
||||||
<App />
|
|
||||||
</ReservationProvider>
|
|
||||||
</AuthProvider>
|
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</React.StrictMode>
|
</React.StrictMode>
|
||||||
);
|
);
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { registerBook } from '../api/books';
|
|
||||||
|
|
||||||
const CATEGORIES = ['FICTION', 'NON_FICTION', 'SCIENCE_FICTION', 'FANTASY', 'MYSTERY', 'THRILLER', 'ROMANCE', 'BIOGRAPHY', 'HISTORY', 'POETRY', 'CHILDRENS', 'YOUNG_ADULT', 'SCIENCE', 'PHILOSOPHY', 'SELF_HELP', 'TRAVEL', 'COOKING', 'ART', 'RELIGION', 'REFERENCE'];
|
|
||||||
|
|
||||||
const initialForm = {
|
|
||||||
isbn: '', title: '', author: '', publisher: '', publicationDate: '', price: '', quantity: '', categories: [], description: '', language: '',
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function AddBook() {
|
|
||||||
const [form, setForm] = useState(initialForm);
|
|
||||||
const [message, setMessage] = useState(null);
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
|
||||||
|
|
||||||
function handleChange(e) {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setForm((prev) => ({ ...prev, [name]: value }));
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleCategoryChange(e) {
|
|
||||||
setForm((prev) => ({ ...prev, categories: e.target.value ? [e.target.value] : [] }));
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleSubmit(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
setSubmitting(true);
|
|
||||||
setMessage(null);
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
...form,
|
|
||||||
isbn: Number(form.isbn),
|
|
||||||
price: Number(form.price),
|
|
||||||
quantity: Number(form.quantity),
|
|
||||||
};
|
|
||||||
|
|
||||||
registerBook(payload)
|
|
||||||
.then((response) => {
|
|
||||||
setMessage({ type: 'success', text: `Livre créé (id : ${response.data})` });
|
|
||||||
setForm(initialForm);
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(error);
|
|
||||||
const status = error.response?.status;
|
|
||||||
if (status === 406) setMessage({ type: 'error', text: 'Ce livre existe déjà.' });
|
|
||||||
else if (status === 400) setMessage({ type: 'error', text: 'Données invalides, vérifie les champs.' });
|
|
||||||
else setMessage({ type: 'error', text: 'Erreur lors de la création.' });
|
|
||||||
})
|
|
||||||
.finally(() => setSubmitting(false));
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<h1>Ajouter un livre</h1>
|
|
||||||
<form onSubmit={handleSubmit}>
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<td>ISBN</td>
|
|
||||||
<td><input name="isbn" type="number" value={form.isbn} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Titre</td>
|
|
||||||
<td><input name="title" value={form.title} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Auteur</td>
|
|
||||||
<td><input name="author" value={form.author} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Éditeur</td>
|
|
||||||
<td><input name="publisher" value={form.publisher} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Date de publication</td>
|
|
||||||
<td><input name="publicationDate" type="date" value={form.publicationDate} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Prix</td>
|
|
||||||
<td><input name="price" type="number" step="0.01" value={form.price} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Quantité</td>
|
|
||||||
<td><input name="quantity" type="number" value={form.quantity} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Langue</td>
|
|
||||||
<td><input name="language" value={form.language} onChange={handleChange} required /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Catégorie</td>
|
|
||||||
<td><select value={form.categories[0] || ''} onChange={handleCategoryChange} required><option value=""> choisir </option>{CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}</select></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Description</td>
|
|
||||||
<td><textarea name="description" value={form.description} onChange={handleChange} /></td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
<button type="submit" disabled={submitting}>
|
|
||||||
{submitting ? 'Envoi…' : 'Ajouter le livre'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
{message && <p>{message.text}</p>}
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { useParams, Link } from 'react-router-dom';
|
|
||||||
import { getBookById } from '../api/books';
|
|
||||||
import { useAuth } from '../context/AuthContext';
|
|
||||||
import { useReservations } from '../context/ReservationContext';
|
|
||||||
|
|
||||||
export default function BookDetail() {
|
|
||||||
const { user } = useAuth();
|
|
||||||
const { addReservation } = useReservations();
|
|
||||||
const { bookId } = useParams();
|
|
||||||
const [book, setBook] = useState(null);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState(null);
|
|
||||||
const [phoneNumber, setPhoneNumber] = useState('');
|
|
||||||
const [reservationStatus, setReservationStatus] = useState(null);
|
|
||||||
|
|
||||||
useEffect(() => { getBookById(bookId).then((response) => setBook(response.data)).catch((err) => { console.error(err); setError('Livre introuvable.'); }).finally(() => setLoading(false)); }, [bookId]);
|
|
||||||
|
|
||||||
function handleReservation(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
addReservation(book, phoneNumber);
|
|
||||||
setReservationStatus({ success: true, message: 'Réservation effectuée avec succès !' });
|
|
||||||
setPhoneNumber('');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loading) return <main><p>Chargement…</p></main>;
|
|
||||||
if (error) return <main><p>{error}</p><Link to="/books">← Retour au catalogue</Link></main>;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<Link to="/books">← Retour au catalogue</Link>
|
|
||||||
<h1>{book.title}</h1>
|
|
||||||
<p>Auteur : {book.author}</p>
|
|
||||||
<p>ISBN : {book.isbn}</p>
|
|
||||||
<p>Éditeur : {book.publisher}</p>
|
|
||||||
<p>Publié le : {book.publicationDate}</p>
|
|
||||||
<p>Prix : {book.price} €</p>
|
|
||||||
<p>Stock : {book.quantity}</p>
|
|
||||||
<p>Langue : {book.language}</p>
|
|
||||||
<p>Catégories : {book.categories?.join(', ')}</p>
|
|
||||||
{book.description && <p>{book.description}</p>}
|
|
||||||
|
|
||||||
{user?.role === 'user' && <section>
|
|
||||||
<h2>Réserver ce livre</h2>
|
|
||||||
<form onSubmit={handleReservation}>
|
|
||||||
<label>
|
|
||||||
Numéro de téléphone :
|
|
||||||
<input
|
|
||||||
type="tel"
|
|
||||||
value={phoneNumber}
|
|
||||||
onChange={(e) => setPhoneNumber(e.target.value)}
|
|
||||||
placeholder="0612345678"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
<button type="submit">Réserver</button>
|
|
||||||
</form>
|
|
||||||
{reservationStatus && (
|
|
||||||
<p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
|
|
||||||
{reservationStatus.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</section>}
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { getBooks } from '../api/books';
|
import { getBooks } from '../api/books';
|
||||||
import { Link } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../context/AuthContext';
|
|
||||||
|
|
||||||
export default function Books() {
|
export default function Books() {
|
||||||
const { user } = useAuth();
|
|
||||||
const [books, setBooks] = useState([]);
|
const [books, setBooks] = useState([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
@@ -30,13 +27,10 @@ export default function Books() {
|
|||||||
return (
|
return (
|
||||||
<main>
|
<main>
|
||||||
<h1>Catalogue</h1>
|
<h1>Catalogue</h1>
|
||||||
{user?.role === 'admin' && <Link to="/books/new">+ Ajouter un livre</Link>}
|
|
||||||
<ul>
|
<ul>
|
||||||
{books.map((book) => (
|
{books.map((book) => (
|
||||||
<li key={book.isbn}>
|
<li key={book.isbn}>
|
||||||
<Link to={`/books/${book.isbn}`}>
|
<strong>{book.title}</strong> - {book.author}
|
||||||
<strong>{book.title}</strong> - {book.author}
|
|
||||||
</Link>
|
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -1,109 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { registerCustomer, findCustomerByPhone, addLoyaltyPoints, subtractLoyaltyPoints } from '../api/customers';
|
|
||||||
|
|
||||||
const initialForm = { firstName: '', lastName: '', phoneNumber: '' };
|
|
||||||
|
|
||||||
export default function Customers() {
|
|
||||||
const [form, setForm] = useState(initialForm);
|
|
||||||
const [registerMsg, setRegisterMsg] = useState(null);
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
|
||||||
const [pointsInput, setPointsInput] = useState('');
|
|
||||||
|
|
||||||
function handleChange(e) {
|
|
||||||
const { name, value } = e.target;
|
|
||||||
setForm((prev) => ({ ...prev, [name]: value }));
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleRegister(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
setSubmitting(true);
|
|
||||||
setRegisterMsg(null);
|
|
||||||
registerCustomer(form)
|
|
||||||
.then((response) => {
|
|
||||||
setRegisterMsg(`Client créé (id : ${response.data})`);
|
|
||||||
setForm(initialForm);
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(error);
|
|
||||||
setRegisterMsg('Erreur lors de la création du client.');
|
|
||||||
})
|
|
||||||
.finally(() => setSubmitting(false));
|
|
||||||
}
|
|
||||||
|
|
||||||
const [phone, setPhone] = useState('');
|
|
||||||
const [customer, setCustomer] = useState(null);
|
|
||||||
const [searchError, setSearchError] = useState(null);
|
|
||||||
|
|
||||||
function handleSearch(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
setSearchError(null);
|
|
||||||
setCustomer(null);
|
|
||||||
findCustomerByPhone(phone)
|
|
||||||
.then((response) => setCustomer(response.data))
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(error);
|
|
||||||
setSearchError('Aucun client trouvé avec ce numéro.');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function applyLoyalty(operation) {
|
|
||||||
const points = Number(pointsInput);
|
|
||||||
const action = operation === 'add' ? addLoyaltyPoints : subtractLoyaltyPoints;
|
|
||||||
|
|
||||||
action(customer.id, points)
|
|
||||||
.then((response) => {
|
|
||||||
setCustomer((prev) => ({ ...prev, loyaltyPoints: response.data }));
|
|
||||||
setPointsInput('');
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error(error);
|
|
||||||
if (error.response?.status === 400) setSearchError('Pas assez de points pour ce retrait.');
|
|
||||||
else setSearchError('Erreur lors de la mise à jour des points.');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<h1>Gestion des clients</h1>
|
|
||||||
|
|
||||||
<section>
|
|
||||||
<h2>Enregistrer un client</h2>
|
|
||||||
<form onSubmit={handleRegister}>
|
|
||||||
<label>Prénom
|
|
||||||
<input name="firstName" value={form.firstName} onChange={handleChange} required />
|
|
||||||
</label>
|
|
||||||
<label>Nom
|
|
||||||
<input name="lastName" value={form.lastName} onChange={handleChange} required />
|
|
||||||
</label>
|
|
||||||
<label>Téléphone
|
|
||||||
<input name="phoneNumber" value={form.phoneNumber} onChange={handleChange} required />
|
|
||||||
</label>
|
|
||||||
<button type="submit" disabled={submitting}>
|
|
||||||
{submitting ? 'Envoi…' : 'Créer le client'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
{registerMsg && <p>{registerMsg}</p>}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section>
|
|
||||||
<h2>Rechercher un client</h2>
|
|
||||||
<form onSubmit={handleSearch}>
|
|
||||||
<label>Téléphone
|
|
||||||
<input value={phone} onChange={(e) => setPhone(e.target.value)} required />
|
|
||||||
</label>
|
|
||||||
<button type="submit">Rechercher</button>
|
|
||||||
</form>
|
|
||||||
{searchError && <p>{searchError}</p>}
|
|
||||||
{customer && (
|
|
||||||
<div>
|
|
||||||
<p>{customer.firstName} {customer.lastName}</p>
|
|
||||||
<p>Téléphone : {customer.phoneNumber}</p>
|
|
||||||
<p><strong>Points de fidélité : {customer.loyaltyPoints}</strong></p>
|
|
||||||
<input type="number"value={pointsInput}onChange={(e) => setPointsInput(e.target.value)}placeholder="Nombre de points"/>
|
|
||||||
<button type="button" onClick={() => applyLoyalty('add')}>Ajouter</button>
|
|
||||||
<button type="button" onClick={() => applyLoyalty('subtract')}>Retirer</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import { useState } from 'react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { useAuth } from '../context/AuthContext';
|
|
||||||
|
|
||||||
export default function Login() {
|
|
||||||
const { login } = useAuth();
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const [form, setForm] = useState({ username: '', password: '' });
|
|
||||||
const [error, setError] = useState(null);
|
|
||||||
|
|
||||||
function handleSubmit(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
const ok = login(form.username, form.password);
|
|
||||||
if (ok) {
|
|
||||||
navigate('/');
|
|
||||||
} else {
|
|
||||||
setError('Identifiants incorrects.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<h1>Connexion</h1>
|
|
||||||
<form onSubmit={handleSubmit}>
|
|
||||||
<div>
|
|
||||||
<label>
|
|
||||||
Nom d'utilisateur :
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={form.username}
|
|
||||||
onChange={e => setForm(f => ({ ...f, username: e.target.value }))}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>
|
|
||||||
Mot de passe :
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
value={form.password}
|
|
||||||
onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<button type="submit">Se connecter</button>
|
|
||||||
{error && <p style={{ color: 'red' }}>{error}</p>}
|
|
||||||
</form>
|
|
||||||
<p>Comptes disponibles :</p>
|
|
||||||
<ul>
|
|
||||||
<li><strong>admin</strong> / admin (administrateur)</li>
|
|
||||||
<li><strong>alice (utilisateur)</strong> / bob (utilisateur)</li>
|
|
||||||
</ul>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
import { useReservations } from '../context/ReservationContext';
|
|
||||||
import { Link } from 'react-router-dom';
|
|
||||||
|
|
||||||
export default function Reservations() {
|
|
||||||
const { reservations, cancelReservation } = useReservations();
|
|
||||||
|
|
||||||
if (reservations.length === 0) {
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<h1>Mes réservations</h1>
|
|
||||||
<p>Aucune réservation pour le moment.</p>
|
|
||||||
<Link to="/books">← Retour au catalogue</Link>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<main>
|
|
||||||
<h1>Mes réservations</h1>
|
|
||||||
<ul>
|
|
||||||
{reservations.map(r => (
|
|
||||||
<li key={r.reservationId}>
|
|
||||||
<strong>{r.bookTitle}</strong> — {r.bookAuthor}
|
|
||||||
<br />
|
|
||||||
Téléphone : {r.phoneNumber}
|
|
||||||
<br />
|
|
||||||
Réservé le : {new Date(r.reservedAt).toLocaleDateString('fr-FR')}
|
|
||||||
<br />
|
|
||||||
Statut : {r.status}
|
|
||||||
<br />
|
|
||||||
<button onClick={() => cancelReservation(r.reservationId)}>Annuler</button>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</main>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# mylibrary — back-end Java (méthode BDD)
|
||||||
|
|
||||||
|
Back-end du projet **2026-DEV-BUT3**. Reproduit, en Java pur, le cœur métier
|
||||||
|
de l'API consommée par le front React `my-library/`.
|
||||||
|
|
||||||
|
## Méthode
|
||||||
|
|
||||||
|
Conformément au cours `maintenanceApplicativeCours1.pdf` (Behavior-Driven
|
||||||
|
Development), pour chaque comportement on :
|
||||||
|
|
||||||
|
1. Écrit le scénario attendu (en Gherkin / `.feature` ou en `@DisplayName` JUnit)
|
||||||
|
2. Écrit le test qui le vérifie
|
||||||
|
3. Implémente le code qui fait passer le test
|
||||||
|
|
||||||
|
## Structure (calquée sur le module `customer` fourni par le prof)
|
||||||
|
|
||||||
|
```
|
||||||
|
src/main/java/fr/iut_fbleau/but3/dev62/mylibrary/
|
||||||
|
├─ customer/ Module fourni par l'enseignant (intact)
|
||||||
|
│ ├─ CustomerInfo.java record d'entrée
|
||||||
|
│ ├─ CustomerDTO.java DTO de sortie
|
||||||
|
│ ├─ entity/ Customer (objet métier, règles fidélité)
|
||||||
|
│ ├─ exception/ Exceptions métier
|
||||||
|
│ ├─ converter/ Mapping Info <-> entity <-> DTO
|
||||||
|
│ ├─ validator/ Règles de validation
|
||||||
|
│ ├─ repository/ Stockage en mémoire (List)
|
||||||
|
│ └─ usecase/ Cas d'usage (orchestration)
|
||||||
|
└─ book/ Module développé en miroir (notre travail)
|
||||||
|
└─ … (mêmes sous-paquets, même découpage)
|
||||||
|
|
||||||
|
src/test/java/.../mylibrary/
|
||||||
|
├─ customer/ Tests JUnit fournis par l'enseignant
|
||||||
|
├─ book/ Tests JUnit que nous avons écrits
|
||||||
|
└─ features/
|
||||||
|
├─ RunCucumberTest.java (du prof, intact)
|
||||||
|
├─ client/CustomerSteps.java (du prof, intact)
|
||||||
|
├─ book/BookSteps.java (notre travail)
|
||||||
|
└─ resources/features/
|
||||||
|
├─ client.feature (du prof, intact)
|
||||||
|
└─ book.feature (notre travail)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dépendances
|
||||||
|
|
||||||
|
Strictement les mêmes que dans le template du prof :
|
||||||
|
|
||||||
|
- JUnit 5 (jupiter-api, params, engine + platform-suite, platform-engine, platform-launcher)
|
||||||
|
- Mockito (core, junit-jupiter)
|
||||||
|
- Cucumber (cucumber-java, cucumber-junit-platform-engine)
|
||||||
|
- Lombok
|
||||||
|
|
||||||
|
## Build & test
|
||||||
|
|
||||||
|
Pré-requis : **JDK 21** + **Maven 3.9+**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -f mylibrary test
|
||||||
|
```
|
||||||
|
|
||||||
|
Cette commande exécute :
|
||||||
|
|
||||||
|
- les tests unitaires JUnit (entity, validator, converter, repository, usecase, exceptions)
|
||||||
|
- les scénarios Cucumber (`client.feature` + `book.feature`) via `RunCucumberTest`
|
||||||
|
|
||||||
|
## Périmètre couvert
|
||||||
|
|
||||||
|
Conformément à la consigne (« reproduire le strict nécessaire pour démontrer
|
||||||
|
la maîtrise »), l'API se limite aux deux domaines présents dans le swagger
|
||||||
|
qui structurent l'app React :
|
||||||
|
|
||||||
|
- **Catalogue** (`book`) : enregistrer, consulter par ISBN, lister tous les livres,
|
||||||
|
refuser ISBN dupliqué, refuser un livre invalide, gérer le stock.
|
||||||
|
- **Comptes clients** (`customer`) : enregistrer, consulter par téléphone, mettre
|
||||||
|
à jour, supprimer, ajouter / retirer des points de fidélité (module fourni).
|
||||||
|
|
||||||
|
L'exposition HTTP réelle utilisée par les développeurs front est l'API du prof
|
||||||
|
(`mylibrary-0.0.1-SNAPSHOT.jar`) ; ce module sert à démontrer la maîtrise
|
||||||
|
de la **conception métier en BDD/TDD**.
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package fr.iut_fbleau.but3.dev62.mylibrary.book.usecase;
|
||||||
|
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.converter.BookConverter;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.validator.BookValidator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public final class BookUseCase {
|
||||||
|
|
||||||
|
private final BookRepository bookRepository;
|
||||||
|
|
||||||
|
public BookUseCase(BookRepository bookRepository) {
|
||||||
|
this.bookRepository = bookRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long registerBook(BookInfo bookInfo) throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
BookValidator.validate(bookInfo);
|
||||||
|
if (bookRepository.existsByIsbn(bookInfo.isbn())) {
|
||||||
|
throw new BookAlreadyExistsException(bookInfo.isbn());
|
||||||
|
}
|
||||||
|
Book toRegister = BookConverter.toDomain(bookInfo);
|
||||||
|
Book registered = bookRepository.save(toRegister);
|
||||||
|
return registered.getIsbn();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookDTO getBookByIsbn(long isbn) throws BookNotFoundException {
|
||||||
|
Optional<Book> optional = bookRepository.findByIsbn(isbn);
|
||||||
|
if (optional.isEmpty()) {
|
||||||
|
throw new BookNotFoundException(isbn);
|
||||||
|
}
|
||||||
|
return BookConverter.toDTO(optional.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BookDTO> getAllBooks() {
|
||||||
|
return bookRepository.findAll().stream()
|
||||||
|
.map(BookConverter::toDTO)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
package fr.iut_fbleau.but3.dev62.mylibrary.book.usecase;
|
||||||
|
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Category;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class BookUseCaseTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private BookUseCase bookUseCase;
|
||||||
|
|
||||||
|
private BookInfo validInfo;
|
||||||
|
private Book validBook;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
validInfo = new BookInfo(
|
||||||
|
9780321125217L,
|
||||||
|
"DDD",
|
||||||
|
"Evans",
|
||||||
|
"Addison-Wesley",
|
||||||
|
LocalDate.of(2003, 8, 22),
|
||||||
|
54.99,
|
||||||
|
10,
|
||||||
|
List.of(Category.SCIENCE),
|
||||||
|
"desc",
|
||||||
|
"EN"
|
||||||
|
);
|
||||||
|
validBook = Book.builder()
|
||||||
|
.isbn(validInfo.isbn())
|
||||||
|
.title(validInfo.title())
|
||||||
|
.author(validInfo.author())
|
||||||
|
.publisher(validInfo.publisher())
|
||||||
|
.publicationDate(validInfo.publicationDate())
|
||||||
|
.price(validInfo.price())
|
||||||
|
.quantity(validInfo.quantity())
|
||||||
|
.categories(validInfo.categories())
|
||||||
|
.description(validInfo.description())
|
||||||
|
.language(validInfo.language())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("registerBook tests")
|
||||||
|
class RegisterTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should register a new book and return its ISBN")
|
||||||
|
void testRegisterBook() throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
when(bookRepository.existsByIsbn(validInfo.isbn())).thenReturn(false);
|
||||||
|
when(bookRepository.save(any(Book.class))).thenReturn(validBook);
|
||||||
|
|
||||||
|
long isbn = bookUseCase.registerBook(validInfo);
|
||||||
|
|
||||||
|
assertEquals(validInfo.isbn(), isbn);
|
||||||
|
verify(bookRepository).existsByIsbn(validInfo.isbn());
|
||||||
|
verify(bookRepository).save(any(Book.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should reject invalid book information without touching the repository")
|
||||||
|
void testRegisterInvalidBook() {
|
||||||
|
BookInfo invalid = new BookInfo(0L, "", "", "", null, -1, -1, null, "", "");
|
||||||
|
assertThrows(NotValidBookException.class, () -> bookUseCase.registerBook(invalid));
|
||||||
|
verifyNoInteractions(bookRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should reject duplicate ISBN")
|
||||||
|
void testRegisterDuplicate() {
|
||||||
|
when(bookRepository.existsByIsbn(validInfo.isbn())).thenReturn(true);
|
||||||
|
assertThrows(BookAlreadyExistsException.class, () -> bookUseCase.registerBook(validInfo));
|
||||||
|
verify(bookRepository).existsByIsbn(validInfo.isbn());
|
||||||
|
verify(bookRepository, never()).save(any(Book.class));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("getBookByIsbn tests")
|
||||||
|
class GetByIdTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should return the BookDTO when ISBN exists")
|
||||||
|
void testGetById() throws BookNotFoundException {
|
||||||
|
when(bookRepository.findByIsbn(validInfo.isbn())).thenReturn(Optional.of(validBook));
|
||||||
|
|
||||||
|
BookDTO dto = bookUseCase.getBookByIsbn(validInfo.isbn());
|
||||||
|
|
||||||
|
assertEquals(validInfo.isbn(), dto.getIsbn());
|
||||||
|
assertEquals(validInfo.title(), dto.getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should throw when ISBN does not exist")
|
||||||
|
void testGetByIdNotFound() {
|
||||||
|
when(bookRepository.findByIsbn(99L)).thenReturn(Optional.empty());
|
||||||
|
assertThrows(BookNotFoundException.class, () -> bookUseCase.getBookByIsbn(99L));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("getAllBooks tests")
|
||||||
|
class GetAllBooksTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should map every book returned by the repository to a DTO")
|
||||||
|
void testGetAllBooks() {
|
||||||
|
when(bookRepository.findAll()).thenReturn(List.of(validBook));
|
||||||
|
|
||||||
|
List<BookDTO> result = bookUseCase.getAllBooks();
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals(validBook.getIsbn(), result.getFirst().getIsbn());
|
||||||
|
assertEquals(validBook.getTitle(), result.getFirst().getTitle());
|
||||||
|
verify(bookRepository).findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should return an empty list when no book is stored")
|
||||||
|
void testGetAllBooksWhenEmpty() {
|
||||||
|
when(bookRepository.findAll()).thenReturn(List.of());
|
||||||
|
|
||||||
|
List<BookDTO> result = bookUseCase.getAllBooks();
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
package fr.iut_fbleau.but3.dev62.mylibrary.features.book;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Category;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.usecase.BookUseCase;
|
||||||
|
import io.cucumber.datatable.DataTable;
|
||||||
|
import io.cucumber.java.en.And;
|
||||||
|
import io.cucumber.java.en.Given;
|
||||||
|
import io.cucumber.java.en.Then;
|
||||||
|
import io.cucumber.java.en.When;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class BookSteps {
|
||||||
|
|
||||||
|
private final BookRepository bookRepository = new BookRepository();
|
||||||
|
private final BookUseCase bookUseCase = new BookUseCase(bookRepository);
|
||||||
|
|
||||||
|
private long lastRegisteredIsbn;
|
||||||
|
private BookDTO retrievedBook;
|
||||||
|
private List<BookDTO> allBooks;
|
||||||
|
private Exception lastException;
|
||||||
|
|
||||||
|
@Given("the catalog has the following books:")
|
||||||
|
public void theCatalogHasTheFollowingBooks(DataTable dataTable) throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
bookRepository.deleteAll();
|
||||||
|
for (Map<String, String> row : dataTable.asMaps(String.class, String.class)) {
|
||||||
|
bookUseCase.registerBook(toBookInfo(row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I register a new book with the following information:")
|
||||||
|
public void iRegisterANewBook(DataTable dataTable) throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
Map<String, String> row = dataTable.asMaps(String.class, String.class).getFirst();
|
||||||
|
lastRegisteredIsbn = bookUseCase.registerBook(toBookInfo(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I try to register a new book with the following information:")
|
||||||
|
public void iTryToRegisterANewBook(DataTable dataTable) {
|
||||||
|
Map<String, String> row = dataTable.asMaps(String.class, String.class).getFirst();
|
||||||
|
lastException = assertThrows(Exception.class, () -> bookUseCase.registerBook(toBookInfo(row)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I request the book with isbn {long}")
|
||||||
|
public void iRequestTheBook(long isbn) throws BookNotFoundException {
|
||||||
|
retrievedBook = bookUseCase.getBookByIsbn(isbn);
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I list all books")
|
||||||
|
public void iListAllBooks() {
|
||||||
|
allBooks = bookUseCase.getAllBooks();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("the book is created")
|
||||||
|
public void theBookIsCreated() {
|
||||||
|
assertNotNull(lastRegisteredIsbn);
|
||||||
|
}
|
||||||
|
|
||||||
|
@And("the catalog now has {int} book(s)")
|
||||||
|
public void theCatalogNowHasNBooks(int expected) {
|
||||||
|
assertEquals(expected, bookRepository.findAll().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("the registration fails with a {string}")
|
||||||
|
public void theRegistrationFailsWith(String exceptionSimpleName) {
|
||||||
|
assertNotNull(lastException);
|
||||||
|
assertEquals(exceptionSimpleName, lastException.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("I receive a book whose title is {string}")
|
||||||
|
public void iReceiveABookWhoseTitleIs(String title) {
|
||||||
|
assertNotNull(retrievedBook);
|
||||||
|
assertEquals(title, retrievedBook.getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("I receive {int} book(s)")
|
||||||
|
public void iReceiveNBooks(int expected) {
|
||||||
|
assertNotNull(allBooks);
|
||||||
|
assertEquals(expected, allBooks.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BookInfo toBookInfo(Map<String, String> row) {
|
||||||
|
return new BookInfo(
|
||||||
|
Long.parseLong(row.get("isbn")),
|
||||||
|
row.get("titre"),
|
||||||
|
row.get("auteur"),
|
||||||
|
row.get("editeur"),
|
||||||
|
LocalDate.parse(row.get("datePublication")),
|
||||||
|
Double.parseDouble(row.get("prix")),
|
||||||
|
Integer.parseInt(row.get("stock")),
|
||||||
|
List.of(Category.valueOf(row.get("categorie"))),
|
||||||
|
"",
|
||||||
|
row.get("langue")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# language: en
|
||||||
|
|
||||||
|
Feature: Manage book catalog
|
||||||
|
|
||||||
|
Scenario: Register a new book in the catalog
|
||||||
|
When I register a new book with the following information:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
Then the book is created
|
||||||
|
And the catalog now has 1 book
|
||||||
|
|
||||||
|
Scenario: Reject duplicate ISBN
|
||||||
|
Given the catalog has the following books:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
When I try to register a new book with the following information:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD copy | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
Then the registration fails with a "BookAlreadyExistsException"
|
||||||
|
|
||||||
|
Scenario: Reject invalid book information
|
||||||
|
When I try to register a new book with the following information:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | | Evans | AW | 2003-08-22 | 0 | -1 | SCIENCE | EN |
|
||||||
|
Then the registration fails with a "NotValidBookException"
|
||||||
|
|
||||||
|
Scenario: Retrieve a book by its ISBN
|
||||||
|
Given the catalog has the following books:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
When I request the book with isbn 9780321125217
|
||||||
|
Then I receive a book whose title is "DDD"
|
||||||
|
|
||||||
|
Scenario: List all books in the catalog
|
||||||
|
Given the catalog has the following books:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
| 9780132350884 | Clean | Martin | PH | 2008-08-01 | 30.00 | 5 | SCIENCE | EN |
|
||||||
|
When I list all books
|
||||||
|
Then I receive 2 books
|
||||||
Reference in New Issue
Block a user