Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e8ac8f0c54 |
@@ -12,6 +12,7 @@ import Login from './pages/Login';
|
||||
import Reservations from './pages/Reservations';
|
||||
import Returns from './pages/Returns';
|
||||
import Subscription from './pages/Subscription';
|
||||
import Loans from './pages/Loans';
|
||||
import { useAuth } from './context/AuthContext';
|
||||
|
||||
function RequireAuth({ children }) {
|
||||
@@ -41,6 +42,7 @@ export default function App() {
|
||||
<Route path="customers" element={<RequireAdmin><Customers /></RequireAdmin>} />
|
||||
<Route path="returns" element={<RequireAdmin><Returns /></RequireAdmin>} />
|
||||
<Route path="subscription" element={<RequireAuth><Subscription /></RequireAuth>} />
|
||||
<Route path="loans" element={<RequireAuth><Loans /></RequireAuth>} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
|
||||
@@ -21,6 +21,7 @@ export default function Navbar() {
|
||||
{user && <li><Link to="/orders">Commandes</Link></li>}
|
||||
{user?.role === 'user' && <li><Link to="/reservations">Mes réservations</Link></li>}
|
||||
{user?.role === 'user' && <li><Link to="/subscription">Mon abonnement</Link></li>}
|
||||
{user?.role === 'user' && <li><Link to="/loans">Mes prêts</Link></li>}
|
||||
{user && <li><Link to="/profile">Mon compte</Link></li>}
|
||||
{user?.role === 'admin' && <li><Link to="/customers">Clients</Link></li>}
|
||||
{user?.role === 'admin' && <li><Link to="/returns">Retours</Link></li>}
|
||||
|
||||
@@ -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, borrowerPhone, dueDate) {
|
||||
const loan = {
|
||||
loanId: crypto.randomUUID(),
|
||||
bookId: book.isbn,
|
||||
bookTitle: book.title,
|
||||
bookAuthor: book.author,
|
||||
borrowerPhone,
|
||||
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);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { ReservationProvider } from './context/ReservationContext';
|
||||
import { ReviewProvider } from './context/ReviewContext';
|
||||
import { ReturnProvider } from './context/ReturnContext';
|
||||
import { SubscriptionProvider } from './context/SubscriptionContext';
|
||||
import { LoanProvider } from './context/LoanContext';
|
||||
import App from './App';
|
||||
import './styles/global.css';
|
||||
|
||||
@@ -18,7 +19,9 @@ root.render(
|
||||
<ReviewProvider>
|
||||
<ReturnProvider>
|
||||
<SubscriptionProvider>
|
||||
<App />
|
||||
<LoanProvider>
|
||||
<App />
|
||||
</LoanProvider>
|
||||
</SubscriptionProvider>
|
||||
</ReturnProvider>
|
||||
</ReviewProvider>
|
||||
|
||||
@@ -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 />
|
||||
Prêté à : {l.borrowerPhone}
|
||||
<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 />
|
||||
Prêté à : {l.borrowerPhone}
|
||||
<br />
|
||||
<small>Rendu ✓</small>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { createOrder } from '../api/orders';
|
||||
import { getBookById } from '../api/books';
|
||||
|
||||
export default function Orders() {
|
||||
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);
|
||||
|
||||
@@ -23,10 +21,6 @@ export default function Orders() {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -43,7 +37,6 @@ export default function Orders() {
|
||||
bookId: Number(line.bookId),
|
||||
quantity: Number(line.quantity),
|
||||
})),
|
||||
...(promoCode ? { promoCode } : {}),
|
||||
};
|
||||
|
||||
createOrder(payload)
|
||||
@@ -70,51 +63,6 @@ export default function Orders() {
|
||||
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>
|
||||
)}
|
||||
@@ -129,27 +77,10 @@ export default function Orders() {
|
||||
<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>
|
||||
|
||||
@@ -1,8 +1,32 @@
|
||||
import { useState } from 'react';
|
||||
import { useReservations } from '../context/ReservationContext';
|
||||
import { useLoans } from '../context/LoanContext';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
export default function Reservations() {
|
||||
const { reservations, cancelReservation } = useReservations();
|
||||
const { addLoan } = useLoans();
|
||||
const [loanForms, setLoanForms] = useState({});
|
||||
const [loanStatuses, setLoanStatuses] = useState({});
|
||||
|
||||
function handleLoanChange(reservationId, field, value) {
|
||||
setLoanForms(prev => ({
|
||||
...prev,
|
||||
[reservationId]: { ...prev[reservationId], [field]: value }
|
||||
}));
|
||||
}
|
||||
|
||||
function handleLoan(e, reservation) {
|
||||
e.preventDefault();
|
||||
const form = loanForms[reservation.reservationId] || {};
|
||||
addLoan(
|
||||
{ isbn: reservation.bookId, title: reservation.bookTitle, author: reservation.bookAuthor },
|
||||
form.borrowerPhone,
|
||||
form.dueDate
|
||||
);
|
||||
setLoanStatuses(prev => ({ ...prev, [reservation.reservationId]: 'Prêt enregistré avec succès !' }));
|
||||
setLoanForms(prev => ({ ...prev, [reservation.reservationId]: {} }));
|
||||
}
|
||||
|
||||
if (reservations.length === 0) {
|
||||
return (
|
||||
@@ -29,6 +53,36 @@ export default function Reservations() {
|
||||
Statut : {r.status}
|
||||
<br />
|
||||
<button onClick={() => cancelReservation(r.reservationId)}>Annuler</button>
|
||||
|
||||
<details>
|
||||
<summary>Prêter ce livre à un autre lecteur</summary>
|
||||
<form onSubmit={e => handleLoan(e, r)}>
|
||||
<label>
|
||||
Téléphone de l'emprunteur :
|
||||
<input
|
||||
type="tel"
|
||||
value={loanForms[r.reservationId]?.borrowerPhone || ''}
|
||||
onChange={e => handleLoanChange(r.reservationId, 'borrowerPhone', e.target.value)}
|
||||
placeholder="0612345678"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Date de retour prévue :
|
||||
<input
|
||||
type="date"
|
||||
value={loanForms[r.reservationId]?.dueDate || ''}
|
||||
onChange={e => handleLoanChange(r.reservationId, 'dueDate', e.target.value)}
|
||||
min={new Date().toISOString().split('T')[0]}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit">Prêter</button>
|
||||
</form>
|
||||
{loanStatuses[r.reservationId] && (
|
||||
<p style={{ color: 'green' }}>{loanStatuses[r.reservationId]}</p>
|
||||
)}
|
||||
</details>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
Reference in New Issue
Block a user