diff --git a/my-library/src/pages/Orders.jsx b/my-library/src/pages/Orders.jsx index 1a428c7..425ab9d 100644 --- a/my-library/src/pages/Orders.jsx +++ b/my-library/src/pages/Orders.jsx @@ -1,5 +1,6 @@ import { useState } from 'react'; import { createOrder } from '../api/orders'; +import { getBookById } from '../api/books'; export default function Orders() { const [customerId, setCustomerId] = useState(''); @@ -22,6 +23,10 @@ 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)); } @@ -65,6 +70,51 @@ export default function Orders() { onChange={(e) => handleLineChange(index, 'bookId', e.target.value)} required /> 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 && ( )} @@ -80,12 +130,26 @@ export default function Orders() {