Compare commits
4 Commits
65b9eed6dc
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 7192efcfd9 | |||
| 677cb6249a | |||
| 24849c6414 | |||
| d7dfec49fd |
@@ -1,11 +1,17 @@
|
||||
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 [promoValid, setPromoValid] = useState(true);
|
||||
const [estimate, setEstimate] = useState(null);
|
||||
const [estimating, setEstimating] = useState(false);
|
||||
const [estimateError, setEstimateError] = useState(null);
|
||||
const [message, setMessage] = useState(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
@@ -17,13 +23,66 @@ export default function Orders() {
|
||||
function handleLineChange(index, field, value) {
|
||||
setLines((prev) => prev.map((line, i) => (i === index ? { ...line, [field]: value } : line)));
|
||||
}
|
||||
|
||||
function addLine() {
|
||||
setLines((prev) => [...prev, { bookId: '', quantity: 1 }]);
|
||||
}
|
||||
|
||||
function removeLine(index) {
|
||||
setLines((prev) => prev.filter((_, i) => i !== index));
|
||||
}
|
||||
|
||||
function validatePromo(code) {
|
||||
if (!code) return true;
|
||||
return /^PROMO\d{1,2}$/.test(code);
|
||||
}
|
||||
|
||||
function handlePromoChange(e) {
|
||||
const code = e.target.value;
|
||||
setPromoCode(code);
|
||||
setPromoValid(validatePromo(code));
|
||||
}
|
||||
|
||||
async function handleEstimate() {
|
||||
setEstimating(true);
|
||||
setEstimate(null);
|
||||
setEstimateError(null);
|
||||
try {
|
||||
const ids = lines.map((l) => Number(l.bookId)).filter((n) => !isNaN(n) && n > 0);
|
||||
if (ids.length === 0) {
|
||||
setEstimateError('Aucun ISBN valide.');
|
||||
return;
|
||||
}
|
||||
const unique = [...new Set(ids)];
|
||||
const responses = await Promise.all(unique.map((id) => getBookById(id).then((r) => r.data)));
|
||||
const priceMap = new Map();
|
||||
unique.forEach((id, idx) => priceMap.set(id, responses[idx].prix ?? responses[idx].price ?? 0));
|
||||
|
||||
let total = 0;
|
||||
for (const l of lines) {
|
||||
const id = Number(l.bookId);
|
||||
const qty = Number(l.quantity) || 0;
|
||||
total += (priceMap.get(id) || 0) * qty;
|
||||
}
|
||||
|
||||
let discounted = total;
|
||||
if (promoCode) {
|
||||
const m = promoCode.match(/^PROMO(\d{1,2})$/);
|
||||
if (m) {
|
||||
const pct = Math.max(0, Math.min(100, Number(m[1])));
|
||||
discounted = total * (1 - pct / 100);
|
||||
}
|
||||
}
|
||||
|
||||
setEstimate({ total, discounted });
|
||||
} catch (err) {
|
||||
setEstimateError("Erreur lors de l'estimation.");
|
||||
console.error(err);
|
||||
} finally {
|
||||
setEstimating(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setSubmitting(true);
|
||||
@@ -37,10 +96,11 @@ export default function Orders() {
|
||||
bookId: Number(line.bookId),
|
||||
quantity: Number(line.quantity),
|
||||
})),
|
||||
...(promoCode ? { promoCode } : {}),
|
||||
};
|
||||
|
||||
createOrder(payload)
|
||||
.then((response) => setMessage('Commande créée'))
|
||||
.then(() => setMessage('Commande créée avec succès !'))
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
setMessage(error.response?.data?.message || 'Erreur lors de la commande.');
|
||||
@@ -58,10 +118,10 @@ export default function Orders() {
|
||||
|
||||
<h2>Livres</h2>
|
||||
{lines.map((line, index) => (
|
||||
<div key={index}>
|
||||
<div key={index} style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.5rem' }}>
|
||||
<input type="number" placeholder="ISBN du livre" value={line.bookId}
|
||||
onChange={(e) => handleLineChange(index, 'bookId', e.target.value)} required />
|
||||
<input type="number" placeholder="Quantité" value={line.quantity}
|
||||
<input type="number" placeholder="Quantité" min="1" value={line.quantity}
|
||||
onChange={(e) => handleLineChange(index, 'quantity', e.target.value)} required />
|
||||
{lines.length > 1 && (
|
||||
<button type="button" onClick={() => removeLine(index)}>Retirer</button>
|
||||
@@ -77,15 +137,35 @@ export default function Orders() {
|
||||
<input name="country" placeholder="Pays" value={address.country} onChange={handleAddressChange} required />
|
||||
|
||||
<h2>Paiement</h2>
|
||||
<label>Code promo (optionnel)
|
||||
<input value={promoCode} onChange={handlePromoChange} placeholder="ex: PROMO10" />
|
||||
</label>
|
||||
{!promoValid && <p style={{ color: 'red' }}>Format invalide (ex: PROMO10)</p>}
|
||||
|
||||
<select value={paymentMethod} onChange={(e) => setPaymentMethod(e.target.value)}>
|
||||
<option value="CREDIT_CARD">Carte bancaire</option>
|
||||
</select>
|
||||
|
||||
<button type="submit" disabled={submitting}>
|
||||
<div>
|
||||
<button type="button" onClick={handleEstimate} disabled={estimating}>
|
||||
{estimating ? 'Estimation…' : 'Estimer le total'}
|
||||
</button>
|
||||
{estimateError && <p style={{ color: 'red' }}>{estimateError}</p>}
|
||||
{estimate && (
|
||||
<div>
|
||||
<p>Total estimé : {estimate.total.toFixed(2)} €</p>
|
||||
{estimate.total !== estimate.discounted && (
|
||||
<p>Après promo : <strong>{estimate.discounted.toFixed(2)} €</strong></p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button type="submit" disabled={submitting || !promoValid}>
|
||||
{submitting ? 'Envoi…' : 'Valider la commande'}
|
||||
</button>
|
||||
</form>
|
||||
{message && <p>{message}</p>}
|
||||
{message && <p style={{ color: message.includes('succès') ? 'green' : 'red' }}>{message}</p>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user