36 Commits

Author SHA1 Message Date
AISSI-JUDE-CHRIST 7192efcfd9 correction syntaxe appliquer promo 2026-06-15 23:42:20 +02:00
Riad KARA-MOSTEFA 677cb6249a Merge pull request 'Fonctionnalitees/appliquer promo' (#9) from fonctionnalitees/appliquer-promo into main
Reviewed-on: #9
2026-06-15 23:30:29 +02:00
AISSI-JUDE-CHRIST 65b9eed6dc Amelioration de linterface et corrections bugs 2026-06-14 20:45:13 +02:00
AISSI-JUDE-CHRIST dabf1df6b9 Commandes groupées 2026-06-14 20:25:52 +02:00
AISSI-JUDE-CHRIST e8ac8f0c54 prets entre utilisateurs 2026-06-14 18:23:57 +02:00
RKaraMos_EVO 24849c6414 feat(front): promoCode validation + estimation du total via API 2026-06-14 16:47:24 +02:00
RKaraMos_EVO d7dfec49fd feat(front): ajouter champ promoCode pour commandes 2026-06-14 16:44:55 +02:00
AISSI-JUDE-CHRIST 0d9f8dc539 Créer un abonnement 2026-06-14 16:12:47 +02:00
Riad KARA-MOSTEFA 4197f99116 Merge pull request 'Api java' (#8) from api_java into main
Reviewed-on: #8
2026-06-14 15:28:23 +02:00
RKaraMos_EVO 092a020059 ajout du scenario cucumber et du README 2026-06-14 15:22:36 +02:00
RKaraMos_EVO 8708686994 ajout du usecase pour les livres + tests 2026-06-14 15:22:29 +02:00
AISSI-JUDE-CHRIST 0d37efd227 merge retours livres admin 2026-06-14 00:10:02 +02:00
Adrien DICK 1cf4bed83b Merge pull request ' Faire une commande' (#7) from Commande into main
Reviewed-on: #7
2026-06-13 11:34:02 +02:00
Adrien DICK 0ba4e5599e Faire une commande 2026-06-13 05:32:59 -04:00
AISSI-JUDE-CHRIST 587e81816c Gérer les retours de livres par l'admin 2026-06-13 01:11:27 +02:00
AISSI-JUDE-CHRIST 8359f21e07 Merge 2026-06-13 00:48:12 +02:00
Riad KARA-MOSTEFA e3c02a6fc8 Merge pull request 'Api java' (#6) from api_java into main
Reviewed-on: #6
2026-06-12 23:34:30 +02:00
RKaraMos_EVO a595750194 ajout du repository en memoire + tests 2026-06-12 23:32:35 +02:00
RKaraMos_EVO 00e90aaa0c ajout du converter Info-entity-DTO + tests 2026-06-12 23:32:26 +02:00
RKaraMos_EVO 009ac7f5f7 ajout du validator pour les livres + tests 2026-06-12 23:32:17 +02:00
RKaraMos_EVO 9080b8e67e ajout entity Book et BookDTO + tests 2026-06-12 23:30:58 +02:00
RKaraMos_EVO 179f259c3d ajout des exceptions du module book et leurs tests 2026-06-12 23:30:45 +02:00
AISSI-JUDE-CHRIST bfd1f600de Gerer un avis 2026-06-12 22:58:43 +02:00
AISSI-JUDE-CHRIST 52213fce0b re Correction page login 2026-06-12 21:37:12 +02:00
AISSI-JUDE-CHRIST 7117aba838 Correction page login 2026-06-12 21:35:40 +02:00
AISSI-JUDE-CHRIST 010ec9c11a reservation livres 2026-06-11 23:08:21 +02:00
AISSI-JUDE-CHRIST de47c293b8 correction affiche livre 2026-06-11 22:36:47 +02:00
AISSI-JUDE-CHRIST 4ae227d79d ajout authentification admin/user 2026-06-11 22:23:39 +02:00
Adrien DICK 8f3451adc0 Merge pull request 'Gestion client' (#5) from GestionClient into main
Reviewed-on: #5
2026-06-11 16:49:36 +02:00
Riad KARA-MOSTEFA 9916b02ef6 Merge pull request 'Api java' (#4) from api_java into main
Reviewed-on: #4
2026-06-11 14:28:28 +02:00
Adrien DICK e33acdf151 Ajouter et Retirer des points de fidélité 2026-06-11 07:59:03 -04:00
Adrien DICK ccafc24f72 Ajouter un client 2026-06-11 07:27:37 -04:00
Adrien DICK c811c373d5 Merge pull request ' Voir le detail d'un livre' (#3) from DetailLivre into main
Reviewed-on: #3
2026-06-11 11:55:29 +02:00
Adrien DICK 1f9a1e9af8 Voir le detail d'un livre 2026-06-11 05:52:26 -04:00
Adrien DICK e438373370 Merge pull request ' Enregistrer un livre' (#2) from EnregistrerLivre into main
Reviewed-on: #2
2026-06-11 11:35:23 +02:00
Adrien DICK 2c0f30f0a2 Enregistrer un livre 2026-06-11 05:15:30 -04:00
51 changed files with 3130 additions and 26 deletions
+34 -3
View File
@@ -1,19 +1,50 @@
import { Routes, Route } from 'react-router-dom'; import { Routes, Route, Navigate } 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 Returns from './pages/Returns';
import Subscription from './pages/Subscription';
import Loans from './pages/Loans';
import GroupOrders from './pages/GroupOrders';
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="orders" element={<Orders />} /> <Route path="books/:bookId" element={<RequireAuth><BookDetail /></RequireAuth>} />
<Route path="profile" element={<Profile />} /> <Route path="books/new" element={<RequireAdmin><AddBook /></RequireAdmin>} />
<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="returns" element={<RequireAdmin><Returns /></RequireAdmin>} />
<Route path="subscription" element={<RequireAuth><Subscription /></RequireAuth>} />
<Route path="loans" element={<RequireAuth><Loans /></RequireAuth>} />
<Route path="group-orders" element={<RequireAuth><GroupOrders /></RequireAuth>} />
<Route path="*" element={<NotFound />} /> <Route path="*" element={<NotFound />} />
</Route> </Route>
</Routes> </Routes>
+17
View File
@@ -0,0 +1,17 @@
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);
}
-5
View File
@@ -1,5 +0,0 @@
import client from './client';
export function getBooks(page = 0, size = 20) {
return client.get('/api/books', { params: { page, size } });
}
+17
View File
@@ -0,0 +1,17 @@
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 } });
}
+5
View File
@@ -0,0 +1,5 @@
import client from './client';
export function createOrder(order) {
return client.post('/api/orders', order);
}
+26 -5
View File
@@ -1,7 +1,16 @@
import { Link } from 'react-router-dom'; import { Link, useNavigate } 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>
@@ -9,13 +18,25 @@ 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>
<li><Link to="/orders">Commandes</Link></li> {user && <li><Link to="/orders">Commandes</Link></li>}
<li><Link to="/profile">Mon compte</Link></li> {user?.role === 'user' && <li><Link to="/reservations">Mes réservations</Link></li>}
{user?.role === 'user' && <li><Link to="/subscription">Mon abonnement</Link></li>}
{user?.role === 'user' && <li><Link to="/loans">Mes prêts</Link></li>}
{user && <li><Link to="/group-orders">Commandes groupées</Link></li>}
{user && <li><Link to="/profile">Mon compte</Link></li>}
{user?.role === 'admin' && <li><Link to="/customers">Clients</Link></li>}
{user?.role === 'admin' && <li><Link to="/returns">Retours</Link></li>}
</ul> </ul>
<div className="navbar__actions"> <div className="navbar__actions">
<button className="btn-ghost">Connexion</button> {user ? (
<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>
); );
+39
View File
@@ -0,0 +1,39 @@
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);
}
@@ -0,0 +1,59 @@
import { createContext, useContext, useState } from 'react';
const GroupOrderContext = createContext(null);
export function GroupOrderProvider({ children }) {
const [groups, setGroups] = useState(() => {
const saved = localStorage.getItem('groupOrders');
return saved ? JSON.parse(saved) : [];
});
function createGroup(creatorPhone) {
const group = {
id: crypto.randomUUID(),
creatorPhone,
orders: [],
status: 'OPEN',
createdAt: new Date().toISOString(),
};
const updated = [...groups, group];
setGroups(updated);
localStorage.setItem('groupOrders', JSON.stringify(updated));
return group;
}
function addOrderToGroup(groupId, phoneNumber, bookId, bookTitle, quantity) {
const updated = groups.map(g => {
if (g.id !== groupId) return g;
const order = {
orderId: crypto.randomUUID(),
phoneNumber,
bookId,
bookTitle,
quantity: Number(quantity),
addedAt: new Date().toISOString(),
};
return { ...g, orders: [...g.orders, order] };
});
setGroups(updated);
localStorage.setItem('groupOrders', JSON.stringify(updated));
}
function closeGroup(groupId) {
const updated = groups.map(g =>
g.id === groupId ? { ...g, status: 'CLOSED' } : g
);
setGroups(updated);
localStorage.setItem('groupOrders', JSON.stringify(updated));
}
return (
<GroupOrderContext.Provider value={{ groups, createGroup, addOrderToGroup, closeGroup }}>
{children}
</GroupOrderContext.Provider>
);
}
export function useGroupOrders() {
return useContext(GroupOrderContext);
}
+45
View File
@@ -0,0 +1,45 @@
import { createContext, useContext, useState } from 'react';
const LoanContext = createContext(null);
export function LoanProvider({ children }) {
const [loans, setLoans] = useState(() => {
const saved = localStorage.getItem('loans');
return saved ? JSON.parse(saved) : [];
});
function addLoan(book, borrowerUsername, dueDate) {
const loan = {
loanId: crypto.randomUUID(),
bookId: book.isbn,
bookTitle: book.title,
bookAuthor: book.author,
borrowerUsername,
dueDate,
status: 'ACTIVE',
loanedAt: new Date().toISOString(),
};
const updated = [...loans, loan];
setLoans(updated);
localStorage.setItem('loans', JSON.stringify(updated));
return loan;
}
function returnLoan(loanId) {
const updated = loans.map(l =>
l.loanId === loanId ? { ...l, status: 'RETURNED' } : l
);
setLoans(updated);
localStorage.setItem('loans', JSON.stringify(updated));
}
return (
<LoanContext.Provider value={{ loans, addLoan, returnLoan }}>
{children}
</LoanContext.Provider>
);
}
export function useLoans() {
return useContext(LoanContext);
}
@@ -0,0 +1,42 @@
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);
}
+36
View File
@@ -0,0 +1,36 @@
import { createContext, useContext, useState } from 'react';
const ReturnContext = createContext(null);
export function ReturnProvider({ children }) {
const [returns, setReturns] = useState(() => {
const saved = localStorage.getItem('returns');
return saved ? JSON.parse(saved) : [];
});
function addReturn(bookId, bookTitle, customerPhone, reason) {
const bookReturn = {
returnId: crypto.randomUUID(),
bookId,
bookTitle,
customerPhone,
reason,
status: 'PROCESSED',
returnedAt: new Date().toISOString(),
};
const updated = [...returns, bookReturn];
setReturns(updated);
localStorage.setItem('returns', JSON.stringify(updated));
return bookReturn;
}
return (
<ReturnContext.Provider value={{ returns, addReturn }}>
{children}
</ReturnContext.Provider>
);
}
export function useReturns() {
return useContext(ReturnContext);
}
+40
View File
@@ -0,0 +1,40 @@
import { createContext, useContext, useState } from 'react';
const ReviewContext = createContext(null);
export function ReviewProvider({ children }) {
const [reviews, setReviews] = useState(() => {
const saved = localStorage.getItem('reviews');
return saved ? JSON.parse(saved) : [];
});
function addReview(bookId, bookTitle, username, rating, comment) {
const review = {
reviewId: crypto.randomUUID(),
bookId,
bookTitle,
username,
rating,
comment,
createdAt: new Date().toISOString(),
};
const updated = [...reviews, review];
setReviews(updated);
localStorage.setItem('reviews', JSON.stringify(updated));
return review;
}
function getReviewsByBook(bookId) {
return reviews.filter(r => String(r.bookId) === String(bookId));
}
return (
<ReviewContext.Provider value={{ reviews, addReview, getReviewsByBook }}>
{children}
</ReviewContext.Provider>
);
}
export function useReviews() {
return useContext(ReviewContext);
}
@@ -0,0 +1,50 @@
import { createContext, useContext, useState } from 'react';
const SubscriptionContext = createContext(null);
const PLANS = [
{ id: 'basic', name: 'Basic', price: 9.99, description: '2 livres par mois' },
{ id: 'standard', name: 'Standard', price: 14.99, description: '5 livres par mois' },
{ id: 'premium', name: 'Premium', price: 24.99, description: 'Livres illimités par mois' },
];
export { PLANS };
export function SubscriptionProvider({ children }) {
const [subscription, setSubscription] = useState(() => {
const saved = localStorage.getItem('subscription');
return saved ? JSON.parse(saved) : null;
});
function subscribe(planId, phoneNumber) {
const plan = PLANS.find(p => p.id === planId);
const newSubscription = {
subscriptionId: crypto.randomUUID(),
planId,
planName: plan.name,
price: plan.price,
phoneNumber,
status: 'ACTIVE',
startDate: new Date().toISOString(),
};
setSubscription(newSubscription);
localStorage.setItem('subscription', JSON.stringify(newSubscription));
return newSubscription;
}
function cancelSubscription() {
const updated = { ...subscription, status: 'CANCELLED' };
setSubscription(updated);
localStorage.setItem('subscription', JSON.stringify(updated));
}
return (
<SubscriptionContext.Provider value={{ subscription, subscribe, cancelSubscription, PLANS }}>
{children}
</SubscriptionContext.Provider>
);
}
export function useSubscription() {
return useContext(SubscriptionContext);
}
+22 -1
View File
@@ -1,6 +1,13 @@
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 { ReviewProvider } from './context/ReviewContext';
import { ReturnProvider } from './context/ReturnContext';
import { SubscriptionProvider } from './context/SubscriptionContext';
import { LoanProvider } from './context/LoanContext';
import { GroupOrderProvider } from './context/GroupOrderContext';
import App from './App'; import App from './App';
import './styles/global.css'; import './styles/global.css';
@@ -8,7 +15,21 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( root.render(
<React.StrictMode> <React.StrictMode>
<BrowserRouter> <BrowserRouter>
<App /> <AuthProvider>
<ReservationProvider>
<ReviewProvider>
<ReturnProvider>
<SubscriptionProvider>
<LoanProvider>
<GroupOrderProvider>
<App />
</GroupOrderProvider>
</LoanProvider>
</SubscriptionProvider>
</ReturnProvider>
</ReviewProvider>
</ReservationProvider>
</AuthProvider>
</BrowserRouter> </BrowserRouter>
</React.StrictMode> </React.StrictMode>
); );
+105
View File
@@ -0,0 +1,105 @@
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>
);
}
+158
View File
@@ -0,0 +1,158 @@
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';
import { useReviews } from '../context/ReviewContext';
import { useSubscription } from '../context/SubscriptionContext';
export default function BookDetail() {
const { user } = useAuth();
const { subscription } = useSubscription();
const { addReservation, reservations } = useReservations();
const { addReview, getReviewsByBook } = useReviews();
const [rating, setRating] = useState(5);
const [comment, setComment] = useState('');
const [reviewStatus, setReviewStatus] = useState(null);
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('');
}
function handleReview(e) {
e.preventDefault();
addReview(book.isbn, book.title, user.username, Number(rating), comment);
setReviewStatus({ success: true, message: 'Avis publié avec succès !' });
setComment('');
setRating(5);
}
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>}
<section>
<h2>Avis des lecteurs</h2>
{getReviewsByBook(book.isbn).length === 0 ? (
<p>Aucun avis pour le moment.</p>
) : (
<ul>
{getReviewsByBook(book.isbn).map(r => (
<li key={r.reviewId}>
<strong>{r.username}</strong> {'*'.repeat(r.rating)}
<br />
{r.comment}
<br />
<small>{new Date(r.createdAt).toLocaleDateString('fr-FR')}</small>
</li>
))}
</ul>
)}
{user?.role === 'user' && (
<form onSubmit={handleReview}>
<h3>Laisser un avis</h3>
<label>
Note :
<select value={rating} onChange={e => setRating(e.target.value)}>
<option value={1}>*</option>
<option value={2}>**</option>
<option value={3}>***</option>
<option value={4}>****</option>
<option value={5}>*****</option>
</select>
</label>
<label>
Commentaire :
<textarea value={comment} onChange={e => setComment(e.target.value)} required />
</label>
<button type="submit">Publier l'avis</button>
</form>
)}
{reviewStatus && (
<p style={{ color: reviewStatus.success ? 'green' : 'red' }}>
{reviewStatus.message}
</p>
)}
</section>
{user?.role === 'user' && (
<section>
<h2>Réserver ce livre</h2>
{!subscription || subscription.status !== 'ACTIVE' ? (
<p>
Vous devez avoir un abonnement actif pour réserver un livre.{' '}
<Link to="/subscription">S'abonner</Link>
</p>
) : (() => {
const QUOTAS = { basic: 2, standard: 5, premium: Infinity };
const quota = QUOTAS[subscription.planId];
const thisMonthStart = new Date();
thisMonthStart.setDate(1);
thisMonthStart.setHours(0, 0, 0, 0);
const usedThisMonth = reservations.filter(r =>
new Date(r.reservedAt) >= thisMonthStart
).length;
const remaining = quota - usedThisMonth;
if (remaining <= 0) {
return (
<p style={{ color: 'orange' }}>
Vous avez atteint votre quota de {quota} réservation(s) ce mois-ci.
<Link to="/subscription"> Passer au plan supérieur</Link>
</p>
);
}
return (
<>
<p>Réservations restantes ce mois : <strong>{remaining === Infinity ? 'illimitées' : remaining}</strong></p>
<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>
);
}
+16 -6
View File
@@ -1,7 +1,10 @@
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);
@@ -26,14 +29,21 @@ export default function Books() {
return ( return (
<main> <main>
<h1>Catalogue</h1> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1rem' }}>
<ul> <h1 style={{ margin: 0 }}>Catalogue</h1>
{user?.role === 'admin' && <Link to="/books/new">+ Ajouter un livre</Link>}
</div>
<div className="card-grid">
{books.map((book) => ( {books.map((book) => (
<li key={book.isbn}> <Link to={`/books/${book.isbn}`} key={book.isbn} style={{ textDecoration: 'none', color: 'inherit' }}>
<strong>{book.title}</strong> - {book.author} <div className="card">
</li> <h3>{book.title}</h3>
<p>{book.author}</p>
<p style={{ marginTop: '0.5rem', fontSize: '0.8rem', color: '#999' }}>ISBN : {book.isbn}</p>
</div>
</Link>
))} ))}
</ul> </div>
</main> </main>
); );
} }
+109
View File
@@ -0,0 +1,109 @@
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>
);
}
+167
View File
@@ -0,0 +1,167 @@
import { useState } from 'react';
import { useGroupOrders } from '../context/GroupOrderContext';
import { useAuth } from '../context/AuthContext';
export default function GroupOrders() {
const { groups, createGroup, addOrderToGroup, closeGroup } = useGroupOrders();
const { user } = useAuth();
const [creatorPhone, setCreatorPhone] = useState('');
const [joinGroupId, setJoinGroupId] = useState('');
const [joinForm, setJoinForm] = useState({ phoneNumber: '', bookId: '', bookTitle: '', quantity: 1 });
const [joinStatus, setJoinStatus] = useState({});
const [createStatus, setCreateStatus] = useState(null);
function handleCreateGroup(e) {
e.preventDefault();
const group = createGroup(creatorPhone);
setCreateStatus(`Groupe créé ! ID : ${group.id}`);
setCreatorPhone('');
}
function handleJoinGroup(e) {
e.preventDefault();
const group = groups.find(g => g.id === joinGroupId);
if (!group) {
setJoinStatus(prev => ({ ...prev, [joinGroupId]: 'Groupe introuvable.' }));
return;
}
if (group.status === 'CLOSED') {
setJoinStatus(prev => ({ ...prev, [joinGroupId]: 'Ce groupe est fermé.' }));
return;
}
addOrderToGroup(joinGroupId, joinForm.phoneNumber, joinForm.bookId, joinForm.bookTitle, joinForm.quantity);
setJoinStatus(prev => ({ ...prev, [joinGroupId]: 'Commande ajoutée au groupe !' }));
setJoinForm({ phoneNumber: '', bookId: '', bookTitle: '', quantity: 1 });
}
const openGroups = groups.filter(g => g.status === 'OPEN');
const closedGroups = groups.filter(g => g.status === 'CLOSED');
return (
<main>
<h1>Commandes groupées</h1>
<section>
<h2>Créer un groupe</h2>
<form onSubmit={handleCreateGroup}>
<label>
Votre téléphone :
<input
type="tel"
value={creatorPhone}
onChange={e => setCreatorPhone(e.target.value)}
placeholder="0612345678"
required
/>
</label>
<button type="submit">Créer un groupe</button>
</form>
{createStatus && <p style={{ color: 'green' }}>{createStatus}</p>}
</section>
<section>
<h2>Rejoindre un groupe</h2>
<form onSubmit={handleJoinGroup}>
<label>
ID du groupe :
<input
value={joinGroupId}
onChange={e => setJoinGroupId(e.target.value)}
placeholder="Collez l'ID du groupe ici"
required
/>
</label>
<label>
Votre téléphone :
<input
type="tel"
value={joinForm.phoneNumber}
onChange={e => setJoinForm(prev => ({ ...prev, phoneNumber: e.target.value }))}
placeholder="0612345678"
required
/>
</label>
<label>
ISBN du livre :
<input
value={joinForm.bookId}
onChange={e => setJoinForm(prev => ({ ...prev, bookId: e.target.value }))}
placeholder="9782070361038"
required
/>
</label>
<label>
Titre du livre :
<input
value={joinForm.bookTitle}
onChange={e => setJoinForm(prev => ({ ...prev, bookTitle: e.target.value }))}
placeholder="Nom du livre"
required
/>
</label>
<label>
Quantité :
<input
type="number"
min="1"
value={joinForm.quantity}
onChange={e => setJoinForm(prev => ({ ...prev, quantity: e.target.value }))}
required
/>
</label>
<button type="submit">Rejoindre</button>
</form>
{joinStatus[joinGroupId] && (
<p style={{ color: joinStatus[joinGroupId].includes('introuvable') || joinStatus[joinGroupId].includes('fermé') ? 'red' : 'green' }}>
{joinStatus[joinGroupId]}
</p>
)}
</section>
<section>
<h2>Groupes ouverts ({openGroups.length})</h2>
{openGroups.length === 0 ? (
<p>Aucun groupe ouvert.</p>
) : (
<ul>
{openGroups.map(g => (
<li key={g.id}>
<strong>Groupe {g.id.slice(0, 8)}</strong>
<br />
Créé par : {g.creatorPhone}
<br />
Créé le : {new Date(g.createdAt).toLocaleDateString('fr-FR')}
<br />
Participants : {g.orders.length}
{g.orders.length > 0 && (
<ul>
{g.orders.map(o => (
<li key={o.orderId}>
{o.phoneNumber} , {o.bookTitle} (x{o.quantity})
</li>
))}
</ul>
)}
<button onClick={() => closeGroup(g.id)}>Fermer le groupe</button>
</li>
))}
</ul>
)}
</section>
{closedGroups.length > 0 && (
<section>
<h2>Groupes fermés ({closedGroups.length})</h2>
<ul>
{closedGroups.map(g => (
<li key={g.id}>
<strong>Groupe {g.id.slice(0, 8)}</strong> , {g.orders.length} commande(s) , <small>Fermé </small>
</li>
))}
</ul>
</section>
)}
</main>
);
}
+20 -1
View File
@@ -1,9 +1,28 @@
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import '../styles/home.css'; import { useAuth } from '../context/AuthContext';
export default function Home() { export default function Home() {
const { user } = useAuth();
return ( return (
<main> <main>
<h1>Bienvenue sur Biblio</h1>
<p>Gérez vos livres, réservations et abonnements depuis une seule interface.</p>
<section>
<h2>Accès rapide</h2>
<ul>
<li><Link to="/books">📚 Parcourir le catalogue</Link></li>
{user?.role === 'user' && <li><Link to="/reservations">🔖 Mes réservations</Link></li>}
{user?.role === 'user' && <li><Link to="/loans">📖 Mes prêts</Link></li>}
{user?.role === 'user' && <li><Link to="/subscription"> Mon abonnement</Link></li>}
{user && <li><Link to="/orders">🛒 Passer une commande</Link></li>}
{user && <li><Link to="/group-orders">👥 Commandes groupées</Link></li>}
{user?.role === 'admin' && <li><Link to="/customers">👤 Gestion des clients</Link></li>}
{user?.role === 'admin' && <li><Link to="/returns"> Retours de livres</Link></li>}
{!user && <li><Link to="/login">Connexion</Link></li>}
</ul>
</section>
</main> </main>
); );
} }
+54
View File
@@ -0,0 +1,54 @@
import { useLoans } from '../context/LoanContext';
export default function Loans() {
const { loans, returnLoan } = useLoans();
const activeLoans = loans.filter(l => l.status === 'ACTIVE');
const returnedLoans = loans.filter(l => l.status === 'RETURNED');
return (
<main>
<h1>Mes prêts</h1>
<section>
<h2>Prêts en cours ({activeLoans.length})</h2>
{activeLoans.length === 0 ? (
<p>Aucun prêt en cours.</p>
) : (
<ul>
{activeLoans.map(l => (
<li key={l.loanId}>
<strong>{l.bookTitle}</strong> {l.bookAuthor}
<br />
Emprunteur : {l.borrowerUsername}
<br />
À rendre avant le : {new Date(l.dueDate).toLocaleDateString('fr-FR')}
<br />
Prêté le : {new Date(l.loanedAt).toLocaleDateString('fr-FR')}
<br />
<button onClick={() => returnLoan(l.loanId)}>Marquer comme rendu</button>
</li>
))}
</ul>
)}
</section>
{returnedLoans.length > 0 && (
<section>
<h2>Prêts terminés ({returnedLoans.length})</h2>
<ul>
{returnedLoans.map(l => (
<li key={l.loanId}>
<strong>{l.bookTitle}</strong> {l.bookAuthor}
<br />
Emprunteur : {l.borrowerUsername}
<br />
<small>Rendu </small>
</li>
))}
</ul>
</section>
)}
</main>
);
}
+57
View File
@@ -0,0 +1,57 @@
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>
);
}
+169 -1
View File
@@ -1,3 +1,171 @@
import { useState } from 'react';
import { createOrder } from '../api/orders';
import { getBookById } from '../api/books';
export default function Orders() { export default function Orders() {
return <main><h1>Mes commandes</h1></main>; const [customerId, setCustomerId] = useState('');
const [paymentMethod, setPaymentMethod] = useState('CREDIT_CARD');
const [address, setAddress] = useState({ street: '', city: '', postalCode: '', country: '' });
const [lines, setLines] = useState([{ bookId: '', quantity: 1 }]);
const [promoCode, setPromoCode] = useState('');
const [promoValid, setPromoValid] = useState(true);
const [estimate, setEstimate] = useState(null);
const [estimating, setEstimating] = useState(false);
const [estimateError, setEstimateError] = useState(null);
const [message, setMessage] = useState(null);
const [submitting, setSubmitting] = useState(false);
function handleAddressChange(e) {
const { name, value } = e.target;
setAddress((prev) => ({ ...prev, [name]: value }));
}
function handleLineChange(index, field, value) {
setLines((prev) => prev.map((line, i) => (i === index ? { ...line, [field]: value } : line)));
}
function addLine() {
setLines((prev) => [...prev, { bookId: '', quantity: 1 }]);
}
function removeLine(index) {
setLines((prev) => prev.filter((_, i) => i !== index));
}
function validatePromo(code) {
if (!code) return true;
return /^PROMO\d{1,2}$/.test(code);
}
function handlePromoChange(e) {
const code = e.target.value;
setPromoCode(code);
setPromoValid(validatePromo(code));
}
async function handleEstimate() {
setEstimating(true);
setEstimate(null);
setEstimateError(null);
try {
const ids = lines.map((l) => Number(l.bookId)).filter((n) => !isNaN(n) && n > 0);
if (ids.length === 0) {
setEstimateError('Aucun ISBN valide.');
return;
}
const unique = [...new Set(ids)];
const responses = await Promise.all(unique.map((id) => getBookById(id).then((r) => r.data)));
const priceMap = new Map();
unique.forEach((id, idx) => priceMap.set(id, responses[idx].prix ?? responses[idx].price ?? 0));
let total = 0;
for (const l of lines) {
const id = Number(l.bookId);
const qty = Number(l.quantity) || 0;
total += (priceMap.get(id) || 0) * qty;
}
let discounted = total;
if (promoCode) {
const m = promoCode.match(/^PROMO(\d{1,2})$/);
if (m) {
const pct = Math.max(0, Math.min(100, Number(m[1])));
discounted = total * (1 - pct / 100);
}
}
setEstimate({ total, discounted });
} catch (err) {
setEstimateError("Erreur lors de l'estimation.");
console.error(err);
} finally {
setEstimating(false);
}
}
function handleSubmit(e) {
e.preventDefault();
setSubmitting(true);
setMessage(null);
const payload = {
customerId,
paymentMethod,
address,
orderLineDtos: lines.map((line) => ({
bookId: Number(line.bookId),
quantity: Number(line.quantity),
})),
...(promoCode ? { promoCode } : {}),
};
createOrder(payload)
.then(() => setMessage('Commande créée avec succès !'))
.catch((error) => {
console.error(error);
setMessage(error.response?.data?.message || 'Erreur lors de la commande.');
})
.finally(() => setSubmitting(false));
}
return (
<main>
<h1>Passer une commande</h1>
<form onSubmit={handleSubmit}>
<label>ID client
<input value={customerId} onChange={(e) => setCustomerId(e.target.value)} required />
</label>
<h2>Livres</h2>
{lines.map((line, index) => (
<div key={index} style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.5rem' }}>
<input type="number" placeholder="ISBN du livre" value={line.bookId}
onChange={(e) => handleLineChange(index, 'bookId', e.target.value)} required />
<input type="number" placeholder="Quantité" min="1" value={line.quantity}
onChange={(e) => handleLineChange(index, 'quantity', e.target.value)} required />
{lines.length > 1 && (
<button type="button" onClick={() => removeLine(index)}>Retirer</button>
)}
</div>
))}
<button type="button" onClick={addLine}>+ Ajouter un livre</button>
<h2>Adresse de livraison</h2>
<input name="street" placeholder="Rue" value={address.street} onChange={handleAddressChange} required />
<input name="city" placeholder="Ville" value={address.city} onChange={handleAddressChange} required />
<input name="postalCode" placeholder="Code postal" value={address.postalCode} onChange={handleAddressChange} required />
<input name="country" placeholder="Pays" value={address.country} onChange={handleAddressChange} required />
<h2>Paiement</h2>
<label>Code promo (optionnel)
<input value={promoCode} onChange={handlePromoChange} placeholder="ex: PROMO10" />
</label>
{!promoValid && <p style={{ color: 'red' }}>Format invalide (ex: PROMO10)</p>}
<select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)}>
<option value="CREDIT_CARD">Carte bancaire</option>
</select>
<div>
<button type="button" onClick={handleEstimate} disabled={estimating}>
{estimating ? 'Estimation…' : 'Estimer le total'}
</button>
{estimateError && <p style={{ color: 'red' }}>{estimateError}</p>}
{estimate && (
<div>
<p>Total estimé : {estimate.total.toFixed(2)} </p>
{estimate.total !== estimate.discounted && (
<p>Après promo : <strong>{estimate.discounted.toFixed(2)} </strong></p>
)}
</div>
)}
</div>
<button type="submit" disabled={submitting || !promoValid}>
{submitting ? 'Envoi…' : 'Valider la commande'}
</button>
</form>
{message && <p style={{ color: message.includes('succès') ? 'green' : 'red' }}>{message}</p>}
</main>
);
} }
+43 -1
View File
@@ -1,3 +1,45 @@
import { useAuth } from '../context/AuthContext';
import { useReservations } from '../context/ReservationContext';
import { useLoans } from '../context/LoanContext';
import { useSubscription } from '../context/SubscriptionContext';
export default function Profile() { export default function Profile() {
return <main><h1>Mon compte</h1></main>; const { user } = useAuth();
const { reservations } = useReservations();
const { loans } = useLoans();
const { subscription } = useSubscription();
const activeReservations = reservations.filter(r => r.status !== 'CANCELLED');
const activeLoans = loans.filter(l => l.status === 'ACTIVE');
return (
<main>
<h1>Mon compte</h1>
<section>
<h2>Informations</h2>
<p><strong>Nom d'utilisateur :</strong> {user?.username}</p>
<p><strong>Rôle :</strong> {user?.role === 'admin' ? 'Administrateur' : 'Utilisateur'}</p>
</section>
{user?.role === 'user' && (
<>
<section>
<h2>Abonnement</h2>
{subscription ? (
<p><strong>Plan actif :</strong> {subscription.planName}</p>
) : (
<p>Aucun abonnement actif.</p>
)}
</section>
<section>
<h2>Activité</h2>
<p>Réservations en cours : <strong>{activeReservations.length}</strong></p>
<p>Prêts en cours : <strong>{activeLoans.length}</strong></p>
</section>
</>
)}
</main>
);
} }
+91
View File
@@ -0,0 +1,91 @@
import { useState } from 'react';
import { useReservations } from '../context/ReservationContext';
import { useLoans } from '../context/LoanContext';
import { Link } from 'react-router-dom';
export default function Reservations() {
const { reservations, cancelReservation } = useReservations();
const { addLoan } = useLoans();
const [loanForms, setLoanForms] = useState({});
const [loanStatuses, setLoanStatuses] = useState({});
function handleLoanChange(reservationId, field, value) {
setLoanForms(prev => ({
...prev,
[reservationId]: { ...prev[reservationId], [field]: value }
}));
}
function handleLoan(e, reservation) {
e.preventDefault();
const form = loanForms[reservation.reservationId] || {};
addLoan(
{ isbn: reservation.bookId, title: reservation.bookTitle, author: reservation.bookAuthor },
form.borrowerUsername,
form.dueDate
);
setLoanStatuses(prev => ({ ...prev, [reservation.reservationId]: 'Prêt enregistré avec succès !' }));
setLoanForms(prev => ({ ...prev, [reservation.reservationId]: {} }));
}
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>
<details>
<summary>Prêter ce livre à un autre lecteur</summary>
<form onSubmit={e => handleLoan(e, r)}>
<label>
Identifiant de l'emprunteur :
<input
type="text"
value={loanForms[r.reservationId]?.borrowerUsername || ''}
onChange={e => handleLoanChange(r.reservationId, 'borrowerUsername', e.target.value)}
placeholder="ex: alice"
required
/>
</label>
<label>
Date de retour prévue :
<input
type="date"
value={loanForms[r.reservationId]?.dueDate || ''}
onChange={e => handleLoanChange(r.reservationId, 'dueDate', e.target.value)}
min={new Date().toISOString().split('T')[0]}
required
/>
</label>
<button type="submit">Prêter</button>
</form>
{loanStatuses[r.reservationId] && (
<p style={{ color: 'green' }}>{loanStatuses[r.reservationId]}</p>
)}
</details>
</li>
))}
</ul>
</main>
);
}
+96
View File
@@ -0,0 +1,96 @@
import { useState } from 'react';
import { useReturns } from '../context/ReturnContext';
import { getBooks } from '../api/books';
import { useEffect } from 'react';
export default function Returns() {
const { returns, addReturn } = useReturns();
const [books, setBooks] = useState([]);
const [form, setForm] = useState({ bookId: '', customerPhone: '', reason: '' });
const [message, setMessage] = useState(null);
useEffect(() => {
getBooks(0, 100).then(res => setBooks(res.data.content)).catch(console.error);
}, []);
function handleChange(e) {
const { name, value } = e.target;
setForm(f => ({ ...f, [name]: value }));
}
function handleSubmit(e) {
e.preventDefault();
const book = books.find(b => String(b.isbn) === String(form.bookId));
const bookTitle = book ? book.title : form.bookId;
addReturn(form.bookId, bookTitle, form.customerPhone, form.reason);
setMessage({ success: true, text: 'Retour enregistré avec succès !' });
setForm({ bookId: '', customerPhone: '', reason: '' });
}
return (
<main>
<h1>Gestion des retours</h1>
<section>
<h2>Enregistrer un retour</h2>
<form onSubmit={handleSubmit}>
<label>
Livre :
<select name="bookId" value={form.bookId} onChange={handleChange} required>
<option value="">-- Choisir un livre --</option>
{books.map(b => (
<option key={b.isbn} value={b.isbn}>{b.title} {b.author}</option>
))}
</select>
</label>
<label>
Téléphone du client :
<input
name="customerPhone"
type="tel"
value={form.customerPhone}
onChange={handleChange}
placeholder="0612345678"
required
/>
</label>
<label>
Motif :
<textarea
name="reason"
value={form.reason}
onChange={handleChange}
placeholder="Motif du retour..."
required
/>
</label>
<button type="submit">Enregistrer le retour</button>
</form>
{message && <p style={{ color: message.success ? 'green' : 'red' }}>{message.text}</p>}
</section>
<section>
<h2>Historique des retours</h2>
{returns.length === 0 ? (
<p>Aucun retour enregistré.</p>
) : (
<ul>
{returns.map(r => (
<li key={r.returnId}>
<strong>{r.bookTitle}</strong>
<br />
Client : {r.customerPhone}
<br />
Motif : {r.reason}
<br />
Statut : {r.status}
<br />
<small>{new Date(r.returnedAt).toLocaleDateString('fr-FR')}</small>
</li>
))}
</ul>
)}
</section>
</main>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { useState } from 'react';
import { useSubscription } from '../context/SubscriptionContext';
export default function Subscription() {
const { subscription, subscribe, cancelSubscription, PLANS } = useSubscription();
const [selectedPlan, setSelectedPlan] = useState('basic');
const [phoneNumber, setPhoneNumber] = useState('');
const [message, setMessage] = useState(null);
function handleSubscribe(e) {
e.preventDefault();
subscribe(selectedPlan, phoneNumber);
setMessage({ success: true, text: 'Abonnement créé avec succès !' });
setPhoneNumber('');
}
function handleCancel() {
cancelSubscription();
setMessage({ success: false, text: 'Abonnement annulé.' });
}
return (
<main>
<h1>Mon abonnement</h1>
{subscription && subscription.status === 'ACTIVE' ? (
<section>
<h2>Abonnement actif</h2>
<p>Plan : <strong>{subscription.planName}</strong></p>
<p>Prix : <strong>{subscription.price} / mois</strong></p>
<p>Téléphone : {subscription.phoneNumber}</p>
<p>Depuis le : {new Date(subscription.startDate).toLocaleDateString('fr-FR')}</p>
<p>Statut : <strong style={{ color: 'green' }}>{subscription.status}</strong></p>
<button onClick={handleCancel}>Annuler l'abonnement</button>
</section>
) : (
<section>
<h2>Choisir un abonnement</h2>
<form onSubmit={handleSubscribe}>
<div>
{PLANS.map(plan => (
<label key={plan.id} style={{ display: 'block', marginBottom: '8px' }}>
<input
type="radio"
name="plan"
value={plan.id}
checked={selectedPlan === plan.id}
onChange={() => setSelectedPlan(plan.id)}
/>
{' '}<strong>{plan.name}</strong> , {plan.price} € / mois , {plan.description}
</label>
))}
</div>
<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">S'abonner</button>
</form>
</section>
)}
{message && (
<p style={{ color: message.success ? 'green' : 'red' }}>{message.text}</p>
)}
</main>
);
}
+196
View File
@@ -0,0 +1,196 @@
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: system-ui, sans-serif;
font-size: 15px;
line-height: 1.6;
color: #222;
background: #f7f7f7;
}
main {
max-width: 860px;
margin: 2rem auto;
padding: 0 1.25rem;
}
h1 {
font-size: 1.6rem;
font-weight: 600;
margin-bottom: 1.25rem;
color: #111;
}
h2 {
font-size: 1.15rem;
font-weight: 600;
margin: 1.5rem 0 0.75rem;
color: #333;
}
p {
margin-bottom: 0.75rem;
}
a {
color: #2563eb;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 0.75rem 0;
border-bottom: 1px solid #e5e5e5;
line-height: 1.7;
}
li:last-child {
border-bottom: none;
}
/* Forms */
form {
display: flex;
flex-direction: column;
gap: 0.75rem;
max-width: 480px;
}
label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.9rem;
color: #444;
}
input, select, textarea {
padding: 0.45rem 0.65rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 0.95rem;
font-family: inherit;
background: #fff;
width: 100%;
}
input:focus, select:focus, textarea:focus {
outline: none;
border-color: #2563eb;
}
/* Buttons */
button {
display: inline-block;
padding: 0.45rem 1rem;
font-size: 0.9rem;
font-family: inherit;
border: 1px solid #ccc;
border-radius: 4px;
background: #fff;
cursor: pointer;
color: #222;
}
button:hover {
background: #f0f0f0;
}
button[type="submit"],
button.primary {
background: #2563eb;
color: #fff;
border-color: #2563eb;
}
button[type="submit"]:hover,
button.primary:hover {
background: #1d4ed8;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Sections */
section {
margin-bottom: 2rem;
}
/* Details / summary */
details {
margin-top: 0.5rem;
}
summary {
cursor: pointer;
color: #2563eb;
font-size: 0.9rem;
}
summary:hover {
text-decoration: underline;
}
details form {
margin-top: 0.75rem;
padding: 0.75rem;
background: #fff;
border: 1px solid #e5e5e5;
border-radius: 4px;
}
/* Status messages */
.msg-success {
color: #15803d;
}
.msg-error {
color: #dc2626;
}
/* Cards (book list etc.) */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 1rem;
margin-top: 1rem;
}
.card {
background: #fff;
border: 1px solid #e5e5e5;
border-radius: 6px;
padding: 1rem;
}
.card h3 {
font-size: 1rem;
font-weight: 600;
margin-bottom: 0.25rem;
}
.card p {
font-size: 0.875rem;
color: #555;
margin: 0;
}
+56
View File
@@ -0,0 +1,56 @@
.navbar {
display: flex;
align-items: center;
gap: 1.5rem;
padding: 0 1.25rem;
height: 52px;
background: #fff;
border-bottom: 1px solid #e5e5e5;
position: sticky;
top: 0;
z-index: 100;
}
.navbar__logo {
font-weight: 700;
font-size: 1.1rem;
color: #111;
text-decoration: none;
margin-right: 0.5rem;
}
.navbar__links {
display: flex;
align-items: center;
gap: 0.25rem;
list-style: none;
flex: 1;
flex-wrap: wrap;
}
.navbar__links a {
padding: 0.3rem 0.6rem;
font-size: 0.875rem;
color: #444;
text-decoration: none;
border-radius: 4px;
}
.navbar__links a:hover {
background: #f0f0f0;
color: #111;
}
.navbar__actions {
display: flex;
align-items: center;
gap: 0.75rem;
font-size: 0.875rem;
color: #555;
white-space: nowrap;
}
.navbar__actions button {
padding: 0.3rem 0.75rem;
font-size: 0.85rem;
}
+78
View File
@@ -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**.
@@ -0,0 +1,22 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Category;
import java.time.LocalDate;
import java.util.List;
import lombok.Builder;
import lombok.Getter;
@Builder
@Getter
public class BookDTO {
private final long isbn;
private final String title;
private final String author;
private final String publisher;
private final LocalDate publicationDate;
private final double price;
private final int quantity;
private final List<Category> categories;
private final String description;
private final String language;
}
@@ -0,0 +1,42 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.converter;
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;
public final class BookConverter {
private BookConverter() {
}
public static Book toDomain(BookInfo book) {
return Book.builder()
.isbn(book.isbn())
.title(book.title())
.author(book.author())
.publisher(book.publisher())
.publicationDate(book.publicationDate())
.price(book.price())
.quantity(book.quantity())
.categories(book.categories())
.description(book.description())
.language(book.language())
.build();
}
public static BookDTO toDTO(Book book) {
return BookDTO.builder()
.isbn(book.getIsbn())
.title(book.getTitle())
.author(book.getAuthor())
.publisher(book.getPublisher())
.publicationDate(book.getPublicationDate())
.price(book.getPrice())
.quantity(book.getQuantity())
.categories(book.getCategories())
.description(book.getDescription())
.language(book.getLanguage())
.build();
}
}
@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import java.text.MessageFormat;
public class BookAlreadyExistsException extends Exception {
public static final String A_BOOK_WITH_ISBN_ALREADY_EXISTS_MESSAGE = "A book with isbn {0} already exists";
public BookAlreadyExistsException(long isbn) {
// ISBN passe en String pour ne pas que MessageFormat ajoute le separateur de milliers
super(MessageFormat.format(A_BOOK_WITH_ISBN_ALREADY_EXISTS_MESSAGE, String.valueOf(isbn)));
}
}
@@ -0,0 +1,13 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import java.text.MessageFormat;
public class BookNotFoundException extends Exception {
public static final String THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE = "The book with isbn {0} does not exist";
public BookNotFoundException(long isbn) {
// ISBN passe en String pour ne pas que MessageFormat ajoute le separateur de milliers
super(MessageFormat.format(THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE, String.valueOf(isbn)));
}
}
@@ -0,0 +1,12 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import java.text.MessageFormat;
public class IllegalBookQuantityException extends Exception {
public static final String CANNOT_REMOVE_STOCK = "Cannot remove {0} units from {1} units in stock";
public IllegalBookQuantityException(int needed, int actual) {
super(MessageFormat.format(CANNOT_REMOVE_STOCK, needed, actual));
}
}
@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
public class NotValidBookException extends Exception {
public NotValidBookException(String message) {
super(message);
}
}
@@ -0,0 +1,42 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public final class BookRepository {
private final List<Book> books = new ArrayList<>();
public List<Book> findAll() {
return books;
}
public void deleteAll() {
books.clear();
}
public Book save(Book book) {
Optional<Book> existing = findByIsbn(book.getIsbn());
existing.ifPresent(books::remove);
books.add(book);
return book;
}
public Optional<Book> findByIsbn(long isbn) {
return books.stream()
.filter(b -> b.getIsbn() == isbn)
.findFirst();
}
public boolean existsByIsbn(long isbn) {
return books.stream().anyMatch(b -> b.getIsbn() == isbn);
}
public void delete(Book book) {
books.remove(book);
}
}
@@ -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();
}
}
@@ -0,0 +1,93 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.validator;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
public final class BookValidator {
public static final int TITLE_MAX_LENGTH = 255;
public static final String ISBN_MUST_BE_POSITIVE = "Isbn must be a positive number";
public static final String TITLE_CANNOT_BE_BLANK = "Title cannot be blank";
public static final String TITLE_TOO_LONG = "Title cannot exceed " + TITLE_MAX_LENGTH + " characters";
public static final String AUTHOR_CANNOT_BE_BLANK = "Author cannot be blank";
public static final String PUBLISHER_CANNOT_BE_BLANK = "Publisher cannot be blank";
public static final String PUBLICATION_DATE_REQUIRED = "Publication date is required";
public static final String PRICE_MUST_BE_POSITIVE = "Price must be strictly positive";
public static final String QUANTITY_MUST_BE_POSITIVE_OR_ZERO = "Quantity must be >= 0";
public static final String CATEGORIES_REQUIRED = "At least one category is required";
public static final String LANGUAGE_CANNOT_BE_BLANK = "Language cannot be blank";
private BookValidator() {
}
public static void validate(BookInfo book) throws NotValidBookException {
validateIsbn(book);
validateTitle(book);
validateAuthor(book);
validatePublisher(book);
validatePublicationDate(book);
validatePrice(book);
validateQuantity(book);
validateCategories(book);
validateLanguage(book);
}
private static void validateIsbn(BookInfo book) throws NotValidBookException {
if (book.isbn() <= 0) {
throw new NotValidBookException(ISBN_MUST_BE_POSITIVE);
}
}
private static void validateTitle(BookInfo book) throws NotValidBookException {
if (book.title() == null || book.title().isBlank()) {
throw new NotValidBookException(TITLE_CANNOT_BE_BLANK);
}
if (book.title().length() > TITLE_MAX_LENGTH) {
throw new NotValidBookException(TITLE_TOO_LONG);
}
}
private static void validateAuthor(BookInfo book) throws NotValidBookException {
if (book.author() == null || book.author().isBlank()) {
throw new NotValidBookException(AUTHOR_CANNOT_BE_BLANK);
}
}
private static void validatePublisher(BookInfo book) throws NotValidBookException {
if (book.publisher() == null || book.publisher().isBlank()) {
throw new NotValidBookException(PUBLISHER_CANNOT_BE_BLANK);
}
}
private static void validatePublicationDate(BookInfo book) throws NotValidBookException {
if (book.publicationDate() == null) {
throw new NotValidBookException(PUBLICATION_DATE_REQUIRED);
}
}
private static void validatePrice(BookInfo book) throws NotValidBookException {
if (book.price() <= 0) {
throw new NotValidBookException(PRICE_MUST_BE_POSITIVE);
}
}
private static void validateQuantity(BookInfo book) throws NotValidBookException {
if (book.quantity() < 0) {
throw new NotValidBookException(QUANTITY_MUST_BE_POSITIVE_OR_ZERO);
}
}
private static void validateCategories(BookInfo book) throws NotValidBookException {
if (book.categories() == null || book.categories().isEmpty()) {
throw new NotValidBookException(CATEGORIES_REQUIRED);
}
}
private static void validateLanguage(BookInfo book) throws NotValidBookException {
if (book.language() == null || book.language().isBlank()) {
throw new NotValidBookException(LANGUAGE_CANNOT_BE_BLANK);
}
}
}
@@ -0,0 +1,86 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.converter;
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 java.time.LocalDate;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BookConverterTest {
@Nested
@DisplayName("toDomain() method tests")
class ToDomainTests {
@Test
@DisplayName("Should convert BookInfo to Book entity preserving all fields")
void testToDomain() {
BookInfo info = new BookInfo(
9780321125217L,
"DDD",
"Evans",
"Addison-Wesley",
LocalDate.of(2003, 8, 22),
54.99,
10,
List.of(Category.SCIENCE),
"desc",
"EN"
);
Book book = BookConverter.toDomain(info);
assertEquals(info.isbn(), book.getIsbn());
assertEquals(info.title(), book.getTitle());
assertEquals(info.author(), book.getAuthor());
assertEquals(info.publisher(), book.getPublisher());
assertEquals(info.publicationDate(), book.getPublicationDate());
assertEquals(info.price(), book.getPrice());
assertEquals(info.quantity(), book.getQuantity());
assertEquals(info.categories(), book.getCategories());
assertEquals(info.description(), book.getDescription());
assertEquals(info.language(), book.getLanguage());
}
}
@Nested
@DisplayName("toDTO() method tests")
class ToDTOTests {
@Test
@DisplayName("Should convert Book entity to BookDTO preserving all fields")
void testToDTO() {
Book book = Book.builder()
.isbn(123L)
.title("T")
.author("A")
.publisher("P")
.publicationDate(LocalDate.of(2020, 1, 1))
.price(9.99)
.quantity(5)
.categories(List.of(Category.FICTION))
.description("d")
.language("FR")
.build();
BookDTO dto = BookConverter.toDTO(book);
assertEquals(123L, dto.getIsbn());
assertEquals("T", dto.getTitle());
assertEquals("A", dto.getAuthor());
assertEquals("P", dto.getPublisher());
assertEquals(LocalDate.of(2020, 1, 1), dto.getPublicationDate());
assertEquals(9.99, dto.getPrice());
assertEquals(5, dto.getQuantity());
assertEquals(List.of(Category.FICTION), dto.getCategories());
assertEquals("d", dto.getDescription());
assertEquals("FR", dto.getLanguage());
}
}
}
@@ -0,0 +1,75 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.entity;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.IllegalBookQuantityException;
import java.time.LocalDate;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BookTest {
@Test
@DisplayName("Builder should create a valid Book instance")
void testBookBuilder() {
long isbn = 9780321125217L;
Book book = Book.builder()
.isbn(isbn)
.title("Domain-Driven Design")
.author("Eric Evans")
.publisher("Addison-Wesley")
.publicationDate(LocalDate.of(2003, 8, 22))
.price(54.99)
.quantity(10)
.categories(List.of(Category.SCIENCE, Category.REFERENCE))
.description("Tackling complexity in the heart of software")
.language("EN")
.build();
assertEquals(isbn, book.getIsbn());
assertEquals("Domain-Driven Design", book.getTitle());
assertEquals("Eric Evans", book.getAuthor());
assertEquals("Addison-Wesley", book.getPublisher());
assertEquals(LocalDate.of(2003, 8, 22), book.getPublicationDate());
assertEquals(54.99, book.getPrice());
assertEquals(10, book.getQuantity());
assertEquals(List.of(Category.SCIENCE, Category.REFERENCE), book.getCategories());
assertEquals("EN", book.getLanguage());
}
@Nested
@DisplayName("Stock management")
class StockTests {
@Test
@DisplayName("addStock should increase the quantity")
void testAddStock() {
Book book = Book.builder().quantity(5).build();
book.addStock(7);
assertEquals(12, book.getQuantity());
}
@Test
@DisplayName("removeStock should decrease the quantity")
void testRemoveStock() throws IllegalBookQuantityException {
Book book = Book.builder().quantity(5).build();
book.removeStock(3);
assertEquals(2, book.getQuantity());
}
@Test
@DisplayName("removeStock should throw when removing more than available")
void testRemoveTooMuchStock() {
Book book = Book.builder().quantity(5).build();
IllegalBookQuantityException exception = assertThrows(
IllegalBookQuantityException.class,
() -> book.removeStock(10)
);
assertEquals(5, book.getQuantity());
assertTrue(exception.getMessage().contains("10"));
assertTrue(exception.getMessage().contains("5"));
}
}
}
@@ -0,0 +1,26 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BookAlreadyExistsExceptionTest {
@Test
@DisplayName("Exception message should contain the ISBN provided")
void testExceptionMessageContainsIsbn() {
long isbn = 9780321125217L;
BookAlreadyExistsException exception = new BookAlreadyExistsException(isbn);
assertTrue(exception.getMessage().contains(String.valueOf(isbn)));
}
@Test
@DisplayName("Exception should expose its message constant")
void testConstantMessage() {
assertEquals("A book with isbn {0} already exists",
BookAlreadyExistsException.A_BOOK_WITH_ISBN_ALREADY_EXISTS_MESSAGE);
}
}
@@ -0,0 +1,37 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BookNotFoundExceptionTest {
@Test
@DisplayName("Exception message should contain the ISBN provided")
void testExceptionMessageContainsIsbn() {
long isbn = 9780321125217L;
BookNotFoundException exception = new BookNotFoundException(isbn);
assertTrue(exception.getMessage().contains(String.valueOf(isbn)));
}
@Test
@DisplayName("Exception should expose its message constant")
void testConstantMessage() {
assertEquals("The book with isbn {0} does not exist",
BookNotFoundException.THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE);
}
@Test
@DisplayName("Exception should be properly thrown and caught")
void testExceptionCanBeThrownAndCaught() {
long isbn = 1L;
try {
throw new BookNotFoundException(isbn);
} catch (BookNotFoundException e) {
assertTrue(e.getMessage().contains("1"));
}
}
}
@@ -0,0 +1,33 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import java.text.MessageFormat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class IllegalBookQuantityExceptionTest {
@Test
@DisplayName("Exception message should contain the requested and actual quantities")
void testExceptionMessageContainsQuantities() {
IllegalBookQuantityException exception = new IllegalBookQuantityException(10, 3);
String expected = "Cannot remove 10 units from 3 units in stock";
assertEquals(expected, exception.getMessage());
}
@ParameterizedTest
@CsvSource({
"10, 3",
"100, 0",
"5, 4"
})
@DisplayName("Message should be formatted using the constant template")
void testFormattedMessage(int needed, int actual) {
IllegalBookQuantityException exception = new IllegalBookQuantityException(needed, actual);
String expected = MessageFormat.format(IllegalBookQuantityException.CANNOT_REMOVE_STOCK, needed, actual);
assertEquals(expected, exception.getMessage());
}
}
@@ -0,0 +1,44 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
class NotValidBookExceptionTest {
@Test
@DisplayName("Exception should be created with the provided message")
void testExceptionCreation() {
String msg = "title cannot be blank";
NotValidBookException exception = new NotValidBookException(msg);
assertEquals(msg, exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {
"Title cannot be blank",
"Author cannot be blank",
"Price must be strictly positive",
"At least one category is required"
})
@DisplayName("Exception should propagate any validation message")
void testExceptionWithDifferentMessages(String message) {
NotValidBookException exception = new NotValidBookException(message);
assertEquals(message, exception.getMessage());
}
@Test
@DisplayName("Exception should be catchable as a general Exception")
void testExceptionInheritance() {
String msg = "invalid book";
try {
throw new NotValidBookException(msg);
} catch (Exception e) {
assertEquals(NotValidBookException.class, e.getClass());
assertEquals(msg, e.getMessage());
}
}
}
@@ -0,0 +1,149 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Category;
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 static org.junit.jupiter.api.Assertions.*;
class BookRepositoryTest {
private BookRepository repository;
private Book book1;
private Book book2;
@BeforeEach
void setUp() {
repository = new BookRepository();
book1 = Book.builder()
.isbn(1111111111111L)
.title("Book One")
.author("Author A")
.publisher("Pub")
.publicationDate(LocalDate.of(2020, 1, 1))
.price(10.0)
.quantity(2)
.categories(List.of(Category.FICTION))
.language("EN")
.build();
book2 = Book.builder()
.isbn(2222222222222L)
.title("Book Two")
.author("Author B")
.publisher("Pub")
.publicationDate(LocalDate.of(2021, 1, 1))
.price(20.0)
.quantity(0)
.categories(List.of(Category.HISTORY))
.language("FR")
.build();
}
@Test
@DisplayName("New repository should be empty")
void testNewRepositoryIsEmpty() {
assertTrue(repository.findAll().isEmpty());
}
@Nested
@DisplayName("Save operations")
class SaveOperations {
@Test
@DisplayName("Save should add a new book")
void testSave() {
Book saved = repository.save(book1);
assertEquals(1, repository.findAll().size());
assertEquals(book1.getIsbn(), saved.getIsbn());
}
@Test
@DisplayName("Save should replace existing book with same ISBN (idempotency)")
void testSaveReplacesExisting() {
repository.save(book1);
Book updated = Book.builder()
.isbn(book1.getIsbn())
.title("New title")
.author("Author A")
.publisher("Pub")
.publicationDate(LocalDate.of(2020, 1, 1))
.price(10.0)
.quantity(99)
.categories(List.of(Category.FICTION))
.language("EN")
.build();
repository.save(updated);
assertEquals(1, repository.findAll().size());
assertEquals(99, repository.findByIsbn(book1.getIsbn()).orElseThrow().getQuantity());
assertEquals("New title", repository.findByIsbn(book1.getIsbn()).orElseThrow().getTitle());
}
}
@Nested
@DisplayName("Find operations")
class FindOperations {
@BeforeEach
void seed() {
repository.save(book1);
repository.save(book2);
}
@Test
@DisplayName("findByIsbn returns the matching book")
void testFindByIsbn() {
Optional<Book> found = repository.findByIsbn(book1.getIsbn());
assertTrue(found.isPresent());
assertEquals(book1.getTitle(), found.get().getTitle());
}
@Test
@DisplayName("findByIsbn returns empty when not found")
void testFindByIsbnNotFound() {
assertTrue(repository.findByIsbn(99L).isEmpty());
}
@Test
@DisplayName("existsByIsbn returns true / false consistently")
void testExistsByIsbn() {
assertTrue(repository.existsByIsbn(book1.getIsbn()));
assertFalse(repository.existsByIsbn(99L));
}
}
@Nested
@DisplayName("Delete operations")
class DeleteOperations {
@BeforeEach
void seed() {
repository.save(book1);
repository.save(book2);
}
@Test
@DisplayName("delete should remove the specified book")
void testDelete() {
repository.delete(book1);
assertEquals(1, repository.findAll().size());
assertFalse(repository.existsByIsbn(book1.getIsbn()));
}
@Test
@DisplayName("deleteAll should clear the repository")
void testDeleteAll() {
repository.deleteAll();
assertTrue(repository.findAll().isEmpty());
}
}
}
@@ -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());
}
}
}
@@ -0,0 +1,167 @@
package fr.iut_fbleau.but3.dev62.mylibrary.book.validator;
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.NotValidBookException;
import java.time.LocalDate;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
class BookValidatorTest {
private BookInfo valid() {
return new BookInfo(
9780321125217L,
"Domain-Driven Design",
"Eric Evans",
"Addison-Wesley",
LocalDate.of(2003, 8, 22),
54.99,
10,
List.of(Category.SCIENCE),
"Tackling complexity in the heart of software",
"EN"
);
}
@Test
@DisplayName("Should accept a valid BookInfo")
void testValidBook() {
assertDoesNotThrow(() -> BookValidator.validate(valid()));
}
@Nested
@DisplayName("ISBN validation")
class IsbnTests {
@ParameterizedTest
@ValueSource(longs = {0L, -1L, -9999L})
@DisplayName("Should reject ISBN that is not strictly positive")
void testInvalidIsbn(long isbn) {
BookInfo info = new BookInfo(isbn, "T", "A", "P", LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.ISBN_MUST_BE_POSITIVE, ex.getMessage());
}
}
@Nested
@DisplayName("Title validation")
class TitleTests {
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t", "\n"})
@DisplayName("Should reject blank title")
void testBlankTitle(String title) {
BookInfo info = new BookInfo(1L, title, "A", "P", LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.TITLE_CANNOT_BE_BLANK, ex.getMessage());
}
@Test
@DisplayName("Should reject null title")
void testNullTitle() {
BookInfo info = new BookInfo(1L, null, "A", "P", LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.TITLE_CANNOT_BE_BLANK, ex.getMessage());
}
@Test
@DisplayName("Should reject title longer than 255 characters")
void testTitleTooLong() {
String longTitle = "a".repeat(256);
BookInfo info = new BookInfo(1L, longTitle, "A", "P", LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.TITLE_TOO_LONG, ex.getMessage());
}
}
@Nested
@DisplayName("Author / Publisher validation")
class AuthorPublisherTests {
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t"})
@DisplayName("Should reject blank author")
void testBlankAuthor(String author) {
BookInfo info = new BookInfo(1L, "T", author, "P", LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.AUTHOR_CANNOT_BE_BLANK, ex.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t"})
@DisplayName("Should reject blank publisher")
void testBlankPublisher(String publisher) {
BookInfo info = new BookInfo(1L, "T", "A", publisher, LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.PUBLISHER_CANNOT_BE_BLANK, ex.getMessage());
}
}
@Nested
@DisplayName("Date / Price / Quantity validation")
class NumericTests {
@Test
@DisplayName("Should reject null publication date")
void testNullDate() {
BookInfo info = new BookInfo(1L, "T", "A", "P", null, 1.0, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.PUBLICATION_DATE_REQUIRED, ex.getMessage());
}
@ParameterizedTest
@ValueSource(doubles = {0.0, -0.01, -10.0})
@DisplayName("Should reject non-positive price")
void testNonPositivePrice(double price) {
BookInfo info = new BookInfo(1L, "T", "A", "P", LocalDate.now(), price, 0, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.PRICE_MUST_BE_POSITIVE, ex.getMessage());
}
@ParameterizedTest
@ValueSource(ints = {-1, -100})
@DisplayName("Should reject negative quantity")
void testNegativeQuantity(int quantity) {
BookInfo info = new BookInfo(1L, "T", "A", "P", LocalDate.now(), 1.0, quantity, List.of(Category.SCIENCE), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.QUANTITY_MUST_BE_POSITIVE_OR_ZERO, ex.getMessage());
}
}
@Nested
@DisplayName("Categories / Language validation")
class MetadataTests {
@Test
@DisplayName("Should reject empty categories")
void testEmptyCategories() {
BookInfo info = new BookInfo(1L, "T", "A", "P", LocalDate.now(), 1.0, 0, List.of(), "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.CATEGORIES_REQUIRED, ex.getMessage());
}
@Test
@DisplayName("Should reject null categories")
void testNullCategories() {
BookInfo info = new BookInfo(1L, "T", "A", "P", LocalDate.now(), 1.0, 0, null, "", "EN");
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.CATEGORIES_REQUIRED, ex.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "\t"})
@DisplayName("Should reject blank language")
void testBlankLanguage(String language) {
BookInfo info = new BookInfo(1L, "T", "A", "P", LocalDate.now(), 1.0, 0, List.of(Category.SCIENCE), "", language);
NotValidBookException ex = assertThrows(NotValidBookException.class, () -> BookValidator.validate(info));
assertEquals(BookValidator.LANGUAGE_CANNOT_BE_BLANK, ex.getMessage());
}
}
}
@@ -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")
);
}
}

Some files were not shown because too many files have changed in this diff Show More