19 Commits

Author SHA1 Message Date
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
RKaraMos_EVO 1aa83b0911 ajout enum Category et record BookInfo 2026-06-11 14:23:15 +02:00
RKaraMos_EVO abbd3ee95d ajout du module customer fourni par le prof 2026-06-11 14:22:59 +02:00
RKaraMos_EVO efa6fc49eb ajout du pom et du gitignore pour le module 2026-06-11 14:22:13 +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
Adrien DICK 4008ef4a9b Merge pull request 'Remise au propre du projet' (#1) from dick into main
Reviewed-on: #1
2026-06-11 10:34:19 +02:00
Adrien DICK b99dcd8592 Get api/books pour la page catalogue 2026-06-11 04:32:20 -04:00
Adrien DICK 4e1a0b24f4 🎨 Remise au propre 2026-06-10 16:24:37 -04:00
51 changed files with 2559 additions and 634 deletions
+41 -3
View File
@@ -12,6 +12,7 @@
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.17.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-router-dom": "^7.13.1",
@@ -4804,6 +4805,34 @@
"node": ">=4"
}
},
"node_modules/axios": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.17.0.tgz",
"integrity": "sha512-J8SwNxprqqpbfenehxWYXE7CW+wM1BB4w3+N+g+/Wx40xM4rsLrfPmHHxSWIxJLYDgSY/HqlFPIYb2/S3rxafw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.16.0",
"form-data": "^4.0.5",
"https-proxy-agent": "^5.0.1",
"proxy-from-env": "^2.1.0"
}
},
"node_modules/axios/node_modules/form-data": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -8090,9 +8119,9 @@
"license": "ISC"
},
"node_modules/follow-redirects": {
"version": "1.15.11",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
"integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",
"funding": [
{
"type": "individual",
@@ -13456,6 +13485,15 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-from-env": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/psl": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
+1
View File
@@ -7,6 +7,7 @@
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.17.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-router-dom": "^7.13.1",
+38 -8
View File
@@ -1,14 +1,44 @@
import { Routes, Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import { Routes, Route, Navigate } from 'react-router-dom';
import Layout from './components/Layout';
import Home from './pages/Home';
import Books from './pages/Books';
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 { 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 (
<>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="books" element={<Books />} />
<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="*" element={<NotFound />} />
</Route>
</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);
}
+7
View File
@@ -0,0 +1,7 @@
import axios from 'axios';
const client = axios.create({
baseURL: 'http://localhost:8080',
});
export default client;
+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 } });
}
+11
View File
@@ -0,0 +1,11 @@
import { Outlet } from 'react-router-dom';
import Navbar from './Navbar';
export default function Layout() {
return (
<>
<Navbar />
<Outlet />
</>
);
}
+22 -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';
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,21 @@ 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 && <li><Link to="/profile">Mon compte</Link></li>}
{user?.role === 'admin' && <li><Link to="/customers">Clients</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>
);
+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,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);
}
-13
View File
@@ -1,13 +0,0 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+7 -1
View File
@@ -1,6 +1,8 @@
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 App from './App';
import './styles/global.css';
@@ -8,7 +10,11 @@ const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
<AuthProvider>
<ReservationProvider>
<App />
</ReservationProvider>
</AuthProvider>
</BrowserRouter>
</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>
);
}
+66
View File
@@ -0,0 +1,66 @@
import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { getBookById } from '../api/books';
import { useAuth } from '../context/AuthContext';
import { useReservations } from '../context/ReservationContext';
export default function BookDetail() {
const { user } = useAuth();
const { addReservation } = useReservations();
const { bookId } = useParams();
const [book, setBook] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [phoneNumber, setPhoneNumber] = useState('');
const [reservationStatus, setReservationStatus] = useState(null);
useEffect(() => { getBookById(bookId).then((response) => setBook(response.data)).catch((err) => { console.error(err); setError('Livre introuvable.'); }).finally(() => setLoading(false)); }, [bookId]);
function handleReservation(e) {
e.preventDefault();
addReservation(book, phoneNumber);
setReservationStatus({ success: true, message: 'Réservation effectuée avec succès !' });
setPhoneNumber('');
}
if (loading) return <main><p>Chargement</p></main>;
if (error) return <main><p>{error}</p><Link to="/books"> Retour au catalogue</Link></main>;
return (
<main>
<Link to="/books"> Retour au catalogue</Link>
<h1>{book.title}</h1>
<p>Auteur : {book.author}</p>
<p>ISBN : {book.isbn}</p>
<p>Éditeur : {book.publisher}</p>
<p>Publié le : {book.publicationDate}</p>
<p>Prix : {book.price} </p>
<p>Stock : {book.quantity}</p>
<p>Langue : {book.language}</p>
<p>Catégories : {book.categories?.join(', ')}</p>
{book.description && <p>{book.description}</p>}
{user?.role === 'user' && <section>
<h2>Réserver ce livre</h2>
<form onSubmit={handleReservation}>
<label>
Numéro de téléphone :
<input
type="tel"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value)}
placeholder="0612345678"
required
/>
</label>
<button type="submit">Réserver</button>
</form>
{reservationStatus && (
<p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
{reservationStatus.message}
</p>
)}
</section>}
</main>
);
}
+45
View File
@@ -0,0 +1,45 @@
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);
useEffect(() => {
getBooks()
.then((response) => {
console.log(response.data);
setBooks(response.data.content);
})
.catch((err) => {
console.error(err);
setError("Impossible de charger les livres.");
})
.finally(() => {
setLoading(false);
});
}, []);
if (loading) return <main><p>Chargement</p></main>;
if (error) return <main><p>{error}</p></main>;
return (
<main>
<h1>Catalogue</h1>
{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>
</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>
);
}
-82
View File
@@ -1,91 +1,9 @@
import { Link } from 'react-router-dom';
import '../styles/home.css';
const features = [
{ icon: '📚', title: 'Enregistrer un livre', desc: 'Ajoutez un nouveau titre au catalogue de la bibliothèque.', role: 'admin', path: '/books/new' },
{ icon: '🛒', title: 'Passer une commande', desc: 'Commandez vos livres préférés en quelques secondes.', role: 'user', path: '/orders/new' },
{ icon: '🏷️', title: 'Appliquer une promotion', desc: 'Créez et gérez vos codes promotionnels.', role: 'admin', path: '/promotions/new' },
{ icon: '📌', title: 'Réserver un livre', desc: 'Réservez un exemplaire avant sa disponibilité.', role: 'user', path: '/reservations/new' },
{ icon: '↩️', title: 'Retour de livre', desc: 'Gérez les retours et remises en stock.', role: 'admin', path: '/returns/new' },
{ icon: '⭐', title: 'Points de fidélité', desc: 'Consultez et utilisez vos points cumulés.', role: 'user', path: '/loyalty' },
{ icon: '💬', title: 'Laisser un avis', desc: 'Partagez votre opinion sur vos dernières lectures.', role: 'user', path: '/reviews/new' },
{ icon: '🎫', title: 'Créer un abonnement', desc: 'Souscrivez à un abonnement mensuel ou annuel.', role: 'user', path: '/subscriptions/new' },
{ icon: '🤝', title: 'Prêt entre lecteurs', desc: "Prêtez vos livres à d'autres membres de la communauté.", role: 'user', path: '/loans/new' },
{ icon: '👥', title: 'Commande groupée', desc: 'Participez à des achats groupés avantageux.', role: 'user', path: '/group-orders' },
];
const stats = [
{ value: '10 000+', label: 'Livres disponibles' },
{ value: '5 000+', label: 'Lecteurs actifs' },
{ value: '50+', label: 'Catégories' },
];
export default function Home() {
return (
<main>
{/* Hero */}
<section className="hero">
<p className="hero__eyebrow">Votre bibliothèque en ligne</p>
<h1 className="hero__title">
Des livres pour tous,
<span className="hero__title-italic">partout, toujours.</span>
</h1>
<div className="hero__rule" />
<p className="hero__subtitle">
Commandez, réservez, prêtez et partagez vos lectures.
Une plateforme pensée pour les vrais amoureux des livres.
</p>
<div className="hero__actions">
<Link to="/books">
<button className="hero__btn-primary">Explorer le catalogue</button>
</Link>
<button className="hero__btn-secondary">En savoir plus</button>
</div>
</section>
{/* Stats */}
<section className="stats">
{stats.map(({ value, label }) => (
<div key={label} className="stats__item">
<div className="stats__value">{value}</div>
<div className="stats__label">{label}</div>
</div>
))}
</section>
{/* Features */}
<div className="section-header">
<p className="section-header__eyebrow">Fonctionnalités</p>
<h2 className="section-header__title">Tout ce dont vous avez besoin</h2>
</div>
<section className="features">
<div className="features__grid">
{features.map((f) => (
<Link to={f.path} key={f.title} className="feature-card">
<div className="feature-card__glyph">{f.icon}</div>
<span className={`badge badge--${f.role}`}>
{f.role === 'admin' ? 'Administrateur' : 'Utilisateur'}
</span>
<h3 className="feature-card__title">{f.title}</h3>
<p className="feature-card__desc">{f.desc}</p>
<span className="feature-card__arrow"> Accéder</span>
</Link>
))}
</div>
</section>
{/* Footer CTA */}
<section className="home-cta">
<div className="home-cta__rule" />
<h2 className="home-cta__title">
Prêt à commencer<br />votre aventure ?
</h2>
<p className="home-cta__sub">Rejoignez des milliers de lecteurs dès aujourd'hui.</p>
<Link to="/register">
<span className="home-cta__btn">Créer un compte gratuit</span>
</Link>
</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>
);
}
+3
View File
@@ -0,0 +1,3 @@
export default function NotFound() {
return <main><h1>404 Page introuvable</h1></main>;
}
+3
View File
@@ -0,0 +1,3 @@
export default function Orders() {
return <main><h1>Mes commandes</h1></main>;
}
+3
View File
@@ -0,0 +1,3 @@
export default function Profile() {
return <main><h1>Mon compte</h1></main>;
}
+37
View File
@@ -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>
);
}
-52
View File
@@ -1,52 +0,0 @@
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root {
--bg: #0d0b08;
--bg-raised: #111009;
--bg-card: #0f0d0a;
--gold: #c9a84c;
--gold-dim: rgba(201, 168, 76, 0.45);
--gold-faint:rgba(201, 168, 76, 0.1);
--parchment: #f0e6d0;
--text: #e8dcc8;
--text-muted:rgba(232, 220, 200, 0.45);
--text-dim: rgba(232, 220, 200, 0.25);
--rust: #c05a2a;
--rust-dim: rgba(192, 90, 42, 0.4);
--border: rgba(180, 150, 80, 0.15);
--border-hi: rgba(180, 150, 80, 0.3);
--font-title:'Cinzel', 'Palatino Linotype', Georgia, serif;
--font-body: 'Cormorant Garamond', 'Palatino Linotype', Georgia, serif;
}
html { scroll-behavior: smooth; }
body {
background-color: var(--bg);
color: var(--text);
font-family: var(--font-body);
font-size: 18px;
line-height: 1.7;
-webkit-font-smoothing: antialiased;
}
h1, h2, h3, h4 {
font-family: var(--font-title);
}
a {
color: inherit;
text-decoration: none;
}
button {
cursor: pointer;
font-family: var(--font-title);
border: none;
outline: none;
background: none;
}
-372
View File
@@ -1,372 +0,0 @@
/* ── Hero ───────────────────────────── */
.hero {
padding: 110px 48px 90px;
text-align: center;
border-bottom: 1px solid var(--border);
position: relative;
overflow: hidden;
}
.hero::before {
content: '';
position: absolute;
top: -80px;
left: 50%;
transform: translateX(-50%);
width: 600px;
height: 400px;
background: radial-gradient(ellipse, rgba(180, 140, 50, 0.06) 0%, transparent 70%);
pointer-events: none;
}
.hero__eyebrow {
font-family: var(--font-title);
font-size: 0.65rem;
letter-spacing: 0.28em;
text-transform: uppercase;
color: var(--gold);
opacity: 0.75;
margin-bottom: 22px;
opacity: 0;
animation: fadeUp 0.7s 0.1s ease forwards;
}
.hero__title {
font-family: var(--font-title);
font-size: clamp(2.4rem, 5.5vw, 4.5rem);
font-weight: 600;
letter-spacing: 0.02em;
line-height: 1.1;
color: var(--parchment);
max-width: 820px;
margin: 0 auto 0;
opacity: 0;
animation: fadeUp 0.7s 0.2s ease forwards;
}
.hero__title-italic {
display: block;
font-family: var(--font-body);
font-style: italic;
font-weight: 400;
font-size: clamp(2.8rem, 6vw, 5rem);
color: var(--gold);
margin-top: 4px;
letter-spacing: 0;
}
.hero__rule {
width: 80px;
height: 1px;
background: linear-gradient(90deg, transparent, var(--gold), transparent);
margin: 28px auto;
opacity: 0;
animation: fadeUp 0.7s 0.3s ease forwards;
}
.hero__subtitle {
font-family: var(--font-body);
font-style: italic;
font-size: 1.1rem;
color: var(--text-muted);
max-width: 500px;
margin: 0 auto 40px;
line-height: 1.85;
opacity: 0;
animation: fadeUp 0.7s 0.35s ease forwards;
}
.hero__actions {
display: flex;
gap: 16px;
justify-content: center;
flex-wrap: wrap;
opacity: 0;
animation: fadeUp 0.7s 0.45s ease forwards;
}
.hero__btn-primary {
font-family: var(--font-title);
font-size: 0.68rem;
letter-spacing: 0.16em;
text-transform: uppercase;
color: var(--gold);
padding: 13px 30px;
border: 1px solid var(--gold-dim);
background: var(--gold-faint);
transition: background 0.2s, border-color 0.2s;
}
.hero__btn-primary:hover {
background: rgba(201, 168, 76, 0.2);
border-color: var(--gold);
}
.hero__btn-secondary {
font-family: var(--font-title);
font-size: 0.68rem;
letter-spacing: 0.16em;
text-transform: uppercase;
color: var(--text-muted);
padding: 13px 30px;
border: 1px solid rgba(232, 220, 200, 0.15);
transition: color 0.2s, border-color 0.2s;
}
.hero__btn-secondary:hover {
color: var(--text);
border-color: rgba(232, 220, 200, 0.35);
}
@keyframes fadeUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
/* ── Stats ───────────────────────────── */
.stats {
display: flex;
justify-content: center;
border-bottom: 1px solid var(--border);
}
.stats__item {
flex: 1;
max-width: 240px;
text-align: center;
padding: 36px 16px;
border-right: 1px solid var(--border);
}
.stats__item:last-child {
border-right: none;
}
.stats__value {
font-family: var(--font-title);
font-size: 2rem;
font-weight: 600;
color: var(--gold);
letter-spacing: 0.04em;
}
.stats__label {
font-family: var(--font-title);
font-size: 0.6rem;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--text-dim);
margin-top: 6px;
}
/* ── Section header ──────────────────── */
.section-header {
text-align: center;
padding: 80px 24px 0;
}
.section-header__eyebrow {
font-family: var(--font-title);
font-size: 0.6rem;
letter-spacing: 0.28em;
text-transform: uppercase;
color: rgba(201, 168, 76, 0.55);
margin-bottom: 14px;
}
.section-header__title {
font-family: var(--font-title);
font-size: clamp(1.4rem, 3vw, 2.2rem);
font-weight: 600;
color: var(--parchment);
letter-spacing: 0.04em;
}
/* ── Features ────────────────────────── */
.features {
padding: 40px 0 80px;
}
.features__grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1px;
background: var(--border);
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
@media (max-width: 1000px) {
.features__grid { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 700px) {
.features__grid { grid-template-columns: repeat(2, 1fr); }
.hero { padding: 80px 24px 60px; }
.navbar { padding: 0 20px; }
.stats { flex-direction: column; align-items: center; }
.stats__item { border-right: none; border-bottom: 1px solid var(--border); max-width: 100%; width: 100%; }
}
@media (max-width: 420px) {
.features__grid { grid-template-columns: 1fr; }
}
/* ── Feature card ────────────────────── */
.feature-card {
background: var(--bg);
padding: 30px 24px 26px;
display: flex;
flex-direction: column;
gap: 9px;
text-decoration: none;
color: var(--text);
transition: background 0.25s;
position: relative;
overflow: hidden;
}
.feature-card::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 1px;
background: linear-gradient(90deg, transparent, var(--gold), transparent);
opacity: 0;
transition: opacity 0.3s;
}
.feature-card:hover {
background: #131007;
}
.feature-card:hover::after {
opacity: 1;
}
.feature-card__glyph {
font-size: 1.4rem;
margin-bottom: 4px;
opacity: 0.8;
line-height: 1;
}
.feature-card__title {
font-family: var(--font-title);
font-size: 0.8rem;
font-weight: 600;
letter-spacing: 0.05em;
color: var(--parchment);
line-height: 1.4;
}
.feature-card__desc {
font-family: var(--font-body);
font-style: italic;
font-size: 0.9rem;
color: var(--text-muted);
line-height: 1.65;
flex: 1;
}
.feature-card__arrow {
font-family: var(--font-title);
font-size: 0.65rem;
letter-spacing: 0.12em;
text-transform: uppercase;
color: var(--text-dim);
transition: color 0.2s;
margin-top: 6px;
}
.feature-card:hover .feature-card__arrow {
color: var(--gold);
}
.badge {
display: inline-block;
font-family: var(--font-title);
font-size: 0.55rem;
letter-spacing: 0.12em;
text-transform: uppercase;
padding: 3px 9px;
align-self: flex-start;
margin-bottom: 2px;
}
.badge--admin {
border: 1px solid var(--rust-dim);
color: var(--rust);
}
.badge--user {
border: 1px solid var(--gold-dim);
color: rgba(201, 168, 76, 0.65);
}
/* ── Footer CTA ──────────────────────── */
.home-cta {
padding: 100px 24px;
text-align: center;
border-top: 1px solid var(--border);
position: relative;
overflow: hidden;
}
.home-cta::before {
content: '';
position: absolute;
bottom: -60px;
left: 50%;
transform: translateX(-50%);
width: 500px;
height: 300px;
background: radial-gradient(ellipse, rgba(180, 140, 50, 0.05) 0%, transparent 70%);
pointer-events: none;
}
.home-cta__rule {
width: 60px;
height: 1px;
background: linear-gradient(90deg, transparent, var(--gold), transparent);
margin: 0 auto 32px;
}
.home-cta__title {
font-family: var(--font-title);
font-size: clamp(1.8rem, 4vw, 3rem);
font-weight: 600;
letter-spacing: 0.04em;
color: var(--parchment);
margin-bottom: 16px;
line-height: 1.15;
}
.home-cta__sub {
font-family: var(--font-body);
font-style: italic;
font-size: 1rem;
color: var(--text-muted);
margin-bottom: 40px;
}
.home-cta__btn {
display: inline-block;
font-family: var(--font-title);
font-size: 0.68rem;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--gold);
padding: 13px 36px;
border: 1px solid var(--gold-dim);
background: var(--gold-faint);
transition: background 0.2s, border-color 0.2s;
cursor: pointer;
}
.home-cta__btn:hover {
background: rgba(201, 168, 76, 0.2);
border-color: var(--gold);
}
-98
View File
@@ -1,98 +0,0 @@
.navbar {
position: sticky;
top: 0;
z-index: 200;
height: 56px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 48px;
background: rgba(13, 11, 8, 0.94);
border-bottom: 1px solid var(--border);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.navbar__logo {
font-family: var(--font-title);
font-size: 1.05rem;
font-weight: 600;
letter-spacing: 0.22em;
color: var(--gold);
text-transform: uppercase;
}
.navbar__links {
display: flex;
gap: 8px;
list-style: none;
}
.navbar__links a {
font-family: var(--font-title);
font-size: 0.7rem;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--text-muted);
padding: 6px 14px;
transition: color 0.2s;
position: relative;
}
.navbar__links a::after {
content: '';
position: absolute;
bottom: 0;
left: 14px;
right: 14px;
height: 1px;
background: var(--gold);
transform: scaleX(0);
transition: transform 0.25s ease;
}
.navbar__links a:hover {
color: var(--gold);
}
.navbar__links a:hover::after {
transform: scaleX(1);
}
.navbar__actions {
display: flex;
gap: 10px;
}
.btn-ghost {
font-family: var(--font-title);
font-size: 0.65rem;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--text-muted);
padding: 7px 16px;
border: 1px solid rgba(232, 220, 200, 0.15);
transition: color 0.2s, border-color 0.2s;
}
.btn-ghost:hover {
color: var(--text);
border-color: rgba(232, 220, 200, 0.35);
}
.btn-cta {
font-family: var(--font-title);
font-size: 0.65rem;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--gold);
padding: 7px 16px;
border: 1px solid var(--gold-dim);
background: var(--gold-faint);
transition: background 0.2s, border-color 0.2s;
}
.btn-cta:hover {
background: rgba(201, 168, 76, 0.18);
border-color: var(--gold);
}
Binary file not shown.
+38
View File
@@ -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
+151
View File
@@ -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,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
) {
}
@@ -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
}
@@ -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) {
}
@@ -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();
}
}
@@ -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;
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -0,0 +1,8 @@
package fr.iut_fbleau.but3.dev62.mylibrary.customer.exception;
public class NotValidCustomerException extends Exception {
public NotValidCustomerException(String message) {
super(message);
}
}
@@ -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);
}
}
@@ -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();
}
}
@@ -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);
}
}
}
@@ -0,0 +1,97 @@
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;
import java.util.UUID;
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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@DisplayName("CustomerConverter Unit Tests")
class CustomerConverterTest {
@Nested
@DisplayName("toDomain() method tests")
class ToDomainTests {
@Test
@DisplayName("Should convert CustomerInfo to Customer domain object with loyalty points initialized to 0")
void shouldConvertCustomerInfoToDomain() {
// Given
CustomerInfo customerInfo = new CustomerInfo("John", "Doe", "0123456789");
// When
Customer result = CustomerConverter.toDomain(customerInfo);
// Then
assertNotNull(result);
assertEquals(customerInfo.firstName(), result.getFirstName());
assertEquals(customerInfo.lastName(), result.getLastName());
assertEquals(customerInfo.phoneNumber(), result.getPhoneNumber());
assertEquals(0, result.getLoyaltyPoints());
}
}
@Nested
@DisplayName("toDTO() method tests")
class ToDTOTests {
@Test
@DisplayName("Should convert Customer domain object to CustomerDTO with all fields mapped correctly")
void shouldConvertCustomerToDTO() {
Customer customer = Customer.builder()
.id(UUID.randomUUID())
.firstName("Jane")
.lastName("Smith")
.phoneNumber("9876543210")
.loyaltyPoints(100)
.build();
CustomerDTO result = CustomerConverter.toDTO(customer);
assertNotNull(result);
assertEquals(customer.getId(), result.getId());
assertEquals(customer.getFirstName(), result.getFirstName());
assertEquals(customer.getLastName(), result.getLastName());
assertEquals(customer.getPhoneNumber(), result.getPhoneNumber());
assertEquals(customer.getLoyaltyPoints(), result.getLoyaltyPoints());
}
}
@Test
@DisplayName("Should handle null values properly when converting between objects")
void shouldHandleNullValuesGracefully() {
Customer customer = Customer.builder()
.id(UUID.randomUUID())
.firstName(null)
.lastName("NullTest")
.phoneNumber(null)
.loyaltyPoints(50)
.build();
CustomerDTO result = CustomerConverter.toDTO(customer);
assertNotNull(result);
assertNull(result.getFirstName());
assertEquals("NullTest", result.getLastName());
assertNull(result.getPhoneNumber());
}
@Test
@DisplayName("Should preserve empty string values during conversion")
void shouldPreserveEmptyStrings() {
CustomerInfo customerInfo = new CustomerInfo("", "", "");
Customer domainResult = CustomerConverter.toDomain(customerInfo);
CustomerDTO dtoResult = CustomerConverter.toDTO(domainResult);
assertEquals("", dtoResult.getFirstName());
assertEquals("", dtoResult.getLastName());
assertEquals("", dtoResult.getPhoneNumber());
}
}
@@ -0,0 +1,136 @@
package fr.iut_fbleau.but3.dev62.mylibrary.customer.entity;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.IllegalCustomerPointException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import static org.junit.jupiter.api.Assertions.*;
import java.util.UUID;
class CustomerTest {
@Test
@DisplayName("Builder should create a valid Customer instance")
void testCustomerBuilder() {
UUID id = UUID.randomUUID();
String firstName = "John";
String lastName = "Doe";
String phoneNumber = "0123456789";
int loyaltyPoints = 100;
Customer customer = Customer.builder()
.id(id)
.firstName(firstName)
.lastName(lastName)
.phoneNumber(phoneNumber)
.loyaltyPoints(loyaltyPoints)
.build();
assertEquals(id, customer.getId());
assertEquals(firstName, customer.getFirstName());
assertEquals(lastName, customer.getLastName());
assertEquals(phoneNumber, customer.getPhoneNumber());
assertEquals(loyaltyPoints, customer.getLoyaltyPoints());
}
@Test
@DisplayName("setRandomUUID should change the ID to a new random UUID")
void testSetRandomUUID() {
Customer customer = Customer.builder().build();
UUID originalId = customer.getId();
customer.setRandomUUID();
assertNotNull(customer.getId());
assertNotEquals(originalId, customer.getId());
}
@Nested
@DisplayName("Loyalty Points Tests")
class LoyaltyPointsTests {
@Test
@DisplayName("addLoyaltyPoints should correctly increment loyalty points")
void testAddLoyaltyPoints() {
Customer customer = Customer.builder()
.loyaltyPoints(50)
.build();
int pointsToAdd = 25;
int expectedPoints = 75;
customer.addLoyaltyPoints(pointsToAdd);
assertEquals(expectedPoints, customer.getLoyaltyPoints());
}
@Test
@DisplayName("addLoyaltyPoints should handle zero points correctly")
void testAddZeroLoyaltyPoints() {
Customer customer = Customer.builder()
.loyaltyPoints(50)
.build();
customer.addLoyaltyPoints(0);
assertEquals(50, customer.getLoyaltyPoints());
}
@Test
@DisplayName("removeLoyaltyPoints should correctly decrement loyalty points")
void testRemoveLoyaltyPoints() throws IllegalCustomerPointException {
Customer customer = Customer.builder()
.loyaltyPoints(50)
.build();
int pointsToRemove = 20;
int expectedPoints = 30;
customer.removeLoyaltyPoints(pointsToRemove);
assertEquals(expectedPoints, customer.getLoyaltyPoints());
}
@Test
@DisplayName("removeLoyaltyPoints should handle removing exactly all points")
void testRemoveAllLoyaltyPoints() throws IllegalCustomerPointException {
Customer customer = Customer.builder()
.loyaltyPoints(50)
.build();
customer.removeLoyaltyPoints(50);
assertEquals(0, customer.getLoyaltyPoints());
}
@Test
@DisplayName("removeLoyaltyPoints should throw exception when trying to remove more points than available")
void testRemoveTooManyLoyaltyPoints() {
Customer customer = Customer.builder()
.loyaltyPoints(50)
.build();
int pointsToRemove = 75;
IllegalCustomerPointException exception = assertThrows(
IllegalCustomerPointException.class,
() -> customer.removeLoyaltyPoints(pointsToRemove)
);
assertEquals(50, customer.getLoyaltyPoints());
assertTrue(exception.getMessage().contains(String.valueOf(pointsToRemove)));
assertTrue(exception.getMessage().contains(String.valueOf(customer.getLoyaltyPoints())));
}
@Test
@DisplayName("removeLoyaltyPoints should handle removing zero points correctly")
void testRemoveZeroLoyaltyPoints() throws IllegalCustomerPointException {
Customer customer = Customer.builder()
.loyaltyPoints(50)
.build();
customer.removeLoyaltyPoints(0);
assertEquals(50, customer.getLoyaltyPoints());
}
}
}
@@ -0,0 +1,49 @@
package fr.iut_fbleau.but3.dev62.mylibrary.customer.exception;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CustomerNotFoundExceptionTest {
@Test
@DisplayName("Exception message should contain the UUID provided")
void testExceptionMessageContainsUUID() {
UUID uuid = UUID.randomUUID();
CustomerNotFoundException exception = new CustomerNotFoundException(uuid);
String expectedMessage = String.format("The customer with id %s does not exist", uuid);
assertEquals(expectedMessage, exception.getMessage());
}
@Test
@DisplayName("Exception should use the correct constant message format")
void testExceptionUsesConstantMessageFormat() {
UUID uuid = UUID.randomUUID();
CustomerNotFoundException exception = new CustomerNotFoundException(uuid);
String expectedFormatWithPlaceholder = "The customer with id {0} does not exist";
assertEquals(CustomerNotFoundException.THE_CUSTOMER_WITH_ID_DOES_NOT_EXIST_MESSAGE,
expectedFormatWithPlaceholder);
assertTrue(exception.getMessage().contains(uuid.toString()));
}
@Test
@DisplayName("Exception should be properly thrown and caught")
void testExceptionCanBeThrownAndCaught() {
UUID uuid = UUID.randomUUID();
try {
throw new CustomerNotFoundException(uuid);
} catch (CustomerNotFoundException e) {
String expectedMessage = String.format("The customer with id %s does not exist", uuid);
assertEquals(expectedMessage, e.getMessage());
}
}
}
@@ -0,0 +1,69 @@
package fr.iut_fbleau.but3.dev62.mylibrary.customer.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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class IllegalCustomerPointExceptionTest {
@Test
@DisplayName("Exception message should contain the needed and actual points")
void testExceptionMessageContainsPoints() {
int neededPoints = 100;
int actualPoints = 50;
IllegalCustomerPointException exception = new IllegalCustomerPointException(neededPoints, actualPoints);
String expectedMessage = "Cannot remove 100 points from 50 points";
assertEquals(expectedMessage, exception.getMessage());
}
@ParameterizedTest
@CsvSource({
"100, 50",
"75, 25",
"200, 150",
"1000, 750"
})
@DisplayName("Exception message should be formatted correctly for different point values")
void testExceptionMessageForDifferentPointValues(int neededPoints, int actualPoints) {
IllegalCustomerPointException exception = new IllegalCustomerPointException(neededPoints, actualPoints);
String expectedMessage = MessageFormat.format(IllegalCustomerPointException.CANNOT_REMOVE_LOYALTY_POINTS, neededPoints, actualPoints);
assertEquals(expectedMessage, exception.getMessage());
}
@Test
@DisplayName("Exception should use the correct constant message format")
void testExceptionUsesConstantMessageFormat() {
int neededPoints = 100;
int actualPoints = 50;
IllegalCustomerPointException exception = new IllegalCustomerPointException(neededPoints, actualPoints);
String expectedFormatWithPlaceholder = "Cannot remove {0} points from {1} points";
assertEquals(IllegalCustomerPointException.CANNOT_REMOVE_LOYALTY_POINTS,
expectedFormatWithPlaceholder);
assertTrue(exception.getMessage().contains(String.valueOf(neededPoints)));
assertTrue(exception.getMessage().contains(String.valueOf(actualPoints)));
}
@Test
@DisplayName("Exception should be properly thrown and caught")
void testExceptionCanBeThrownAndCaught() {
int neededPoints = 100;
int actualPoints = 50;
try {
throw new IllegalCustomerPointException(neededPoints, actualPoints);
} catch (IllegalCustomerPointException e) {
String expectedMessage = String.format("Cannot remove %d points from %d points", neededPoints, actualPoints);
assertEquals(expectedMessage, e.getMessage());
}
}
}
@@ -0,0 +1,61 @@
package fr.iut_fbleau.but3.dev62.mylibrary.customer.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.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class NotValidCustomerExceptionTest {
@Test
@DisplayName("Exception should be created with the provided message")
void testExceptionCreation() {
String errorMessage = "Customer data is not valid";
NotValidCustomerException exception = new NotValidCustomerException(errorMessage);
assertEquals(errorMessage, exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {
"First name is required",
"Last name cannot be empty",
"Phone number format is invalid",
"Customer age must be above 18"
})
@DisplayName("Exception should handle different validation messages")
void testExceptionWithDifferentMessages(String errorMessage) {
NotValidCustomerException exception = new NotValidCustomerException(errorMessage);
assertEquals(errorMessage, exception.getMessage());
}
@Test
@DisplayName("Exception should be properly thrown and caught")
void testExceptionCanBeThrownAndCaught() {
String errorMessage = "Required field is missing";
Exception exception = assertThrows(NotValidCustomerException.class, () -> {
throw new NotValidCustomerException(errorMessage);
});
assertEquals(errorMessage, exception.getMessage());
}
@Test
@DisplayName("Exception should be catchable as a general Exception")
void testExceptionInheritance() {
String errorMessage = "Invalid customer data";
try {
throw new NotValidCustomerException(errorMessage);
} catch (Exception e) {
assertEquals(NotValidCustomerException.class, e.getClass());
assertEquals(errorMessage, e.getMessage());
}
}
}
@@ -0,0 +1,227 @@
package fr.iut_fbleau.but3.dev62.mylibrary.customer.repository;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.entity.Customer;
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 java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
class CustomerRepositoryTest {
private CustomerRepository repository;
private Customer customer1;
private Customer customer2;
@BeforeEach
void setUp() {
repository = new CustomerRepository();
customer1 = Customer.builder()
.firstName("John")
.lastName("Doe")
.phoneNumber("0123456789")
.loyaltyPoints(100)
.build();
customer1.setRandomUUID();
customer2 = Customer.builder()
.firstName("Jane")
.lastName("Smith")
.phoneNumber("9876543210")
.loyaltyPoints(200)
.build();
customer2.setRandomUUID();
}
@Test
@DisplayName("New repository should be empty")
void testNewRepositoryIsEmpty() {
List<Customer> customers = repository.findAll();
assertTrue(customers.isEmpty());
assertEquals(0, customers.size());
}
@Nested
@DisplayName("Save operations")
class SaveOperations {
@Test
@DisplayName("Save should add a new customer")
void testSaveNewCustomer() {
Customer savedCustomer = repository.save(customer1);
assertEquals(1, repository.findAll().size());
assertEquals(customer1.getId(), savedCustomer.getId());
assertEquals(customer1.getFirstName(), savedCustomer.getFirstName());
}
@Test
@DisplayName("Save should update existing customer with same ID")
void testSaveUpdatesExistingCustomer() {
repository.save(customer1);
UUID id = customer1.getId();
Customer updatedCustomer = Customer.builder()
.id(id)
.firstName("John")
.lastName("Updated")
.phoneNumber("1111111111")
.loyaltyPoints(150)
.build();
Customer savedCustomer = repository.save(updatedCustomer);
assertEquals(1, repository.findAll().size());
assertEquals(id, savedCustomer.getId());
assertEquals("Updated", savedCustomer.getLastName());
assertEquals("1111111111", savedCustomer.getPhoneNumber());
assertEquals(150, savedCustomer.getLoyaltyPoints());
}
@Test
@DisplayName("Save multiple customers should add all of them")
void testSaveMultipleCustomers() {
repository.save(customer1);
repository.save(customer2);
List<Customer> customers = repository.findAll();
assertEquals(2, customers.size());
assertTrue(customers.contains(customer1));
assertTrue(customers.contains(customer2));
}
}
@Nested
@DisplayName("Find operations")
class FindOperations {
@BeforeEach
void setUpCustomers() {
repository.save(customer1);
repository.save(customer2);
}
@Test
@DisplayName("FindAll should return all customers")
void testFindAll() {
List<Customer> customers = repository.findAll();
assertEquals(2, customers.size());
assertTrue(customers.contains(customer1));
assertTrue(customers.contains(customer2));
}
@Test
@DisplayName("FindById should return customer with matching ID")
void testFindById() {
Optional<Customer> foundCustomer = repository.findById(customer1.getId());
assertTrue(foundCustomer.isPresent());
assertEquals(customer1.getFirstName(), foundCustomer.get().getFirstName());
assertEquals(customer1.getLastName(), foundCustomer.get().getLastName());
}
@Test
@DisplayName("FindById should return empty Optional when ID doesn't exist")
void testFindByIdNotFound() {
UUID nonExistentId = UUID.randomUUID();
Optional<Customer> foundCustomer = repository.findById(nonExistentId);
assertTrue(foundCustomer.isEmpty());
}
@Test
@DisplayName("FindByPhoneNumber should return customer with matching phone number")
void testFindByPhoneNumber() {
Optional<Customer> foundCustomer = repository.findByPhoneNumber("0123456789");
assertTrue(foundCustomer.isPresent());
assertEquals(customer1.getId(), foundCustomer.get().getId());
assertEquals(customer1.getFirstName(), foundCustomer.get().getFirstName());
}
@Test
@DisplayName("FindByPhoneNumber should return empty Optional when phone number doesn't exist")
void testFindByPhoneNumberNotFound() {
Optional<Customer> foundCustomer = repository.findByPhoneNumber("0000000000");
assertTrue(foundCustomer.isEmpty());
}
@Test
@DisplayName("ExistsById should return true when ID exists")
void testExistsByIdExists() {
boolean exists = repository.existsById(customer1.getId());
assertTrue(exists);
}
@Test
@DisplayName("ExistsById should return false when ID doesn't exist")
void testExistsByIdNotExists() {
UUID nonExistentId = UUID.randomUUID();
boolean exists = repository.existsById(nonExistentId);
assertFalse(exists);
}
}
@Nested
@DisplayName("Delete operations")
class DeleteOperations {
@BeforeEach
void setUpCustomers() {
repository.save(customer1);
repository.save(customer2);
}
@Test
@DisplayName("Delete should remove the specified customer")
void testDelete() {
repository.delete(customer1);
List<Customer> customers = repository.findAll();
assertEquals(1, customers.size());
assertFalse(customers.contains(customer1));
assertTrue(customers.contains(customer2));
}
@Test
@DisplayName("DeleteAll should remove all customers")
void testDeleteAll() {
repository.deleteAll();
List<Customer> customers = repository.findAll();
assertTrue(customers.isEmpty());
assertEquals(0, customers.size());
}
@Test
@DisplayName("Delete should not throw exception when customer doesn't exist")
void testDeleteNonExistentCustomer() {
Customer nonExistentCustomer = Customer.builder()
.firstName("Non")
.lastName("Existent")
.phoneNumber("0000000000")
.build();
nonExistentCustomer.setRandomUUID();
assertDoesNotThrow(() -> repository.delete(nonExistentCustomer));
assertEquals(2, repository.findAll().size());
}
}
}
@@ -0,0 +1,279 @@
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.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 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 java.util.Optional;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class CustomerUseCaseTest {
@Mock
private CustomerRepository customerRepository;
@InjectMocks
private CustomerUseCase customerUseCase;
private UUID customerId;
private Customer testCustomer;
private CustomerInfo validCustomerInfo;
@BeforeEach
void setUp() {
customerId = UUID.randomUUID();
testCustomer = Customer.builder()
.id(customerId)
.firstName("John")
.lastName("Doe")
.phoneNumber("0612345678")
.loyaltyPoints(100)
.build();
validCustomerInfo = new CustomerInfo("John", "Doe", "0612345678");
}
@Nested
@DisplayName("Register customer tests")
class RegisterCustomerTests {
@Test
@DisplayName("Should register customer when valid data is provided")
void testRegisterCustomerWithValidData() throws NotValidCustomerException {
when(customerRepository.save(any(Customer.class))).thenReturn(testCustomer);
UUID registeredId = customerUseCase.registerCustomer(validCustomerInfo);
assertNotNull(registeredId);
assertEquals(customerId, registeredId);
verify(customerRepository, times(1)).save(any(Customer.class));
}
@Test
@DisplayName("Should throw exception when customer data is not valid")
void testRegisterCustomerWithInvalidData() {
CustomerInfo invalidCustomerInfo = new CustomerInfo("", "", "");
assertThrows(NotValidCustomerException.class,
() -> customerUseCase.registerCustomer(invalidCustomerInfo));
verify(customerRepository, never()).save(any(Customer.class));
}
}
@Nested
@DisplayName("Find customer tests")
class FindCustomerTests {
@Test
@DisplayName("Should return customer when phone number exists")
void testFindCustomerByPhoneNumber() {
when(customerRepository.findByPhoneNumber("0612345678")).thenReturn(Optional.of(testCustomer));
Optional<CustomerDTO> foundCustomer = customerUseCase.findCustomerByPhoneNumber("0612345678");
assertTrue(foundCustomer.isPresent());
assertEquals(testCustomer.getId(), foundCustomer.get().getId());
assertEquals(testCustomer.getFirstName(), foundCustomer.get().getFirstName());
verify(customerRepository, times(1)).findByPhoneNumber("0612345678");
}
@Test
@DisplayName("Should return empty Optional when phone number doesn't exist")
void testFindCustomerByPhoneNumberNotFound() {
when(customerRepository.findByPhoneNumber("0799999999")).thenReturn(Optional.empty());
Optional<CustomerDTO> foundCustomer = customerUseCase.findCustomerByPhoneNumber("0799999999");
assertTrue(foundCustomer.isEmpty());
verify(customerRepository, times(1)).findByPhoneNumber("0799999999");
}
}
@Nested
@DisplayName("Update customer tests")
class UpdateCustomerTests {
@Test
@DisplayName("Should update customer when valid data is provided")
void testUpdateCustomerWithValidData() throws CustomerNotFoundException, NotValidCustomerException {
when(customerRepository.findById(customerId)).thenReturn(Optional.of(testCustomer));
Customer updatedCustomer = Customer.builder()
.id(customerId)
.firstName("John")
.lastName("Updated")
.phoneNumber("0712345678")
.loyaltyPoints(100)
.build();
when(customerRepository.save(any(Customer.class))).thenReturn(updatedCustomer);
CustomerInfo updateInfo = new CustomerInfo("John", "Updated", "0712345678");
CustomerDTO result = customerUseCase.updateCustomer(customerId, updateInfo);
assertNotNull(result);
assertEquals(customerId, result.getId());
assertEquals("Updated", result.getLastName());
assertEquals("0712345678", result.getPhoneNumber());
verify(customerRepository, times(1)).findById(customerId);
verify(customerRepository, times(1)).save(any(Customer.class));
}
@Test
@DisplayName("Should throw exception when customer ID doesn't exist")
void testUpdateCustomerNotFound() {
UUID nonExistentId = UUID.randomUUID();
when(customerRepository.findById(nonExistentId)).thenReturn(Optional.empty());
CustomerInfo updateInfo = new CustomerInfo("John", "Updated", "0712345678");
assertThrows(CustomerNotFoundException.class,
() -> customerUseCase.updateCustomer(nonExistentId, updateInfo));
verify(customerRepository, times(1)).findById(nonExistentId);
verify(customerRepository, never()).save(any(Customer.class));
}
@Test
@DisplayName("Should throw exception when update data is not valid")
void testUpdateCustomerWithInvalidData() {
CustomerInfo invalidUpdateInfo = new CustomerInfo("", "", "");
assertThrows(NotValidCustomerException.class,
() -> customerUseCase.updateCustomer(customerId, invalidUpdateInfo));
verify(customerRepository, never()).findById(any(UUID.class));
verify(customerRepository, never()).save(any(Customer.class));
}
}
@Nested
@DisplayName("Delete customer tests")
class DeleteCustomerTests {
@Test
@DisplayName("Should delete customer when ID exists")
void testDeleteCustomer() throws CustomerNotFoundException {
when(customerRepository.findById(customerId)).thenReturn(Optional.of(testCustomer));
doNothing().when(customerRepository).delete(testCustomer);
customerUseCase.deleteCustomer(customerId);
verify(customerRepository, times(1)).findById(customerId);
verify(customerRepository, times(1)).delete(testCustomer);
}
@Test
@DisplayName("Should throw exception when customer ID doesn't exist")
void testDeleteCustomerNotFound() {
UUID nonExistentId = UUID.randomUUID();
when(customerRepository.findById(nonExistentId)).thenReturn(Optional.empty());
assertThrows(CustomerNotFoundException.class,
() -> customerUseCase.deleteCustomer(nonExistentId));
verify(customerRepository, times(1)).findById(nonExistentId);
verify(customerRepository, never()).delete(any(Customer.class));
}
}
@Nested
@DisplayName("Loyalty points tests")
class LoyaltyPointsTests {
@Test
@DisplayName("Should add loyalty points to customer")
void testAddLoyaltyPoints() throws CustomerNotFoundException {
when(customerRepository.findById(customerId)).thenReturn(Optional.of(testCustomer));
when(customerRepository.save(testCustomer)).thenReturn(testCustomer);
int initialPoints = testCustomer.getLoyaltyPoints();
int pointsToAdd = 50;
int expectedPoints = initialPoints + pointsToAdd;
int newPoints = customerUseCase.addLoyaltyPoints(customerId, pointsToAdd);
assertEquals(expectedPoints, newPoints);
assertEquals(expectedPoints, testCustomer.getLoyaltyPoints());
verify(customerRepository, times(1)).findById(customerId);
verify(customerRepository, times(1)).save(testCustomer);
}
@Test
@DisplayName("Should throw exception when adding points to non-existent customer")
void testAddLoyaltyPointsToNonExistentCustomer() {
UUID nonExistentId = UUID.randomUUID();
when(customerRepository.findById(nonExistentId)).thenReturn(Optional.empty());
assertThrows(CustomerNotFoundException.class,
() -> customerUseCase.addLoyaltyPoints(nonExistentId, 50));
verify(customerRepository, times(1)).findById(nonExistentId);
verify(customerRepository, never()).save(any(Customer.class));
}
@Test
@DisplayName("Should subtract loyalty points from customer")
void testSubtractLoyaltyPoints() throws CustomerNotFoundException, IllegalCustomerPointException {
when(customerRepository.findById(customerId)).thenReturn(Optional.of(testCustomer));
when(customerRepository.save(testCustomer)).thenReturn(testCustomer);
int initialPoints = testCustomer.getLoyaltyPoints();
int pointsToRemove = 30;
int expectedPoints = initialPoints - pointsToRemove;
int newPoints = customerUseCase.subtractLoyaltyPoints(customerId, pointsToRemove);
assertEquals(expectedPoints, newPoints);
assertEquals(expectedPoints, testCustomer.getLoyaltyPoints());
verify(customerRepository, times(1)).findById(customerId);
verify(customerRepository, times(1)).save(testCustomer);
}
@Test
@DisplayName("Should throw exception when trying to remove more points than available")
void testSubtractTooManyLoyaltyPoints() {
when(customerRepository.findById(customerId)).thenReturn(Optional.of(testCustomer));
int pointsToRemove = 200;
assertThrows(IllegalCustomerPointException.class,
() -> customerUseCase.subtractLoyaltyPoints(customerId, pointsToRemove));
verify(customerRepository, times(1)).findById(customerId);
verify(customerRepository, never()).save(any(Customer.class));
}
@Test
@DisplayName("Should throw exception when subtracting points from non-existent customer")
void testSubtractLoyaltyPointsFromNonExistentCustomer() {
UUID nonExistentId = UUID.randomUUID();
when(customerRepository.findById(nonExistentId)).thenReturn(Optional.empty());
assertThrows(CustomerNotFoundException.class,
() -> customerUseCase.subtractLoyaltyPoints(nonExistentId, 50));
verify(customerRepository, times(1)).findById(nonExistentId);
verify(customerRepository, never()).save(any(Customer.class));
}
}
}
@@ -0,0 +1,155 @@
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;
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 CustomerValidatorTest {
@Test
@DisplayName("Should validate customer with valid data")
void testValidateValidCustomer() {
CustomerInfo validCustomer = new CustomerInfo("John", "Doe", "0612345678");
assertDoesNotThrow(() -> CustomerValidator.validate(validCustomer));
}
@Nested
@DisplayName("First name validation tests")
class FirstNameValidationTests {
@Test
@DisplayName("Should throw exception when first name is blank")
void testValidateBlankFirstName() {
CustomerInfo customerWithBlankFirstName = new CustomerInfo("", "Doe", "0612345678");
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithBlankFirstName)
);
assertEquals(CustomerValidator.FIRST_NAME_CANNOT_BE_BLANK, exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {" ", " ", "\t", "\n"})
@DisplayName("Should throw exception when first name contains only whitespace")
void testValidateWhitespaceFirstName(String whitespace) {
CustomerInfo customerWithWhitespaceFirstName = new CustomerInfo(whitespace, "Doe", "0612345678");
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithWhitespaceFirstName)
);
assertEquals(CustomerValidator.FIRST_NAME_CANNOT_BE_BLANK, exception.getMessage());
}
}
@Nested
@DisplayName("Last name validation tests")
class LastNameValidationTests {
@Test
@DisplayName("Should throw exception when last name is blank")
void testValidateBlankLastName() {
CustomerInfo customerWithBlankLastName = new CustomerInfo("John", "", "0612345678");
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithBlankLastName)
);
assertEquals(CustomerValidator.LAST_NAME_CANNOT_BE_BLANK, exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {" ", " ", "\t", "\n"})
@DisplayName("Should throw exception when last name contains only whitespace")
void testValidateWhitespaceLastName(String whitespace) {
CustomerInfo customerWithWhitespaceLastName = new CustomerInfo("John", whitespace, "0612345678");
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithWhitespaceLastName)
);
assertEquals(CustomerValidator.LAST_NAME_CANNOT_BE_BLANK, exception.getMessage());
}
}
@Nested
@DisplayName("Phone number validation tests")
class PhoneNumberValidationTests {
@Test
@DisplayName("Should throw exception when phone number is blank")
void testValidateBlankPhoneNumber() {
CustomerInfo customerWithBlankPhoneNumber = new CustomerInfo("John", "Doe", "");
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithBlankPhoneNumber)
);
assertEquals("Phone number cannot be blank", exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {" ", " ", "\t", "\n"})
@DisplayName("Should throw exception when phone number contains only whitespace")
void testValidateWhitespacePhoneNumber(String whitespace) {
CustomerInfo customerWithWhitespacePhoneNumber = new CustomerInfo("John", "Doe", whitespace);
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithWhitespacePhoneNumber)
);
assertEquals("Phone number cannot be blank", exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {
"0512345678", // Invalid prefix (not 06 or 07)
"0812345678", // Invalid prefix (not 06 or 07)
"061234567", // Too short (missing one digit)
"06123456789", // Too long (one extra digit)
"6123456789", // Missing leading 0
"O612345678", // Letter O instead of zero
"+33612345678", // International format not supported
"06 12 34 56 78" // Contains spaces
})
@DisplayName("Should throw exception when phone number format is invalid")
void testValidateInvalidPhoneNumberFormat(String invalidPhoneNumber) {
CustomerInfo customerWithInvalidPhoneNumber = new CustomerInfo("John", "Doe", invalidPhoneNumber);
NotValidCustomerException exception = assertThrows(
NotValidCustomerException.class,
() -> CustomerValidator.validate(customerWithInvalidPhoneNumber)
);
assertEquals(CustomerValidator.PHONE_NUMBER_IS_NOT_VALID, exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {
"0612345678", // Valid 06 number
"0712345678", // Valid 07 number
"0699999999", // Valid 06 number with all 9s
"0700000000" // Valid 07 number with all 0s
})
@DisplayName("Should validate when phone number format is valid")
void testValidateValidPhoneNumberFormat(String validPhoneNumber) {
CustomerInfo customerWithValidPhoneNumber = new CustomerInfo("John", "Doe", validPhoneNumber);
assertDoesNotThrow(() -> CustomerValidator.validate(customerWithValidPhoneNumber));
}
}
}
@@ -0,0 +1,14 @@
package fr.iut_fbleau.but3.dev62.mylibrary.features;
import org.junit.platform.suite.api.*;
import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME;
import static io.cucumber.junit.platform.engine.Constants.PLUGIN_PROPERTY_NAME;
@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty")
@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "fr.iut_fbleau.but3.dev62.mylibrary.features")
public class RunCucumberTest {
}
@@ -0,0 +1,223 @@
package fr.iut_fbleau.but3.dev62.mylibrary.features.client;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
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;
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.usecase.CustomerUseCase;
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.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public class CustomerSteps {
private final CustomerRepository customerRepository = new CustomerRepository();
private final CustomerUseCase customerUseCase = new CustomerUseCase(customerRepository);
private final Map<String, UUID> customerPhoneUUID = new HashMap<>();
private UUID customerRegistration;
private Optional<CustomerDTO> customerByPhoneNumber;
private Customer updatedCustomer;
private IllegalCustomerPointException illegalCustomerPointException;
private NotValidCustomerException notValidCustomerException;
@Given("the system has the following customers:")
public void theSystemHasTheFollowingCustomers(DataTable dataTable) {
int size = customerRepository.findAll().size();
if (size > 0) {
customerRepository.deleteAll();
}
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
for (Map<String, String> customer : customers) {
String numeroTelephone = customer.get("numeroTelephone");
Customer newCustomer = Customer.builder()
.firstName(customer.get("prenom"))
.lastName(customer.get("nom"))
.phoneNumber(numeroTelephone)
.loyaltyPoints(Integer.parseInt(customer.get("pointsFidelite")))
.build();
Customer save = customerRepository.save(newCustomer);
customerPhoneUUID.put(numeroTelephone, save.getId());
}
assertEquals(customers.size(), customerRepository.findAll().size());
}
@When("I create a new customer with the following information:")
public void iCreateANewCustomerWithTheFollowingInformation(DataTable dataTable) throws NotValidCustomerException {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
Map<String, String> customerInfo = rows.getFirst();
CustomerInfo newCustomer = new CustomerInfo(
customerInfo.get("prenom"),
customerInfo.get("nom"),
customerInfo.get("numeroTelephone")
);
customerRegistration = customerUseCase.registerCustomer(newCustomer);
}
@And("the system now has {int} customers")
public void theSystemNowHasCustomers(int numberOfCustomers) {
assertEquals(numberOfCustomers, customerRepository.findAll().size());
}
@And("the customer has {int} loyalty points")
public void theCustomerHasLoyaltyPoints(int loyaltyPoints) {
Customer customer = customerRepository.findById(customerRegistration).orElseThrow();
assertEquals(loyaltyPoints, customer.getLoyaltyPoints());
}
@Then("a new customer is created")
public void aNewCustomerIsCreated() {
assertNotNull(customerRegistration);
}
@When("I request the customer with phone number {string}")
public void iRequestTheCustomerWithPhoneNumber(String phoneNumber) {
customerByPhoneNumber = customerUseCase.findCustomerByPhoneNumber(phoneNumber);
}
@Then("I receive the following customer information:")
public void iReceiveTheFollowingCustomerInformation(DataTable dataTable) {
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
Map<String, String> customerInfo = customers.getFirst();
assertTrue(customerByPhoneNumber.isPresent());
CustomerDTO customerDTO = customerByPhoneNumber.get();
assertEquals(customerInfo.get("prenom"), customerDTO.getFirstName());
assertEquals(customerInfo.get("nom"), customerDTO.getLastName());
assertEquals(customerInfo.get("numeroTelephone"), customerDTO.getPhoneNumber());
}
@When("I update customer {string} with the following information:")
public void iUpdateCustomerWithTheFollowingInformation(String phoneNumber, DataTable dataTable)
throws CustomerNotFoundException, NotValidCustomerException {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
Map<String, String> customerData = rows.getFirst();
CustomerInfo customerInfo = new CustomerInfo(
customerData.get("prenom"),
customerData.get("nom"),
customerData.get("numeroTelephone")
);
UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.updateCustomer(uuid, customerInfo);
}
@Then("the customer {string} has the following updated information:")
public void theCustomerHasTheFollowingUpdatedInformation(String phoneNumber, DataTable dataTable) {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
Map<String, String> updatedDate = rows.getFirst();
UUID uuid = customerPhoneUUID.get(phoneNumber);
updatedCustomer = customerRepository.findById(uuid).orElseThrow();
assertEquals(updatedDate.get("numeroTelephone"), updatedCustomer.getPhoneNumber());
assertEquals(updatedDate.get("prenom"), updatedCustomer.getFirstName());
assertEquals(updatedDate.get("nom"), updatedCustomer.getLastName());
}
@And("the loyalty points remain unchanged at {int}")
public void theLoyaltyPointsRemainUnchangedAt(int expectedLoyaltyPoint) {
assertEquals(expectedLoyaltyPoint, updatedCustomer.getLoyaltyPoints());
}
@When("I delete the customer with phone number {string}")
public void iDeleteTheCustomerWithPhoneNumber(String phoneNumber) throws CustomerNotFoundException {
UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.deleteCustomer(uuid);
}
@Then("the customer {string} is removed from the system")
public void theCustomerIsRemovedFromTheSystem(String phoneNumber) {
UUID uuid = customerPhoneUUID.get(phoneNumber);
assertFalse(customerRepository.existsById(uuid));
}
@When("I add {int} loyalty points to customer {string}")
public void iAddLoyaltyPointsToCustomer(int loyaltyPointToAdd, String phoneNumber) throws CustomerNotFoundException {
UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.addLoyaltyPoints(uuid, loyaltyPointToAdd);
}
@Then("customer {string} now has {int} loyalty points")
public void customerNowHasLoyaltyPoints(String phoneNumber, int expectedLoyaltyPoints) {
UUID uuid = customerPhoneUUID.get(phoneNumber);
Customer customer = customerRepository.findById(uuid).orElseThrow();
assertEquals(expectedLoyaltyPoints, customer.getLoyaltyPoints());
}
@When("I deduct {int} loyalty points from customer {string} for a purchase")
public void iDeductLoyaltyPointsFromCustomerForAPurchase(int pointsToRemove, String phoneNumber) throws CustomerNotFoundException, IllegalCustomerPointException {
UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.subtractLoyaltyPoints(uuid, pointsToRemove);
}
@When("I try to create a new customer with the following information:")
public void iTryToCreateANewCustomerWithTheFollowingInformation(DataTable ddataTable) {
List<Map<String, String>> rows = ddataTable.asMaps(String.class, String.class);
Map<String, String> customerInfo = rows.getFirst();
CustomerInfo newCustomer = new CustomerInfo(
customerInfo.get("prenom"),
customerInfo.get("nom"),
customerInfo.get("numeroTelephone")
);
notValidCustomerException = assertThrows(NotValidCustomerException.class, () -> customerUseCase.registerCustomer(newCustomer));
}
@Then("the creation fails")
public void theCreationFails() {
assertNotNull(notValidCustomerException);
}
@And("I receive an error for validation customer message containing {string}")
public void iReceiveAnErrorMessageContaining(String errorMessage) {
assertEquals(errorMessage, notValidCustomerException.getMessage());
}
@And("the system still has {int} customers")
public void theSystemStillHasCustomers(int expectedNumberOfUser) {
assertEquals(expectedNumberOfUser, customerRepository.findAll().size());
}
@When("I try to deduct {int} loyalty points from customer {string} for a purchase")
public void iTryToDeductLoyaltyPointsFromCustomerForAPurchase(int points, String phoneNumber) {
UUID uuid = customerPhoneUUID.get(phoneNumber);
illegalCustomerPointException = assertThrows(IllegalCustomerPointException.class, () -> customerUseCase.subtractLoyaltyPoints(uuid, points));
}
@Then("the deduction fails")
public void theDeductionFails() {
assertNotNull(illegalCustomerPointException);
}
@And("I receive an error for illegal customer exception message containing {string}")
public void iReceiveAnErrorForIllegalCustomerExceptionMessageContaining(String errorMessage) {
assertEquals(errorMessage, illegalCustomerPointException.getMessage());
}
}

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