Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 677cb6249a | |||
| 65b9eed6dc | |||
| dabf1df6b9 | |||
| e8ac8f0c54 | |||
| 24849c6414 | |||
| d7dfec49fd | |||
| 0d9f8dc539 | |||
| 4197f99116 | |||
| 092a020059 | |||
| 8708686994 | |||
| 0d37efd227 | |||
| 1cf4bed83b | |||
| 0ba4e5599e |
@@ -11,6 +11,9 @@ import Customers from './pages/Customers';
|
|||||||
import Login from './pages/Login';
|
import Login from './pages/Login';
|
||||||
import Reservations from './pages/Reservations';
|
import Reservations from './pages/Reservations';
|
||||||
import Returns from './pages/Returns';
|
import Returns from './pages/Returns';
|
||||||
|
import Subscription from './pages/Subscription';
|
||||||
|
import Loans from './pages/Loans';
|
||||||
|
import GroupOrders from './pages/GroupOrders';
|
||||||
import { useAuth } from './context/AuthContext';
|
import { useAuth } from './context/AuthContext';
|
||||||
|
|
||||||
function RequireAuth({ children }) {
|
function RequireAuth({ children }) {
|
||||||
@@ -39,6 +42,9 @@ export default function App() {
|
|||||||
<Route path="profile" element={<RequireAuth><Profile /></RequireAuth>} />
|
<Route path="profile" element={<RequireAuth><Profile /></RequireAuth>} />
|
||||||
<Route path="customers" element={<RequireAdmin><Customers /></RequireAdmin>} />
|
<Route path="customers" element={<RequireAdmin><Customers /></RequireAdmin>} />
|
||||||
<Route path="returns" element={<RequireAdmin><Returns /></RequireAdmin>} />
|
<Route path="returns" element={<RequireAdmin><Returns /></RequireAdmin>} />
|
||||||
|
<Route path="subscription" element={<RequireAuth><Subscription /></RequireAuth>} />
|
||||||
|
<Route path="loans" element={<RequireAuth><Loans /></RequireAuth>} />
|
||||||
|
<Route path="group-orders" element={<RequireAuth><GroupOrders /></RequireAuth>} />
|
||||||
<Route path="*" element={<NotFound />} />
|
<Route path="*" element={<NotFound />} />
|
||||||
</Route>
|
</Route>
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import client from './client';
|
||||||
|
|
||||||
|
export function createOrder(order) {
|
||||||
|
return client.post('/api/orders', order);
|
||||||
|
}
|
||||||
@@ -20,6 +20,9 @@ export default function Navbar() {
|
|||||||
<li><Link to="/books">Catalogue</Link></li>
|
<li><Link to="/books">Catalogue</Link></li>
|
||||||
{user && <li><Link to="/orders">Commandes</Link></li>}
|
{user && <li><Link to="/orders">Commandes</Link></li>}
|
||||||
{user?.role === 'user' && <li><Link to="/reservations">Mes réservations</Link></li>}
|
{user?.role === 'user' && <li><Link to="/reservations">Mes réservations</Link></li>}
|
||||||
|
{user?.role === 'user' && <li><Link to="/subscription">Mon abonnement</Link></li>}
|
||||||
|
{user?.role === 'user' && <li><Link to="/loans">Mes prêts</Link></li>}
|
||||||
|
{user && <li><Link to="/group-orders">Commandes groupées</Link></li>}
|
||||||
{user && <li><Link to="/profile">Mon compte</Link></li>}
|
{user && <li><Link to="/profile">Mon compte</Link></li>}
|
||||||
{user?.role === 'admin' && <li><Link to="/customers">Clients</Link></li>}
|
{user?.role === 'admin' && <li><Link to="/customers">Clients</Link></li>}
|
||||||
{user?.role === 'admin' && <li><Link to="/returns">Retours</Link></li>}
|
{user?.role === 'admin' && <li><Link to="/returns">Retours</Link></li>}
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { createContext, useContext, useState } from 'react';
|
||||||
|
|
||||||
|
const GroupOrderContext = createContext(null);
|
||||||
|
|
||||||
|
export function GroupOrderProvider({ children }) {
|
||||||
|
const [groups, setGroups] = useState(() => {
|
||||||
|
const saved = localStorage.getItem('groupOrders');
|
||||||
|
return saved ? JSON.parse(saved) : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
function createGroup(creatorPhone) {
|
||||||
|
const group = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
creatorPhone,
|
||||||
|
orders: [],
|
||||||
|
status: 'OPEN',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
const updated = [...groups, group];
|
||||||
|
setGroups(updated);
|
||||||
|
localStorage.setItem('groupOrders', JSON.stringify(updated));
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addOrderToGroup(groupId, phoneNumber, bookId, bookTitle, quantity) {
|
||||||
|
const updated = groups.map(g => {
|
||||||
|
if (g.id !== groupId) return g;
|
||||||
|
const order = {
|
||||||
|
orderId: crypto.randomUUID(),
|
||||||
|
phoneNumber,
|
||||||
|
bookId,
|
||||||
|
bookTitle,
|
||||||
|
quantity: Number(quantity),
|
||||||
|
addedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
return { ...g, orders: [...g.orders, order] };
|
||||||
|
});
|
||||||
|
setGroups(updated);
|
||||||
|
localStorage.setItem('groupOrders', JSON.stringify(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeGroup(groupId) {
|
||||||
|
const updated = groups.map(g =>
|
||||||
|
g.id === groupId ? { ...g, status: 'CLOSED' } : g
|
||||||
|
);
|
||||||
|
setGroups(updated);
|
||||||
|
localStorage.setItem('groupOrders', JSON.stringify(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<GroupOrderContext.Provider value={{ groups, createGroup, addOrderToGroup, closeGroup }}>
|
||||||
|
{children}
|
||||||
|
</GroupOrderContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useGroupOrders() {
|
||||||
|
return useContext(GroupOrderContext);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { createContext, useContext, useState } from 'react';
|
||||||
|
|
||||||
|
const LoanContext = createContext(null);
|
||||||
|
|
||||||
|
export function LoanProvider({ children }) {
|
||||||
|
const [loans, setLoans] = useState(() => {
|
||||||
|
const saved = localStorage.getItem('loans');
|
||||||
|
return saved ? JSON.parse(saved) : [];
|
||||||
|
});
|
||||||
|
|
||||||
|
function addLoan(book, borrowerUsername, dueDate) {
|
||||||
|
const loan = {
|
||||||
|
loanId: crypto.randomUUID(),
|
||||||
|
bookId: book.isbn,
|
||||||
|
bookTitle: book.title,
|
||||||
|
bookAuthor: book.author,
|
||||||
|
borrowerUsername,
|
||||||
|
dueDate,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
loanedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
const updated = [...loans, loan];
|
||||||
|
setLoans(updated);
|
||||||
|
localStorage.setItem('loans', JSON.stringify(updated));
|
||||||
|
return loan;
|
||||||
|
}
|
||||||
|
|
||||||
|
function returnLoan(loanId) {
|
||||||
|
const updated = loans.map(l =>
|
||||||
|
l.loanId === loanId ? { ...l, status: 'RETURNED' } : l
|
||||||
|
);
|
||||||
|
setLoans(updated);
|
||||||
|
localStorage.setItem('loans', JSON.stringify(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LoanContext.Provider value={{ loans, addLoan, returnLoan }}>
|
||||||
|
{children}
|
||||||
|
</LoanContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLoans() {
|
||||||
|
return useContext(LoanContext);
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { createContext, useContext, useState } from 'react';
|
||||||
|
|
||||||
|
const SubscriptionContext = createContext(null);
|
||||||
|
|
||||||
|
const PLANS = [
|
||||||
|
{ id: 'basic', name: 'Basic', price: 9.99, description: '2 livres par mois' },
|
||||||
|
{ id: 'standard', name: 'Standard', price: 14.99, description: '5 livres par mois' },
|
||||||
|
{ id: 'premium', name: 'Premium', price: 24.99, description: 'Livres illimités par mois' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export { PLANS };
|
||||||
|
|
||||||
|
export function SubscriptionProvider({ children }) {
|
||||||
|
const [subscription, setSubscription] = useState(() => {
|
||||||
|
const saved = localStorage.getItem('subscription');
|
||||||
|
return saved ? JSON.parse(saved) : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
function subscribe(planId, phoneNumber) {
|
||||||
|
const plan = PLANS.find(p => p.id === planId);
|
||||||
|
const newSubscription = {
|
||||||
|
subscriptionId: crypto.randomUUID(),
|
||||||
|
planId,
|
||||||
|
planName: plan.name,
|
||||||
|
price: plan.price,
|
||||||
|
phoneNumber,
|
||||||
|
status: 'ACTIVE',
|
||||||
|
startDate: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
setSubscription(newSubscription);
|
||||||
|
localStorage.setItem('subscription', JSON.stringify(newSubscription));
|
||||||
|
return newSubscription;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelSubscription() {
|
||||||
|
const updated = { ...subscription, status: 'CANCELLED' };
|
||||||
|
setSubscription(updated);
|
||||||
|
localStorage.setItem('subscription', JSON.stringify(updated));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SubscriptionContext.Provider value={{ subscription, subscribe, cancelSubscription, PLANS }}>
|
||||||
|
{children}
|
||||||
|
</SubscriptionContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSubscription() {
|
||||||
|
return useContext(SubscriptionContext);
|
||||||
|
}
|
||||||
+10
-1
@@ -5,6 +5,9 @@ import { AuthProvider } from './context/AuthContext';
|
|||||||
import { ReservationProvider } from './context/ReservationContext';
|
import { ReservationProvider } from './context/ReservationContext';
|
||||||
import { ReviewProvider } from './context/ReviewContext';
|
import { ReviewProvider } from './context/ReviewContext';
|
||||||
import { ReturnProvider } from './context/ReturnContext';
|
import { ReturnProvider } from './context/ReturnContext';
|
||||||
|
import { SubscriptionProvider } from './context/SubscriptionContext';
|
||||||
|
import { LoanProvider } from './context/LoanContext';
|
||||||
|
import { GroupOrderProvider } from './context/GroupOrderContext';
|
||||||
import App from './App';
|
import App from './App';
|
||||||
import './styles/global.css';
|
import './styles/global.css';
|
||||||
|
|
||||||
@@ -16,7 +19,13 @@ root.render(
|
|||||||
<ReservationProvider>
|
<ReservationProvider>
|
||||||
<ReviewProvider>
|
<ReviewProvider>
|
||||||
<ReturnProvider>
|
<ReturnProvider>
|
||||||
<App />
|
<SubscriptionProvider>
|
||||||
|
<LoanProvider>
|
||||||
|
<GroupOrderProvider>
|
||||||
|
<App />
|
||||||
|
</GroupOrderProvider>
|
||||||
|
</LoanProvider>
|
||||||
|
</SubscriptionProvider>
|
||||||
</ReturnProvider>
|
</ReturnProvider>
|
||||||
</ReviewProvider>
|
</ReviewProvider>
|
||||||
</ReservationProvider>
|
</ReservationProvider>
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import { getBookById } from '../api/books';
|
|||||||
import { useAuth } from '../context/AuthContext';
|
import { useAuth } from '../context/AuthContext';
|
||||||
import { useReservations } from '../context/ReservationContext';
|
import { useReservations } from '../context/ReservationContext';
|
||||||
import { useReviews } from '../context/ReviewContext';
|
import { useReviews } from '../context/ReviewContext';
|
||||||
|
import { useSubscription } from '../context/SubscriptionContext';
|
||||||
|
|
||||||
export default function BookDetail() {
|
export default function BookDetail() {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const { addReservation } = useReservations();
|
const { subscription } = useSubscription();
|
||||||
|
const { addReservation, reservations } = useReservations();
|
||||||
const { addReview, getReviewsByBook } = useReviews();
|
const { addReview, getReviewsByBook } = useReviews();
|
||||||
const [rating, setRating] = useState(5);
|
const [rating, setRating] = useState(5);
|
||||||
const [comment, setComment] = useState('');
|
const [comment, setComment] = useState('');
|
||||||
@@ -97,27 +99,60 @@ export default function BookDetail() {
|
|||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{user?.role === 'user' && <section>
|
{user?.role === 'user' && (
|
||||||
<h2>Réserver ce livre</h2>
|
<section>
|
||||||
<form onSubmit={handleReservation}>
|
<h2>Réserver ce livre</h2>
|
||||||
<label>
|
{!subscription || subscription.status !== 'ACTIVE' ? (
|
||||||
Numéro de téléphone :
|
<p>
|
||||||
<input
|
Vous devez avoir un abonnement actif pour réserver un livre.{' '}
|
||||||
type="tel"
|
<Link to="/subscription">S'abonner</Link>
|
||||||
value={phoneNumber}
|
</p>
|
||||||
onChange={(e) => setPhoneNumber(e.target.value)}
|
) : (() => {
|
||||||
placeholder="0612345678"
|
const QUOTAS = { basic: 2, standard: 5, premium: Infinity };
|
||||||
required
|
const quota = QUOTAS[subscription.planId];
|
||||||
/>
|
const thisMonthStart = new Date();
|
||||||
</label>
|
thisMonthStart.setDate(1);
|
||||||
<button type="submit">Réserver</button>
|
thisMonthStart.setHours(0, 0, 0, 0);
|
||||||
</form>
|
const usedThisMonth = reservations.filter(r =>
|
||||||
{reservationStatus && (
|
new Date(r.reservedAt) >= thisMonthStart
|
||||||
<p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
|
).length;
|
||||||
{reservationStatus.message}
|
const remaining = quota - usedThisMonth;
|
||||||
</p>
|
|
||||||
)}
|
if (remaining <= 0) {
|
||||||
</section>}
|
return (
|
||||||
|
<p style={{ color: 'orange' }}>
|
||||||
|
Vous avez atteint votre quota de {quota} réservation(s) ce mois-ci.
|
||||||
|
<Link to="/subscription"> Passer au plan supérieur</Link>
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<p>Réservations restantes ce mois : <strong>{remaining === Infinity ? 'illimitées' : remaining}</strong></p>
|
||||||
|
<form onSubmit={handleReservation}>
|
||||||
|
<label>
|
||||||
|
Numéro de téléphone :
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={phoneNumber}
|
||||||
|
onChange={(e) => setPhoneNumber(e.target.value)}
|
||||||
|
placeholder="0612345678"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Réserver</button>
|
||||||
|
</form>
|
||||||
|
{reservationStatus && (
|
||||||
|
<p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
|
||||||
|
{reservationStatus.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})()}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -29,17 +29,21 @@ export default function Books() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<main>
|
<main>
|
||||||
<h1>Catalogue</h1>
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1rem' }}>
|
||||||
{user?.role === 'admin' && <Link to="/books/new">+ Ajouter un livre</Link>}
|
<h1 style={{ margin: 0 }}>Catalogue</h1>
|
||||||
<ul>
|
{user?.role === 'admin' && <Link to="/books/new">+ Ajouter un livre</Link>}
|
||||||
|
</div>
|
||||||
|
<div className="card-grid">
|
||||||
{books.map((book) => (
|
{books.map((book) => (
|
||||||
<li key={book.isbn}>
|
<Link to={`/books/${book.isbn}`} key={book.isbn} style={{ textDecoration: 'none', color: 'inherit' }}>
|
||||||
<Link to={`/books/${book.isbn}`}>
|
<div className="card">
|
||||||
<strong>{book.title}</strong> - {book.author}
|
<h3>{book.title}</h3>
|
||||||
</Link>
|
<p>{book.author}</p>
|
||||||
</li>
|
<p style={{ marginTop: '0.5rem', fontSize: '0.8rem', color: '#999' }}>ISBN : {book.isbn}</p>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useGroupOrders } from '../context/GroupOrderContext';
|
||||||
|
import { useAuth } from '../context/AuthContext';
|
||||||
|
|
||||||
|
export default function GroupOrders() {
|
||||||
|
const { groups, createGroup, addOrderToGroup, closeGroup } = useGroupOrders();
|
||||||
|
const { user } = useAuth();
|
||||||
|
|
||||||
|
const [creatorPhone, setCreatorPhone] = useState('');
|
||||||
|
const [joinGroupId, setJoinGroupId] = useState('');
|
||||||
|
const [joinForm, setJoinForm] = useState({ phoneNumber: '', bookId: '', bookTitle: '', quantity: 1 });
|
||||||
|
const [joinStatus, setJoinStatus] = useState({});
|
||||||
|
const [createStatus, setCreateStatus] = useState(null);
|
||||||
|
|
||||||
|
function handleCreateGroup(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const group = createGroup(creatorPhone);
|
||||||
|
setCreateStatus(`Groupe créé ! ID : ${group.id}`);
|
||||||
|
setCreatorPhone('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleJoinGroup(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
const group = groups.find(g => g.id === joinGroupId);
|
||||||
|
if (!group) {
|
||||||
|
setJoinStatus(prev => ({ ...prev, [joinGroupId]: 'Groupe introuvable.' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (group.status === 'CLOSED') {
|
||||||
|
setJoinStatus(prev => ({ ...prev, [joinGroupId]: 'Ce groupe est fermé.' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
addOrderToGroup(joinGroupId, joinForm.phoneNumber, joinForm.bookId, joinForm.bookTitle, joinForm.quantity);
|
||||||
|
setJoinStatus(prev => ({ ...prev, [joinGroupId]: 'Commande ajoutée au groupe !' }));
|
||||||
|
setJoinForm({ phoneNumber: '', bookId: '', bookTitle: '', quantity: 1 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const openGroups = groups.filter(g => g.status === 'OPEN');
|
||||||
|
const closedGroups = groups.filter(g => g.status === 'CLOSED');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<h1>Commandes groupées</h1>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Créer un groupe</h2>
|
||||||
|
<form onSubmit={handleCreateGroup}>
|
||||||
|
<label>
|
||||||
|
Votre téléphone :
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={creatorPhone}
|
||||||
|
onChange={e => setCreatorPhone(e.target.value)}
|
||||||
|
placeholder="0612345678"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Créer un groupe</button>
|
||||||
|
</form>
|
||||||
|
{createStatus && <p style={{ color: 'green' }}>{createStatus}</p>}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Rejoindre un groupe</h2>
|
||||||
|
<form onSubmit={handleJoinGroup}>
|
||||||
|
<label>
|
||||||
|
ID du groupe :
|
||||||
|
<input
|
||||||
|
value={joinGroupId}
|
||||||
|
onChange={e => setJoinGroupId(e.target.value)}
|
||||||
|
placeholder="Collez l'ID du groupe ici"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Votre téléphone :
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={joinForm.phoneNumber}
|
||||||
|
onChange={e => setJoinForm(prev => ({ ...prev, phoneNumber: e.target.value }))}
|
||||||
|
placeholder="0612345678"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
ISBN du livre :
|
||||||
|
<input
|
||||||
|
value={joinForm.bookId}
|
||||||
|
onChange={e => setJoinForm(prev => ({ ...prev, bookId: e.target.value }))}
|
||||||
|
placeholder="9782070361038"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Titre du livre :
|
||||||
|
<input
|
||||||
|
value={joinForm.bookTitle}
|
||||||
|
onChange={e => setJoinForm(prev => ({ ...prev, bookTitle: e.target.value }))}
|
||||||
|
placeholder="Nom du livre"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Quantité :
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
value={joinForm.quantity}
|
||||||
|
onChange={e => setJoinForm(prev => ({ ...prev, quantity: e.target.value }))}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Rejoindre</button>
|
||||||
|
</form>
|
||||||
|
{joinStatus[joinGroupId] && (
|
||||||
|
<p style={{ color: joinStatus[joinGroupId].includes('introuvable') || joinStatus[joinGroupId].includes('fermé') ? 'red' : 'green' }}>
|
||||||
|
{joinStatus[joinGroupId]}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Groupes ouverts ({openGroups.length})</h2>
|
||||||
|
{openGroups.length === 0 ? (
|
||||||
|
<p>Aucun groupe ouvert.</p>
|
||||||
|
) : (
|
||||||
|
<ul>
|
||||||
|
{openGroups.map(g => (
|
||||||
|
<li key={g.id}>
|
||||||
|
<strong>Groupe {g.id.slice(0, 8)}…</strong>
|
||||||
|
<br />
|
||||||
|
Créé par : {g.creatorPhone}
|
||||||
|
<br />
|
||||||
|
Créé le : {new Date(g.createdAt).toLocaleDateString('fr-FR')}
|
||||||
|
<br />
|
||||||
|
Participants : {g.orders.length}
|
||||||
|
{g.orders.length > 0 && (
|
||||||
|
<ul>
|
||||||
|
{g.orders.map(o => (
|
||||||
|
<li key={o.orderId}>
|
||||||
|
{o.phoneNumber} , {o.bookTitle} (x{o.quantity})
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
<button onClick={() => closeGroup(g.id)}>Fermer le groupe</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{closedGroups.length > 0 && (
|
||||||
|
<section>
|
||||||
|
<h2>Groupes fermés ({closedGroups.length})</h2>
|
||||||
|
<ul>
|
||||||
|
{closedGroups.map(g => (
|
||||||
|
<li key={g.id}>
|
||||||
|
<strong>Groupe {g.id.slice(0, 8)}…</strong> , {g.orders.length} commande(s) , <small>Fermé ✓</small>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,28 @@
|
|||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import '../styles/home.css';
|
import { useAuth } from '../context/AuthContext';
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main>
|
<main>
|
||||||
|
<h1>Bienvenue sur Biblio</h1>
|
||||||
|
<p>Gérez vos livres, réservations et abonnements depuis une seule interface.</p>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Accès rapide</h2>
|
||||||
|
<ul>
|
||||||
|
<li><Link to="/books">📚 Parcourir le catalogue</Link></li>
|
||||||
|
{user?.role === 'user' && <li><Link to="/reservations">🔖 Mes réservations</Link></li>}
|
||||||
|
{user?.role === 'user' && <li><Link to="/loans">📖 Mes prêts</Link></li>}
|
||||||
|
{user?.role === 'user' && <li><Link to="/subscription">⭐ Mon abonnement</Link></li>}
|
||||||
|
{user && <li><Link to="/orders">🛒 Passer une commande</Link></li>}
|
||||||
|
{user && <li><Link to="/group-orders">👥 Commandes groupées</Link></li>}
|
||||||
|
{user?.role === 'admin' && <li><Link to="/customers">👤 Gestion des clients</Link></li>}
|
||||||
|
{user?.role === 'admin' && <li><Link to="/returns">↩️ Retours de livres</Link></li>}
|
||||||
|
{!user && <li><Link to="/login">Connexion</Link></li>}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { useLoans } from '../context/LoanContext';
|
||||||
|
|
||||||
|
export default function Loans() {
|
||||||
|
const { loans, returnLoan } = useLoans();
|
||||||
|
|
||||||
|
const activeLoans = loans.filter(l => l.status === 'ACTIVE');
|
||||||
|
const returnedLoans = loans.filter(l => l.status === 'RETURNED');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<h1>Mes prêts</h1>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Prêts en cours ({activeLoans.length})</h2>
|
||||||
|
{activeLoans.length === 0 ? (
|
||||||
|
<p>Aucun prêt en cours.</p>
|
||||||
|
) : (
|
||||||
|
<ul>
|
||||||
|
{activeLoans.map(l => (
|
||||||
|
<li key={l.loanId}>
|
||||||
|
<strong>{l.bookTitle}</strong> — {l.bookAuthor}
|
||||||
|
<br />
|
||||||
|
Emprunteur : {l.borrowerUsername}
|
||||||
|
<br />
|
||||||
|
À rendre avant le : {new Date(l.dueDate).toLocaleDateString('fr-FR')}
|
||||||
|
<br />
|
||||||
|
Prêté le : {new Date(l.loanedAt).toLocaleDateString('fr-FR')}
|
||||||
|
<br />
|
||||||
|
<button onClick={() => returnLoan(l.loanId)}>Marquer comme rendu</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{returnedLoans.length > 0 && (
|
||||||
|
<section>
|
||||||
|
<h2>Prêts terminés ({returnedLoans.length})</h2>
|
||||||
|
<ul>
|
||||||
|
{returnedLoans.map(l => (
|
||||||
|
<li key={l.loanId}>
|
||||||
|
<strong>{l.bookTitle}</strong> — {l.bookAuthor}
|
||||||
|
<br />
|
||||||
|
Emprunteur : {l.borrowerUsername}
|
||||||
|
<br />
|
||||||
|
<small>Rendu ✓</small>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,160 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { createOrder } from '../api/orders';
|
||||||
|
import { getBookById } from '../api/books';
|
||||||
|
|
||||||
export default function Orders() {
|
export default function Orders() {
|
||||||
return <main><h1>Mes commandes</h1></main>;
|
const [customerId, setCustomerId] = useState('');
|
||||||
|
const [paymentMethod, setPaymentMethod] = useState('CREDIT_CARD');
|
||||||
|
const [address, setAddress] = useState({ street: '', city: '', postalCode: '', country: '' });
|
||||||
|
const [lines, setLines] = useState([{ bookId: '', quantity: 1 }]);
|
||||||
|
const [promoCode, setPromoCode] = useState('');
|
||||||
|
const [message, setMessage] = useState(null);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
function handleAddressChange(e) {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setAddress((prev) => ({ ...prev, [name]: value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleLineChange(index, field, value) {
|
||||||
|
setLines((prev) => prev.map((line, i) => (i === index ? { ...line, [field]: value } : line)));
|
||||||
|
}
|
||||||
|
function addLine() {
|
||||||
|
setLines((prev) => [...prev, { bookId: '', quantity: 1 }]);
|
||||||
|
}
|
||||||
|
function removeLine(index) {
|
||||||
|
const [promoValid, setPromoValid] = useState(true);
|
||||||
|
const [estimate, setEstimate] = useState(null);
|
||||||
|
const [estimating, setEstimating] = useState(false);
|
||||||
|
const [estimateError, setEstimateError] = useState(null);
|
||||||
|
setLines((prev) => prev.filter((_, i) => i !== index));
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSubmit(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
setSubmitting(true);
|
||||||
|
setMessage(null);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
customerId,
|
||||||
|
paymentMethod,
|
||||||
|
address,
|
||||||
|
orderLineDtos: lines.map((line) => ({
|
||||||
|
bookId: Number(line.bookId),
|
||||||
|
quantity: Number(line.quantity),
|
||||||
|
})),
|
||||||
|
...(promoCode ? { promoCode } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
createOrder(payload)
|
||||||
|
.then((response) => setMessage('Commande créée'))
|
||||||
|
.catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
setMessage(error.response?.data?.message || 'Erreur lors de la commande.');
|
||||||
|
})
|
||||||
|
.finally(() => setSubmitting(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<h1>Passer une commande</h1>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<label>ID client
|
||||||
|
<input value={customerId} onChange={(e) => setCustomerId(e.target.value)} required />
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<h2>Livres</h2>
|
||||||
|
{lines.map((line, index) => (
|
||||||
|
<div key={index}>
|
||||||
|
<input type="number" placeholder="ISBN du livre" value={line.bookId}
|
||||||
|
onChange={(e) => handleLineChange(index, 'bookId', e.target.value)} required />
|
||||||
|
<input type="number" placeholder="Quantité" value={line.quantity}
|
||||||
|
onChange={(e) => handleLineChange(index, 'quantity', e.target.value)} required />
|
||||||
|
function validatePromo(code) {
|
||||||
|
if (!code) return true;
|
||||||
|
// simple format: PROMO10 => 10% , PROMO5 => 5%
|
||||||
|
return /^PROMO\d{1,2}$/.test(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleEstimate() {
|
||||||
|
setEstimating(true);
|
||||||
|
setEstimate(null);
|
||||||
|
setEstimateError(null);
|
||||||
|
try {
|
||||||
|
const ids = lines.map((l) => Number(l.bookId)).filter((n) => !Number.isNaN(n) && n > 0);
|
||||||
|
if (ids.length === 0) {
|
||||||
|
setEstimateError('Aucun ISBN valide');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const unique = Array.from(new Set(ids));
|
||||||
|
const responses = await Promise.all(unique.map((id) => getBookById(id).then((r) => r.data)));
|
||||||
|
const priceMap = new Map();
|
||||||
|
unique.forEach((id, idx) => priceMap.set(id, responses[idx].prix ?? responses[idx].price ?? 0));
|
||||||
|
|
||||||
|
let total = 0;
|
||||||
|
for (const l of lines) {
|
||||||
|
const id = Number(l.bookId);
|
||||||
|
const qty = Number(l.quantity) || 0;
|
||||||
|
total += (priceMap.get(id) || 0) * qty;
|
||||||
|
}
|
||||||
|
|
||||||
|
let discounted = total;
|
||||||
|
if (promoCode) {
|
||||||
|
const m = promoCode.match(/^PROMO(\d{1,2})$/);
|
||||||
|
if (m) {
|
||||||
|
const pct = Math.max(0, Math.min(100, Number(m[1])));
|
||||||
|
discounted = total * (1 - pct / 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setEstimate({ total, discounted });
|
||||||
|
} catch (err) {
|
||||||
|
setEstimateError('Erreur lors de l\'estimation');
|
||||||
|
console.error(err);
|
||||||
|
} finally {
|
||||||
|
setEstimating(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{lines.length > 1 && (
|
||||||
|
<button type="button" onClick={() => removeLine(index)}>Retirer</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button type="button" onClick={addLine}>+ Ajouter un livre</button>
|
||||||
|
|
||||||
|
<h2>Adresse de livraison</h2>
|
||||||
|
<input name="street" placeholder="Rue" value={address.street} onChange={handleAddressChange} required />
|
||||||
|
<input name="city" placeholder="Ville" value={address.city} onChange={handleAddressChange} required />
|
||||||
|
<input name="postalCode" placeholder="Code postal" value={address.postalCode} onChange={handleAddressChange} required />
|
||||||
|
<input name="country" placeholder="Pays" value={address.country} onChange={handleAddressChange} required />
|
||||||
|
|
||||||
|
<h2>Paiement</h2>
|
||||||
|
<label>Code promo
|
||||||
|
<input value={promoCode} onChange={(e) => { setPromoCode(e.target.value); setPromoValid(validatePromo(e.target.value)); }} placeholder="Code promo (optionnel)" />
|
||||||
|
</label>
|
||||||
|
{!promoValid && <div style={{ color: 'red' }}>Format de code promo invalide (ex: PROMO10)</div>}
|
||||||
|
<select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)}>
|
||||||
|
<option value="CREDIT_CARD">Carte bancaire</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<div style={{ marginTop: 8 }}>
|
||||||
|
<button type="button" onClick={handleEstimate} disabled={estimating}>
|
||||||
|
{estimating ? 'Estimation…' : 'Estimer le total'}
|
||||||
|
</button>
|
||||||
|
{estimateError && <div style={{ color: 'red' }}>{estimateError}</div>}
|
||||||
|
{estimate && (
|
||||||
|
<div>
|
||||||
|
<div>Total estimé : {estimate.total.toFixed(2)} €</div>
|
||||||
|
<div>Après promo : {estimate.discounted.toFixed(2)} €</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" disabled={submitting}>
|
||||||
|
{submitting ? 'Envoi…' : 'Valider la commande'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{message && <p>{message}</p>}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,45 @@
|
|||||||
|
import { useAuth } from '../context/AuthContext';
|
||||||
|
import { useReservations } from '../context/ReservationContext';
|
||||||
|
import { useLoans } from '../context/LoanContext';
|
||||||
|
import { useSubscription } from '../context/SubscriptionContext';
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
return <main><h1>Mon compte</h1></main>;
|
const { user } = useAuth();
|
||||||
|
const { reservations } = useReservations();
|
||||||
|
const { loans } = useLoans();
|
||||||
|
const { subscription } = useSubscription();
|
||||||
|
|
||||||
|
const activeReservations = reservations.filter(r => r.status !== 'CANCELLED');
|
||||||
|
const activeLoans = loans.filter(l => l.status === 'ACTIVE');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<h1>Mon compte</h1>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Informations</h2>
|
||||||
|
<p><strong>Nom d'utilisateur :</strong> {user?.username}</p>
|
||||||
|
<p><strong>Rôle :</strong> {user?.role === 'admin' ? 'Administrateur' : 'Utilisateur'}</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{user?.role === 'user' && (
|
||||||
|
<>
|
||||||
|
<section>
|
||||||
|
<h2>Abonnement</h2>
|
||||||
|
{subscription ? (
|
||||||
|
<p><strong>Plan actif :</strong> {subscription.planName}</p>
|
||||||
|
) : (
|
||||||
|
<p>Aucun abonnement actif.</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Activité</h2>
|
||||||
|
<p>Réservations en cours : <strong>{activeReservations.length}</strong></p>
|
||||||
|
<p>Prêts en cours : <strong>{activeLoans.length}</strong></p>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,32 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
import { useReservations } from '../context/ReservationContext';
|
import { useReservations } from '../context/ReservationContext';
|
||||||
|
import { useLoans } from '../context/LoanContext';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
|
|
||||||
export default function Reservations() {
|
export default function Reservations() {
|
||||||
const { reservations, cancelReservation } = useReservations();
|
const { reservations, cancelReservation } = useReservations();
|
||||||
|
const { addLoan } = useLoans();
|
||||||
|
const [loanForms, setLoanForms] = useState({});
|
||||||
|
const [loanStatuses, setLoanStatuses] = useState({});
|
||||||
|
|
||||||
|
function handleLoanChange(reservationId, field, value) {
|
||||||
|
setLoanForms(prev => ({
|
||||||
|
...prev,
|
||||||
|
[reservationId]: { ...prev[reservationId], [field]: value }
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleLoan(e, reservation) {
|
||||||
|
e.preventDefault();
|
||||||
|
const form = loanForms[reservation.reservationId] || {};
|
||||||
|
addLoan(
|
||||||
|
{ isbn: reservation.bookId, title: reservation.bookTitle, author: reservation.bookAuthor },
|
||||||
|
form.borrowerUsername,
|
||||||
|
form.dueDate
|
||||||
|
);
|
||||||
|
setLoanStatuses(prev => ({ ...prev, [reservation.reservationId]: 'Prêt enregistré avec succès !' }));
|
||||||
|
setLoanForms(prev => ({ ...prev, [reservation.reservationId]: {} }));
|
||||||
|
}
|
||||||
|
|
||||||
if (reservations.length === 0) {
|
if (reservations.length === 0) {
|
||||||
return (
|
return (
|
||||||
@@ -29,6 +53,36 @@ export default function Reservations() {
|
|||||||
Statut : {r.status}
|
Statut : {r.status}
|
||||||
<br />
|
<br />
|
||||||
<button onClick={() => cancelReservation(r.reservationId)}>Annuler</button>
|
<button onClick={() => cancelReservation(r.reservationId)}>Annuler</button>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Prêter ce livre à un autre lecteur</summary>
|
||||||
|
<form onSubmit={e => handleLoan(e, r)}>
|
||||||
|
<label>
|
||||||
|
Identifiant de l'emprunteur :
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={loanForms[r.reservationId]?.borrowerUsername || ''}
|
||||||
|
onChange={e => handleLoanChange(r.reservationId, 'borrowerUsername', e.target.value)}
|
||||||
|
placeholder="ex: alice"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Date de retour prévue :
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={loanForms[r.reservationId]?.dueDate || ''}
|
||||||
|
onChange={e => handleLoanChange(r.reservationId, 'dueDate', e.target.value)}
|
||||||
|
min={new Date().toISOString().split('T')[0]}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit">Prêter</button>
|
||||||
|
</form>
|
||||||
|
{loanStatuses[r.reservationId] && (
|
||||||
|
<p style={{ color: 'green' }}>{loanStatuses[r.reservationId]}</p>
|
||||||
|
)}
|
||||||
|
</details>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useSubscription } from '../context/SubscriptionContext';
|
||||||
|
|
||||||
|
export default function Subscription() {
|
||||||
|
const { subscription, subscribe, cancelSubscription, PLANS } = useSubscription();
|
||||||
|
const [selectedPlan, setSelectedPlan] = useState('basic');
|
||||||
|
const [phoneNumber, setPhoneNumber] = useState('');
|
||||||
|
const [message, setMessage] = useState(null);
|
||||||
|
|
||||||
|
function handleSubscribe(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
subscribe(selectedPlan, phoneNumber);
|
||||||
|
setMessage({ success: true, text: 'Abonnement créé avec succès !' });
|
||||||
|
setPhoneNumber('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCancel() {
|
||||||
|
cancelSubscription();
|
||||||
|
setMessage({ success: false, text: 'Abonnement annulé.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<h1>Mon abonnement</h1>
|
||||||
|
|
||||||
|
{subscription && subscription.status === 'ACTIVE' ? (
|
||||||
|
<section>
|
||||||
|
<h2>Abonnement actif</h2>
|
||||||
|
<p>Plan : <strong>{subscription.planName}</strong></p>
|
||||||
|
<p>Prix : <strong>{subscription.price} € / mois</strong></p>
|
||||||
|
<p>Téléphone : {subscription.phoneNumber}</p>
|
||||||
|
<p>Depuis le : {new Date(subscription.startDate).toLocaleDateString('fr-FR')}</p>
|
||||||
|
<p>Statut : <strong style={{ color: 'green' }}>{subscription.status}</strong></p>
|
||||||
|
<button onClick={handleCancel}>Annuler l'abonnement</button>
|
||||||
|
</section>
|
||||||
|
) : (
|
||||||
|
<section>
|
||||||
|
<h2>Choisir un abonnement</h2>
|
||||||
|
<form onSubmit={handleSubscribe}>
|
||||||
|
<div>
|
||||||
|
{PLANS.map(plan => (
|
||||||
|
<label key={plan.id} style={{ display: 'block', marginBottom: '8px' }}>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="plan"
|
||||||
|
value={plan.id}
|
||||||
|
checked={selectedPlan === plan.id}
|
||||||
|
onChange={() => setSelectedPlan(plan.id)}
|
||||||
|
/>
|
||||||
|
{' '}<strong>{plan.name}</strong> , {plan.price} € / mois , {plan.description}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<label>
|
||||||
|
Numéro de téléphone :
|
||||||
|
<input
|
||||||
|
type="tel"
|
||||||
|
value={phoneNumber}
|
||||||
|
onChange={e => setPhoneNumber(e.target.value)}
|
||||||
|
placeholder="0612345678"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit">S'abonner</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<p style={{ color: message.success ? 'green' : 'red' }}>{message.text}</p>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
*, *::before, *::after {
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: system-ui, sans-serif;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: #222;
|
||||||
|
background: #f7f7f7;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
max-width: 860px;
|
||||||
|
margin: 2rem auto;
|
||||||
|
padding: 0 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 1.6rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
color: #111;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 1.15rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 1.5rem 0 0.75rem;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: #2563eb;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
ul {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
li {
|
||||||
|
padding: 0.75rem 0;
|
||||||
|
border-bottom: 1px solid #e5e5e5;
|
||||||
|
line-height: 1.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
li:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Forms */
|
||||||
|
|
||||||
|
form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
max-width: 480px;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: #444;
|
||||||
|
}
|
||||||
|
|
||||||
|
input, select, textarea {
|
||||||
|
padding: 0.45rem 0.65rem;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-family: inherit;
|
||||||
|
background: #fff;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, select:focus, textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: #2563eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
|
||||||
|
button {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.45rem 1rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-family: inherit;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #222;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background: #f0f0f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
button[type="submit"],
|
||||||
|
button.primary {
|
||||||
|
background: #2563eb;
|
||||||
|
color: #fff;
|
||||||
|
border-color: #2563eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
button[type="submit"]:hover,
|
||||||
|
button.primary:hover {
|
||||||
|
background: #1d4ed8;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sections */
|
||||||
|
|
||||||
|
section {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Details / summary */
|
||||||
|
|
||||||
|
details {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
summary {
|
||||||
|
cursor: pointer;
|
||||||
|
color: #2563eb;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
summary:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
details form {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #e5e5e5;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Status messages */
|
||||||
|
|
||||||
|
.msg-success {
|
||||||
|
color: #15803d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-error {
|
||||||
|
color: #dc2626;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Cards (book list etc.) */
|
||||||
|
|
||||||
|
.card-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #e5e5e5;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card h3 {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card p {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: #555;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
.navbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1.5rem;
|
||||||
|
padding: 0 1.25rem;
|
||||||
|
height: 52px;
|
||||||
|
background: #fff;
|
||||||
|
border-bottom: 1px solid #e5e5e5;
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar__logo {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
color: #111;
|
||||||
|
text-decoration: none;
|
||||||
|
margin-right: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar__links {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
list-style: none;
|
||||||
|
flex: 1;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar__links a {
|
||||||
|
padding: 0.3rem 0.6rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: #444;
|
||||||
|
text-decoration: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar__links a:hover {
|
||||||
|
background: #f0f0f0;
|
||||||
|
color: #111;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: #555;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar__actions button {
|
||||||
|
padding: 0.3rem 0.75rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# mylibrary — back-end Java (méthode BDD)
|
||||||
|
|
||||||
|
Back-end du projet **2026-DEV-BUT3**. Reproduit, en Java pur, le cœur métier
|
||||||
|
de l'API consommée par le front React `my-library/`.
|
||||||
|
|
||||||
|
## Méthode
|
||||||
|
|
||||||
|
Conformément au cours `maintenanceApplicativeCours1.pdf` (Behavior-Driven
|
||||||
|
Development), pour chaque comportement on :
|
||||||
|
|
||||||
|
1. Écrit le scénario attendu (en Gherkin / `.feature` ou en `@DisplayName` JUnit)
|
||||||
|
2. Écrit le test qui le vérifie
|
||||||
|
3. Implémente le code qui fait passer le test
|
||||||
|
|
||||||
|
## Structure (calquée sur le module `customer` fourni par le prof)
|
||||||
|
|
||||||
|
```
|
||||||
|
src/main/java/fr/iut_fbleau/but3/dev62/mylibrary/
|
||||||
|
├─ customer/ Module fourni par l'enseignant (intact)
|
||||||
|
│ ├─ CustomerInfo.java record d'entrée
|
||||||
|
│ ├─ CustomerDTO.java DTO de sortie
|
||||||
|
│ ├─ entity/ Customer (objet métier, règles fidélité)
|
||||||
|
│ ├─ exception/ Exceptions métier
|
||||||
|
│ ├─ converter/ Mapping Info <-> entity <-> DTO
|
||||||
|
│ ├─ validator/ Règles de validation
|
||||||
|
│ ├─ repository/ Stockage en mémoire (List)
|
||||||
|
│ └─ usecase/ Cas d'usage (orchestration)
|
||||||
|
└─ book/ Module développé en miroir (notre travail)
|
||||||
|
└─ … (mêmes sous-paquets, même découpage)
|
||||||
|
|
||||||
|
src/test/java/.../mylibrary/
|
||||||
|
├─ customer/ Tests JUnit fournis par l'enseignant
|
||||||
|
├─ book/ Tests JUnit que nous avons écrits
|
||||||
|
└─ features/
|
||||||
|
├─ RunCucumberTest.java (du prof, intact)
|
||||||
|
├─ client/CustomerSteps.java (du prof, intact)
|
||||||
|
├─ book/BookSteps.java (notre travail)
|
||||||
|
└─ resources/features/
|
||||||
|
├─ client.feature (du prof, intact)
|
||||||
|
└─ book.feature (notre travail)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Dépendances
|
||||||
|
|
||||||
|
Strictement les mêmes que dans le template du prof :
|
||||||
|
|
||||||
|
- JUnit 5 (jupiter-api, params, engine + platform-suite, platform-engine, platform-launcher)
|
||||||
|
- Mockito (core, junit-jupiter)
|
||||||
|
- Cucumber (cucumber-java, cucumber-junit-platform-engine)
|
||||||
|
- Lombok
|
||||||
|
|
||||||
|
## Build & test
|
||||||
|
|
||||||
|
Pré-requis : **JDK 21** + **Maven 3.9+**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -f mylibrary test
|
||||||
|
```
|
||||||
|
|
||||||
|
Cette commande exécute :
|
||||||
|
|
||||||
|
- les tests unitaires JUnit (entity, validator, converter, repository, usecase, exceptions)
|
||||||
|
- les scénarios Cucumber (`client.feature` + `book.feature`) via `RunCucumberTest`
|
||||||
|
|
||||||
|
## Périmètre couvert
|
||||||
|
|
||||||
|
Conformément à la consigne (« reproduire le strict nécessaire pour démontrer
|
||||||
|
la maîtrise »), l'API se limite aux deux domaines présents dans le swagger
|
||||||
|
qui structurent l'app React :
|
||||||
|
|
||||||
|
- **Catalogue** (`book`) : enregistrer, consulter par ISBN, lister tous les livres,
|
||||||
|
refuser ISBN dupliqué, refuser un livre invalide, gérer le stock.
|
||||||
|
- **Comptes clients** (`customer`) : enregistrer, consulter par téléphone, mettre
|
||||||
|
à jour, supprimer, ajouter / retirer des points de fidélité (module fourni).
|
||||||
|
|
||||||
|
L'exposition HTTP réelle utilisée par les développeurs front est l'API du prof
|
||||||
|
(`mylibrary-0.0.1-SNAPSHOT.jar`) ; ce module sert à démontrer la maîtrise
|
||||||
|
de la **conception métier en BDD/TDD**.
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package fr.iut_fbleau.but3.dev62.mylibrary.book.usecase;
|
||||||
|
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.converter.BookConverter;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.validator.BookValidator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public final class BookUseCase {
|
||||||
|
|
||||||
|
private final BookRepository bookRepository;
|
||||||
|
|
||||||
|
public BookUseCase(BookRepository bookRepository) {
|
||||||
|
this.bookRepository = bookRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long registerBook(BookInfo bookInfo) throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
BookValidator.validate(bookInfo);
|
||||||
|
if (bookRepository.existsByIsbn(bookInfo.isbn())) {
|
||||||
|
throw new BookAlreadyExistsException(bookInfo.isbn());
|
||||||
|
}
|
||||||
|
Book toRegister = BookConverter.toDomain(bookInfo);
|
||||||
|
Book registered = bookRepository.save(toRegister);
|
||||||
|
return registered.getIsbn();
|
||||||
|
}
|
||||||
|
|
||||||
|
public BookDTO getBookByIsbn(long isbn) throws BookNotFoundException {
|
||||||
|
Optional<Book> optional = bookRepository.findByIsbn(isbn);
|
||||||
|
if (optional.isEmpty()) {
|
||||||
|
throw new BookNotFoundException(isbn);
|
||||||
|
}
|
||||||
|
return BookConverter.toDTO(optional.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<BookDTO> getAllBooks() {
|
||||||
|
return bookRepository.findAll().stream()
|
||||||
|
.map(BookConverter::toDTO)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
package fr.iut_fbleau.but3.dev62.mylibrary.book.usecase;
|
||||||
|
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Category;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class BookUseCaseTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private BookUseCase bookUseCase;
|
||||||
|
|
||||||
|
private BookInfo validInfo;
|
||||||
|
private Book validBook;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
validInfo = new BookInfo(
|
||||||
|
9780321125217L,
|
||||||
|
"DDD",
|
||||||
|
"Evans",
|
||||||
|
"Addison-Wesley",
|
||||||
|
LocalDate.of(2003, 8, 22),
|
||||||
|
54.99,
|
||||||
|
10,
|
||||||
|
List.of(Category.SCIENCE),
|
||||||
|
"desc",
|
||||||
|
"EN"
|
||||||
|
);
|
||||||
|
validBook = Book.builder()
|
||||||
|
.isbn(validInfo.isbn())
|
||||||
|
.title(validInfo.title())
|
||||||
|
.author(validInfo.author())
|
||||||
|
.publisher(validInfo.publisher())
|
||||||
|
.publicationDate(validInfo.publicationDate())
|
||||||
|
.price(validInfo.price())
|
||||||
|
.quantity(validInfo.quantity())
|
||||||
|
.categories(validInfo.categories())
|
||||||
|
.description(validInfo.description())
|
||||||
|
.language(validInfo.language())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("registerBook tests")
|
||||||
|
class RegisterTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should register a new book and return its ISBN")
|
||||||
|
void testRegisterBook() throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
when(bookRepository.existsByIsbn(validInfo.isbn())).thenReturn(false);
|
||||||
|
when(bookRepository.save(any(Book.class))).thenReturn(validBook);
|
||||||
|
|
||||||
|
long isbn = bookUseCase.registerBook(validInfo);
|
||||||
|
|
||||||
|
assertEquals(validInfo.isbn(), isbn);
|
||||||
|
verify(bookRepository).existsByIsbn(validInfo.isbn());
|
||||||
|
verify(bookRepository).save(any(Book.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should reject invalid book information without touching the repository")
|
||||||
|
void testRegisterInvalidBook() {
|
||||||
|
BookInfo invalid = new BookInfo(0L, "", "", "", null, -1, -1, null, "", "");
|
||||||
|
assertThrows(NotValidBookException.class, () -> bookUseCase.registerBook(invalid));
|
||||||
|
verifyNoInteractions(bookRepository);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should reject duplicate ISBN")
|
||||||
|
void testRegisterDuplicate() {
|
||||||
|
when(bookRepository.existsByIsbn(validInfo.isbn())).thenReturn(true);
|
||||||
|
assertThrows(BookAlreadyExistsException.class, () -> bookUseCase.registerBook(validInfo));
|
||||||
|
verify(bookRepository).existsByIsbn(validInfo.isbn());
|
||||||
|
verify(bookRepository, never()).save(any(Book.class));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("getBookByIsbn tests")
|
||||||
|
class GetByIdTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should return the BookDTO when ISBN exists")
|
||||||
|
void testGetById() throws BookNotFoundException {
|
||||||
|
when(bookRepository.findByIsbn(validInfo.isbn())).thenReturn(Optional.of(validBook));
|
||||||
|
|
||||||
|
BookDTO dto = bookUseCase.getBookByIsbn(validInfo.isbn());
|
||||||
|
|
||||||
|
assertEquals(validInfo.isbn(), dto.getIsbn());
|
||||||
|
assertEquals(validInfo.title(), dto.getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should throw when ISBN does not exist")
|
||||||
|
void testGetByIdNotFound() {
|
||||||
|
when(bookRepository.findByIsbn(99L)).thenReturn(Optional.empty());
|
||||||
|
assertThrows(BookNotFoundException.class, () -> bookUseCase.getBookByIsbn(99L));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
@DisplayName("getAllBooks tests")
|
||||||
|
class GetAllBooksTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should map every book returned by the repository to a DTO")
|
||||||
|
void testGetAllBooks() {
|
||||||
|
when(bookRepository.findAll()).thenReturn(List.of(validBook));
|
||||||
|
|
||||||
|
List<BookDTO> result = bookUseCase.getAllBooks();
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals(validBook.getIsbn(), result.getFirst().getIsbn());
|
||||||
|
assertEquals(validBook.getTitle(), result.getFirst().getTitle());
|
||||||
|
verify(bookRepository).findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Should return an empty list when no book is stored")
|
||||||
|
void testGetAllBooksWhenEmpty() {
|
||||||
|
when(bookRepository.findAll()).thenReturn(List.of());
|
||||||
|
|
||||||
|
List<BookDTO> result = bookUseCase.getAllBooks();
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
package fr.iut_fbleau.but3.dev62.mylibrary.features.book;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Category;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookAlreadyExistsException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
|
||||||
|
import fr.iut_fbleau.but3.dev62.mylibrary.book.usecase.BookUseCase;
|
||||||
|
import io.cucumber.datatable.DataTable;
|
||||||
|
import io.cucumber.java.en.And;
|
||||||
|
import io.cucumber.java.en.Given;
|
||||||
|
import io.cucumber.java.en.Then;
|
||||||
|
import io.cucumber.java.en.When;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class BookSteps {
|
||||||
|
|
||||||
|
private final BookRepository bookRepository = new BookRepository();
|
||||||
|
private final BookUseCase bookUseCase = new BookUseCase(bookRepository);
|
||||||
|
|
||||||
|
private long lastRegisteredIsbn;
|
||||||
|
private BookDTO retrievedBook;
|
||||||
|
private List<BookDTO> allBooks;
|
||||||
|
private Exception lastException;
|
||||||
|
|
||||||
|
@Given("the catalog has the following books:")
|
||||||
|
public void theCatalogHasTheFollowingBooks(DataTable dataTable) throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
bookRepository.deleteAll();
|
||||||
|
for (Map<String, String> row : dataTable.asMaps(String.class, String.class)) {
|
||||||
|
bookUseCase.registerBook(toBookInfo(row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I register a new book with the following information:")
|
||||||
|
public void iRegisterANewBook(DataTable dataTable) throws NotValidBookException, BookAlreadyExistsException {
|
||||||
|
Map<String, String> row = dataTable.asMaps(String.class, String.class).getFirst();
|
||||||
|
lastRegisteredIsbn = bookUseCase.registerBook(toBookInfo(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I try to register a new book with the following information:")
|
||||||
|
public void iTryToRegisterANewBook(DataTable dataTable) {
|
||||||
|
Map<String, String> row = dataTable.asMaps(String.class, String.class).getFirst();
|
||||||
|
lastException = assertThrows(Exception.class, () -> bookUseCase.registerBook(toBookInfo(row)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I request the book with isbn {long}")
|
||||||
|
public void iRequestTheBook(long isbn) throws BookNotFoundException {
|
||||||
|
retrievedBook = bookUseCase.getBookByIsbn(isbn);
|
||||||
|
}
|
||||||
|
|
||||||
|
@When("I list all books")
|
||||||
|
public void iListAllBooks() {
|
||||||
|
allBooks = bookUseCase.getAllBooks();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("the book is created")
|
||||||
|
public void theBookIsCreated() {
|
||||||
|
assertNotNull(lastRegisteredIsbn);
|
||||||
|
}
|
||||||
|
|
||||||
|
@And("the catalog now has {int} book(s)")
|
||||||
|
public void theCatalogNowHasNBooks(int expected) {
|
||||||
|
assertEquals(expected, bookRepository.findAll().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("the registration fails with a {string}")
|
||||||
|
public void theRegistrationFailsWith(String exceptionSimpleName) {
|
||||||
|
assertNotNull(lastException);
|
||||||
|
assertEquals(exceptionSimpleName, lastException.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("I receive a book whose title is {string}")
|
||||||
|
public void iReceiveABookWhoseTitleIs(String title) {
|
||||||
|
assertNotNull(retrievedBook);
|
||||||
|
assertEquals(title, retrievedBook.getTitle());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Then("I receive {int} book(s)")
|
||||||
|
public void iReceiveNBooks(int expected) {
|
||||||
|
assertNotNull(allBooks);
|
||||||
|
assertEquals(expected, allBooks.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BookInfo toBookInfo(Map<String, String> row) {
|
||||||
|
return new BookInfo(
|
||||||
|
Long.parseLong(row.get("isbn")),
|
||||||
|
row.get("titre"),
|
||||||
|
row.get("auteur"),
|
||||||
|
row.get("editeur"),
|
||||||
|
LocalDate.parse(row.get("datePublication")),
|
||||||
|
Double.parseDouble(row.get("prix")),
|
||||||
|
Integer.parseInt(row.get("stock")),
|
||||||
|
List.of(Category.valueOf(row.get("categorie"))),
|
||||||
|
"",
|
||||||
|
row.get("langue")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# language: en
|
||||||
|
|
||||||
|
Feature: Manage book catalog
|
||||||
|
|
||||||
|
Scenario: Register a new book in the catalog
|
||||||
|
When I register a new book with the following information:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
Then the book is created
|
||||||
|
And the catalog now has 1 book
|
||||||
|
|
||||||
|
Scenario: Reject duplicate ISBN
|
||||||
|
Given the catalog has the following books:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
When I try to register a new book with the following information:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD copy | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
Then the registration fails with a "BookAlreadyExistsException"
|
||||||
|
|
||||||
|
Scenario: Reject invalid book information
|
||||||
|
When I try to register a new book with the following information:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | | Evans | AW | 2003-08-22 | 0 | -1 | SCIENCE | EN |
|
||||||
|
Then the registration fails with a "NotValidBookException"
|
||||||
|
|
||||||
|
Scenario: Retrieve a book by its ISBN
|
||||||
|
Given the catalog has the following books:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
When I request the book with isbn 9780321125217
|
||||||
|
Then I receive a book whose title is "DDD"
|
||||||
|
|
||||||
|
Scenario: List all books in the catalog
|
||||||
|
Given the catalog has the following books:
|
||||||
|
| isbn | titre | auteur | editeur | datePublication | prix | stock | categorie | langue |
|
||||||
|
| 9780321125217 | DDD | Evans | AW | 2003-08-22 | 54.99 | 10 | SCIENCE | EN |
|
||||||
|
| 9780132350884 | Clean | Martin | PH | 2008-08-01 | 30.00 | 5 | SCIENCE | EN |
|
||||||
|
When I list all books
|
||||||
|
Then I receive 2 books
|
||||||
Reference in New Issue
Block a user