Files
ludikevent_crm/assets/tools/FlowAddToCart.js
Serreau Jovann 900b55c07b ```
 feat(ReserverController): Gère les options de produits au panier et en session.

Ajoute la gestion des options de produits lors de l'ajout au panier et dans la session de réservation. Inclut des corrections pour les options orphelines.
```
2026-02-04 11:58:07 +01:00

88 lines
3.2 KiB
JavaScript

export class FlowAddToCart extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.btn = this.querySelector('button');
if (!this.btn) return;
this.productId = this.getAttribute('product-id');
this.btn.addEventListener('click', (e) => {
e.preventDefault();
this.addToCart();
});
}
async addToCart() {
// 1. Check Dates
const dates = JSON.parse(localStorage.getItem('reservation_dates') || '{}');
if (!dates.start || !dates.end) {
// Open Date Picker if no dates
document.dispatchEvent(new CustomEvent('open-date-picker'));
return;
}
// 2. Loading State
const originalContent = this.btn.innerHTML;
this.btn.disabled = true;
this.btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full"></span>';
try {
// 3. Check Availability
const response = await fetch('/produit/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: this.productId,
start: dates.start,
end: dates.end
})
});
if (!response.ok) throw new Error('Network error');
const data = await response.json();
if (data.dispo) {
// 4. Add to Cart
const list = JSON.parse(localStorage.getItem('pl_list') || '[]');
// --- Save Options ---
const selectedOptions = Array.from(document.querySelectorAll('.product-option-checkbox:checked'))
.map(cb => cb.value);
const allOptions = JSON.parse(localStorage.getItem('pl_options') || '{}'); console.log(selectedOptions);
if (selectedOptions.length > 0) {
allOptions[this.productId] = selectedOptions;
} else {
delete allOptions[this.productId];
}
localStorage.setItem('pl_options', JSON.stringify(allOptions));
// --------------------
if (!list.includes(this.productId)) {
list.push(this.productId);
localStorage.setItem('pl_list', JSON.stringify(list));
window.dispatchEvent(new CustomEvent('cart:updated'));
}
// Open Cart
const cart = document.querySelector('[is="flow-reserve"]');
if (cart) cart.open();
} else {
// 5. Not Available
alert("Ce produit n'est pas disponible pour les dates sélectionnées.");
}
} catch (error) {
console.error(error);
alert("Une erreur est survenue.");
} finally {
this.btn.disabled = false;
this.btn.innerHTML = originalContent;
}
}
}