Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0d9f8dc539 | |||
| 4197f99116 | |||
| 092a020059 | |||
| 8708686994 | |||
| 0d37efd227 | |||
| 1cf4bed83b | |||
| 0ba4e5599e | |||
| 587e81816c | |||
| 8359f21e07 | |||
| e3c02a6fc8 | |||
| a595750194 | |||
| 00e90aaa0c | |||
| 009ac7f5f7 | |||
| 9080b8e67e | |||
| 179f259c3d | |||
| bfd1f600de | |||
| 52213fce0b | |||
| 7117aba838 | |||
| 010ec9c11a | |||
| de47c293b8 | |||
| 4ae227d79d | |||
| 8f3451adc0 | |||
| 9916b02ef6 | |||
| 1aa83b0911 | |||
| abbd3ee95d | |||
| efa6fc49eb | |||
| e33acdf151 | |||
| ccafc24f72 | |||
| c811c373d5 | |||
| 1f9a1e9af8 |
+29
-4
@@ -1,4 +1,4 @@
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import Layout from './components/Layout';
|
||||
import Home from './pages/Home';
|
||||
import Books from './pages/Books';
|
||||
@@ -6,17 +6,42 @@ import Orders from './pages/Orders';
|
||||
import Profile from './pages/Profile';
|
||||
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 { 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() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<Layout />}>
|
||||
<Route index element={<Home />} />
|
||||
<Route path="books" element={<Books />} />
|
||||
<Route path="orders" element={<Orders />} />
|
||||
<Route path="profile" element={<Profile />} />
|
||||
<Route path="books/:bookId" element={<RequireAuth><BookDetail /></RequireAuth>} />
|
||||
<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="*" element={<NotFound />} />
|
||||
<Route path="books/new" element={<AddBook />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
@@ -7,3 +7,11 @@ export function getBooks(page = 0, size = 20) {
|
||||
export function registerBook(book) {
|
||||
return client.post('/api/books', book);
|
||||
}
|
||||
|
||||
export function getBookById(id) {
|
||||
return client.get(`/api/books/${id}`);
|
||||
}
|
||||
|
||||
export function reserveBook(bookId, reservation) {
|
||||
return client.post(`/api/books/${bookId}/reservations`, reservation);
|
||||
}
|
||||
@@ -0,0 +1,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 } });
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import client from './client';
|
||||
|
||||
export function createOrder(order) {
|
||||
return client.post('/api/orders', order);
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
export default function Navbar() {
|
||||
const { user, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
function handleLogout() {
|
||||
logout();
|
||||
navigate('/login');
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="navbar">
|
||||
<Link to="/" className="navbar__logo">Biblio</Link>
|
||||
@@ -9,13 +18,23 @@ export default function Navbar() {
|
||||
<ul className="navbar__links">
|
||||
<li><Link to="/">Accueil</Link></li>
|
||||
<li><Link to="/books">Catalogue</Link></li>
|
||||
<li><Link to="/orders">Commandes</Link></li>
|
||||
<li><Link to="/profile">Mon compte</Link></li>
|
||||
{user && <li><Link to="/orders">Commandes</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 && <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>
|
||||
|
||||
<div className="navbar__actions">
|
||||
<button className="btn-ghost">Connexion</button>
|
||||
<button className="btn-cta">S'inscrire</button>
|
||||
{user ? (
|
||||
<>
|
||||
<span>{user.username} ({user.role})</span>
|
||||
<button onClick={handleLogout}>Déconnexion</button>
|
||||
</>
|
||||
) : (
|
||||
<Link to="/login"><button>Connexion</button></Link>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
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 App from './App';
|
||||
import './styles/global.css';
|
||||
|
||||
@@ -8,7 +13,17 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<ReservationProvider>
|
||||
<ReviewProvider>
|
||||
<ReturnProvider>
|
||||
<SubscriptionProvider>
|
||||
<App />
|
||||
</SubscriptionProvider>
|
||||
</ReturnProvider>
|
||||
</ReviewProvider>
|
||||
</ReservationProvider>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -35,7 +35,7 @@ export default function AddBook() {
|
||||
|
||||
registerBook(payload)
|
||||
.then((response) => {
|
||||
setMessage({ type: 'success', text: `Livre créé (id : ${response.data}) ✅` });
|
||||
setMessage({ type: 'success', text: `Livre créé (id : ${response.data})` });
|
||||
setForm(initialForm);
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { getBooks } from '../api/books';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function Books() {
|
||||
const { user } = useAuth();
|
||||
const [books, setBooks] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
@@ -28,11 +30,13 @@ export default function Books() {
|
||||
return (
|
||||
<main>
|
||||
<h1>Catalogue</h1>
|
||||
<Link to="/books/new">+ Ajouter un livre</Link>
|
||||
{user?.role === 'admin' && <Link to="/books/new">+ Ajouter un livre</Link>}
|
||||
<ul>
|
||||
{books.map((book) => (
|
||||
<li key={book.isbn}>
|
||||
<Link to={`/books/${book.isbn}`}>
|
||||
<strong>{book.title}</strong> - {book.author}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,91 @@
|
||||
import { useState } from 'react';
|
||||
import { createOrder } from '../api/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 [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 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),
|
||||
})),
|
||||
};
|
||||
|
||||
createOrder(payload)
|
||||
.then((response) => setMessage('Commande créée'))
|
||||
.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}>
|
||||
<input type="number" placeholder="ISBN du livre" value={line.bookId}
|
||||
onChange={(e) => handleLineChange(index, 'bookId', e.target.value)} required />
|
||||
<input type="number" placeholder="Quantité" 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>
|
||||
<select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)}>
|
||||
<option value="CREDIT_CARD">Carte bancaire</option>
|
||||
</select>
|
||||
|
||||
<button type="submit" disabled={submitting}>
|
||||
{submitting ? 'Envoi…' : 'Valider la commande'}
|
||||
</button>
|
||||
</form>
|
||||
{message && <p>{message}</p>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useReservations } from '../context/ReservationContext';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
export default function Reservations() {
|
||||
const { reservations, cancelReservation } = useReservations();
|
||||
|
||||
if (reservations.length === 0) {
|
||||
return (
|
||||
<main>
|
||||
<h1>Mes réservations</h1>
|
||||
<p>Aucune réservation pour le moment.</p>
|
||||
<Link to="/books">← Retour au catalogue</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main>
|
||||
<h1>Mes réservations</h1>
|
||||
<ul>
|
||||
{reservations.map(r => (
|
||||
<li key={r.reservationId}>
|
||||
<strong>{r.bookTitle}</strong> — {r.bookAuthor}
|
||||
<br />
|
||||
Téléphone : {r.phoneNumber}
|
||||
<br />
|
||||
Réservé le : {new Date(r.reservedAt).toLocaleDateString('fr-FR')}
|
||||
<br />
|
||||
Statut : {r.status}
|
||||
<br />
|
||||
<button onClick={() => cancelReservation(r.reservationId)}>Annuler</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/modules.xml
|
||||
.idea/jarRepositories.xml
|
||||
.idea/compiler.xml
|
||||
.idea/libraries/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
@@ -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,151 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>fr.iut_fbleau.but3.dev62</groupId>
|
||||
<artifactId>mylibrary</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<!-- Your java version-->
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<!-- Main dependencies -->
|
||||
<lombok.version>1.18.36</lombok.version>
|
||||
|
||||
<!-- Test Verisons-->
|
||||
<junit.version>5.11.4</junit.version>
|
||||
<junit.platform.version>1.11.4</junit.platform.version>
|
||||
<cucumber.version>7.21.1</cucumber.version>
|
||||
<mockito.version>5.16.0</mockito.version>
|
||||
|
||||
<!-- Maven build version -->
|
||||
<maven.compiler.version>3.13.0</maven.compiler.version>
|
||||
<maven.surefire.version>3.5.2</maven.surefire.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.cucumber</groupId>
|
||||
<artifactId>cucumber-bom</artifactId>
|
||||
<version>${cucumber.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.cucumber</groupId>
|
||||
<artifactId>cucumber-java</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.cucumber</groupId>
|
||||
<artifactId>cucumber-junit-platform-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-suite</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-engine</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-launcher</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-junit-jupiter</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven.compiler.version}</version>
|
||||
<configuration>
|
||||
<encoding>${project.build.sourceEncoding}</encoding>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven.surefire.version}</version>
|
||||
<configuration>
|
||||
<properties>
|
||||
<!-- Work around. Surefire does not include enough
|
||||
information to disambiguate between different
|
||||
examples and scenarios. -->
|
||||
<configurationParameters>
|
||||
cucumber.junit-platform.naming-strategy=long
|
||||
</configurationParameters>
|
||||
</properties>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -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,19 @@
|
||||
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;
|
||||
|
||||
public record BookInfo(
|
||||
long isbn,
|
||||
String title,
|
||||
String author,
|
||||
String publisher,
|
||||
LocalDate publicationDate,
|
||||
double price,
|
||||
int quantity,
|
||||
List<Category> categories,
|
||||
String description,
|
||||
String language
|
||||
) {
|
||||
}
|
||||
+42
@@ -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,24 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.book.entity;
|
||||
|
||||
public enum Category {
|
||||
FICTION,
|
||||
NON_FICTION,
|
||||
SCIENCE_FICTION,
|
||||
FANTASY,
|
||||
MYSTERY,
|
||||
THRILLER,
|
||||
ROMANCE,
|
||||
BIOGRAPHY,
|
||||
HISTORY,
|
||||
POETRY,
|
||||
CHILDRENS,
|
||||
YOUNG_ADULT,
|
||||
SCIENCE,
|
||||
PHILOSOPHY,
|
||||
SELF_HELP,
|
||||
TRAVEL,
|
||||
COOKING,
|
||||
ART,
|
||||
RELIGION,
|
||||
REFERENCE
|
||||
}
|
||||
+13
@@ -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)));
|
||||
}
|
||||
}
|
||||
+13
@@ -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)));
|
||||
}
|
||||
}
|
||||
+12
@@ -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));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.book.exception;
|
||||
|
||||
public class NotValidBookException extends Exception {
|
||||
|
||||
public NotValidBookException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+42
@@ -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);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.book.usecase;
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.converter.BookConverter;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.book.validator.BookValidator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class BookUseCase {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
public BookUseCase(BookRepository bookRepository) {
|
||||
this.bookRepository = bookRepository;
|
||||
}
|
||||
|
||||
public long registerBook(BookInfo bookInfo) throws NotValidBookException, BookAlreadyExistsException {
|
||||
BookValidator.validate(bookInfo);
|
||||
if (bookRepository.existsByIsbn(bookInfo.isbn())) {
|
||||
throw new BookAlreadyExistsException(bookInfo.isbn());
|
||||
}
|
||||
Book toRegister = BookConverter.toDomain(bookInfo);
|
||||
Book registered = bookRepository.save(toRegister);
|
||||
return registered.getIsbn();
|
||||
}
|
||||
|
||||
public BookDTO getBookByIsbn(long isbn) throws BookNotFoundException {
|
||||
Optional<Book> optional = bookRepository.findByIsbn(isbn);
|
||||
if (optional.isEmpty()) {
|
||||
throw new BookNotFoundException(isbn);
|
||||
}
|
||||
return BookConverter.toDTO(optional.get());
|
||||
}
|
||||
|
||||
public List<BookDTO> getAllBooks() {
|
||||
return bookRepository.findAll().stream()
|
||||
.map(BookConverter::toDTO)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
+93
@@ -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,15 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer;
|
||||
|
||||
import java.util.UUID;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
public class CustomerDTO {
|
||||
private final UUID id;
|
||||
private final String firstName;
|
||||
private final String lastName;
|
||||
private final String phoneNumber;
|
||||
private final int loyaltyPoints;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer;
|
||||
|
||||
public record CustomerInfo(String firstName, String lastName, String phoneNumber) {
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.converter;
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerDTO;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
|
||||
|
||||
public final class CustomerConverter {
|
||||
private CustomerConverter(){
|
||||
|
||||
}
|
||||
|
||||
public static Customer toDomain(CustomerInfo newCustomer) {
|
||||
return Customer.builder()
|
||||
.firstName(newCustomer.firstName())
|
||||
.lastName(newCustomer.lastName())
|
||||
.phoneNumber(newCustomer.phoneNumber())
|
||||
.loyaltyPoints(0)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static CustomerDTO toDTO(Customer customer) {
|
||||
return CustomerDTO.builder()
|
||||
.id(customer.getId())
|
||||
.firstName(customer.getFirstName())
|
||||
.lastName(customer.getLastName())
|
||||
.phoneNumber(customer.getPhoneNumber())
|
||||
.loyaltyPoints(customer.getLoyaltyPoints())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.entity;
|
||||
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.IllegalCustomerPointException;
|
||||
import java.util.UUID;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
|
||||
@Builder
|
||||
@Getter
|
||||
public class Customer {
|
||||
private UUID id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private String phoneNumber;
|
||||
private int loyaltyPoints;
|
||||
|
||||
public void setRandomUUID() {
|
||||
this.id = UUID.randomUUID();
|
||||
}
|
||||
|
||||
public void addLoyaltyPoints(int loyaltyPointToAdd) {
|
||||
this.loyaltyPoints += loyaltyPointToAdd;
|
||||
}
|
||||
|
||||
public void removeLoyaltyPoints(int loyaltyPointToRemove) throws IllegalCustomerPointException {
|
||||
if (loyaltyPointToRemove > this.loyaltyPoints) throw new IllegalCustomerPointException(loyaltyPointToRemove, this.loyaltyPoints);
|
||||
this.loyaltyPoints -= loyaltyPointToRemove;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.exception;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.UUID;
|
||||
|
||||
public class CustomerNotFoundException extends Exception {
|
||||
|
||||
public static final String THE_CUSTOMER_WITH_ID_DOES_NOT_EXIST_MESSAGE = "The customer with id {0} does not exist";
|
||||
|
||||
public CustomerNotFoundException(UUID uuid) {
|
||||
super(MessageFormat.format(THE_CUSTOMER_WITH_ID_DOES_NOT_EXIST_MESSAGE, uuid));
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.exception;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
|
||||
public class IllegalCustomerPointException extends Exception {
|
||||
|
||||
public static final String CANNOT_REMOVE_LOYALTY_POINTS = "Cannot remove {0} points from {1} points";
|
||||
|
||||
public IllegalCustomerPointException(int needed, int actual) {
|
||||
super(MessageFormat.format(CANNOT_REMOVE_LOYALTY_POINTS, needed,
|
||||
actual));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.exception;
|
||||
|
||||
public class NotValidCustomerException extends Exception {
|
||||
|
||||
public NotValidCustomerException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.repository;
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@NoArgsConstructor
|
||||
public final class CustomerRepository {
|
||||
private final List<Customer> customers = new ArrayList<>();
|
||||
|
||||
public List<Customer> findAll() {
|
||||
return customers;
|
||||
}
|
||||
|
||||
public void deleteAll() {
|
||||
customers.clear();
|
||||
}
|
||||
|
||||
public Customer save(Customer newCustomer) {
|
||||
Optional<Customer> optionalCustomerWithSameId = this.findById(newCustomer.getId());
|
||||
optionalCustomerWithSameId.ifPresentOrElse(customers::remove, newCustomer::setRandomUUID);
|
||||
this.customers.add(newCustomer);
|
||||
return newCustomer;
|
||||
}
|
||||
|
||||
public Optional<Customer> findById(UUID uuid) {
|
||||
return this.customers.stream()
|
||||
.filter(customer -> customer.getId().equals(uuid))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public boolean existsById(UUID uuid) {
|
||||
return this.customers.stream()
|
||||
.anyMatch(customer -> customer.getId().equals(uuid));
|
||||
}
|
||||
|
||||
public Optional<Customer> findByPhoneNumber(String phoneNumber) {
|
||||
return this.customers.stream()
|
||||
.filter(customer -> customer.getPhoneNumber().equals(phoneNumber))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public void delete(Customer customer) {
|
||||
this.customers.remove(customer);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.usecase;
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerDTO;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.converter.CustomerConverter;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.CustomerNotFoundException;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.IllegalCustomerPointException;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.NotValidCustomerException;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.repository.CustomerRepository;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.validator.CustomerValidator;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class CustomerUseCase {
|
||||
|
||||
private final CustomerRepository customerRepository;
|
||||
|
||||
public CustomerUseCase(CustomerRepository customerRepository) {
|
||||
this.customerRepository = customerRepository;
|
||||
}
|
||||
|
||||
public UUID registerCustomer(CustomerInfo newCustomer) throws NotValidCustomerException {
|
||||
CustomerValidator.validate(newCustomer);
|
||||
Customer customerToRegister = CustomerConverter.toDomain(newCustomer);
|
||||
Customer customerToRegistered = customerRepository.save(customerToRegister);
|
||||
return customerToRegistered.getId();
|
||||
}
|
||||
|
||||
public Optional<CustomerDTO> findCustomerByPhoneNumber(String phoneNumber) {
|
||||
Optional<Customer> optionalCustomer = customerRepository.findByPhoneNumber(phoneNumber);
|
||||
return optionalCustomer.map(CustomerConverter::toDTO);
|
||||
}
|
||||
|
||||
public CustomerDTO updateCustomer(UUID uuid, CustomerInfo customerInfo)
|
||||
throws CustomerNotFoundException, NotValidCustomerException {
|
||||
CustomerValidator.validate(customerInfo);
|
||||
Customer customerByUUID = getCustomerIfDoesNotExistThrowCustomerNotFoundException(
|
||||
uuid);
|
||||
Customer customer = Customer.builder()
|
||||
.id(uuid)
|
||||
.firstName(customerInfo.firstName())
|
||||
.lastName(customerInfo.lastName())
|
||||
.phoneNumber(customerInfo.phoneNumber())
|
||||
.loyaltyPoints(customerByUUID.getLoyaltyPoints())
|
||||
.build();
|
||||
Customer updatedCustomer = customerRepository.save(customer);
|
||||
return CustomerConverter.toDTO(updatedCustomer);
|
||||
}
|
||||
|
||||
public void deleteCustomer(UUID uuid) throws CustomerNotFoundException {
|
||||
Customer customerToDelete = getCustomerIfDoesNotExistThrowCustomerNotFoundException(uuid);
|
||||
this.customerRepository.delete(customerToDelete);
|
||||
}
|
||||
|
||||
public int addLoyaltyPoints(UUID uuid, int loyaltyPointToAdd) throws CustomerNotFoundException {
|
||||
Customer customerToAddLoyaltyPoints = getCustomerIfDoesNotExistThrowCustomerNotFoundException(
|
||||
uuid);
|
||||
customerToAddLoyaltyPoints.addLoyaltyPoints(loyaltyPointToAdd);
|
||||
customerRepository.save(customerToAddLoyaltyPoints);
|
||||
return customerToAddLoyaltyPoints.getLoyaltyPoints();
|
||||
}
|
||||
|
||||
public int subtractLoyaltyPoints(UUID uuid, int loyaltyPointToRemove)
|
||||
throws CustomerNotFoundException, IllegalCustomerPointException {
|
||||
Customer customerToSubtractLoyaltyPoints = getCustomerIfDoesNotExistThrowCustomerNotFoundException(
|
||||
uuid);
|
||||
customerToSubtractLoyaltyPoints.removeLoyaltyPoints(loyaltyPointToRemove);
|
||||
customerRepository.save(customerToSubtractLoyaltyPoints);
|
||||
return customerToSubtractLoyaltyPoints.getLoyaltyPoints();
|
||||
}
|
||||
|
||||
private Customer getCustomerIfDoesNotExistThrowCustomerNotFoundException(UUID uuid)
|
||||
throws CustomerNotFoundException {
|
||||
Optional<Customer> optionalCustomerById = customerRepository.findById(uuid);
|
||||
if (optionalCustomerById.isEmpty()) {
|
||||
throw new CustomerNotFoundException(uuid);
|
||||
}
|
||||
return optionalCustomerById.get();
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.customer.validator;
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo;
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.NotValidCustomerException;
|
||||
|
||||
public final class CustomerValidator {
|
||||
|
||||
public static final String PHONE_NUMBER_IS_NOT_VALID = "Phone number is not valid";
|
||||
public static final String LAST_NAME_CANNOT_BE_BLANK = "Last name cannot be blank";
|
||||
public static final String FIRST_NAME_CANNOT_BE_BLANK = "First name cannot be blank";
|
||||
public static final String PHONE_NUMBER_REGEX = "0([67])\\d{8}";
|
||||
|
||||
private CustomerValidator() {
|
||||
|
||||
}
|
||||
|
||||
public static void validate(CustomerInfo newCustomer) throws NotValidCustomerException {
|
||||
validateFirstName(newCustomer);
|
||||
validateLastName(newCustomer);
|
||||
validatePhoneNumber(newCustomer);
|
||||
}
|
||||
|
||||
private static void validatePhoneNumber(CustomerInfo newCustomer)
|
||||
throws NotValidCustomerException {
|
||||
if (newCustomer.phoneNumber().isBlank()) {
|
||||
throw new NotValidCustomerException("Phone number cannot be blank");
|
||||
}
|
||||
if (!newCustomer.phoneNumber().matches(PHONE_NUMBER_REGEX)) {
|
||||
throw new NotValidCustomerException(PHONE_NUMBER_IS_NOT_VALID);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateLastName(CustomerInfo newCustomer) throws NotValidCustomerException {
|
||||
if (newCustomer.lastName().isBlank()) {
|
||||
throw new NotValidCustomerException(LAST_NAME_CANNOT_BE_BLANK);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateFirstName(CustomerInfo newCustomer) throws NotValidCustomerException {
|
||||
if (newCustomer.firstName().isBlank()) {
|
||||
throw new NotValidCustomerException(FIRST_NAME_CANNOT_BE_BLANK);
|
||||
}
|
||||
}
|
||||
}
|
||||
+86
@@ -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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -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);
|
||||
}
|
||||
}
|
||||
+37
@@ -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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -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());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user