Исправлен конфликт ID между товарами и комплектами в корзине, использован составной ключ type-id
This commit is contained in:
@@ -12,7 +12,7 @@ console.log(` - Товаров: ${productsCount}, Комплектов: ${kitsC
|
||||
console.log('Позиции:', ITEMS);
|
||||
|
||||
let currentCategoryId = null;
|
||||
const cart = new Map(); // productId -> {id, name, price, qty}
|
||||
const cart = new Map(); // "type-id" -> {id, name, price, qty, type}
|
||||
|
||||
function formatMoney(v) {
|
||||
return (Number(v)).toFixed(2);
|
||||
@@ -146,12 +146,13 @@ function renderProducts() {
|
||||
}
|
||||
|
||||
function addToCart(item) {
|
||||
const isNew = !cart.has(item.id);
|
||||
const cartKey = `${item.type}-${item.id}`; // Уникальный ключ: "product-1" или "kit-1"
|
||||
const isNew = !cart.has(cartKey);
|
||||
|
||||
if (isNew) {
|
||||
cart.set(item.id, { id: item.id, name: item.name, price: Number(item.price), qty: 1, type: item.type });
|
||||
cart.set(cartKey, { id: item.id, name: item.name, price: Number(item.price), qty: 1, type: item.type });
|
||||
} else {
|
||||
cart.get(item.id).qty += 1;
|
||||
cart.get(cartKey).qty += 1;
|
||||
}
|
||||
|
||||
renderCart();
|
||||
@@ -160,7 +161,7 @@ function addToCart(item) {
|
||||
setTimeout(() => {
|
||||
const qtyInputs = document.querySelectorAll('.qty-input');
|
||||
const cartItems = Array.from(cart.keys());
|
||||
const itemIndex = cartItems.indexOf(item.id);
|
||||
const itemIndex = cartItems.indexOf(cartKey);
|
||||
|
||||
if (itemIndex !== -1 && qtyInputs[itemIndex]) {
|
||||
qtyInputs[itemIndex].focus();
|
||||
@@ -188,7 +189,7 @@ function renderCart() {
|
||||
return;
|
||||
}
|
||||
|
||||
cart.forEach(item => {
|
||||
cart.forEach((item, cartKey) => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'cart-item mb-2';
|
||||
|
||||
@@ -214,9 +215,9 @@ function renderCart() {
|
||||
qtyInput.onchange = (e) => {
|
||||
const newQty = parseInt(e.target.value) || 1;
|
||||
if (newQty <= 0) {
|
||||
removeFromCart(item.id);
|
||||
removeFromCart(cartKey);
|
||||
} else {
|
||||
cart.get(item.id).qty = newQty;
|
||||
cart.get(cartKey).qty = newQty;
|
||||
renderCart();
|
||||
}
|
||||
};
|
||||
@@ -230,7 +231,7 @@ function renderCart() {
|
||||
const deleteBtn = document.createElement('button');
|
||||
deleteBtn.className = 'btn btn-sm btn-link text-danger p-0';
|
||||
deleteBtn.innerHTML = '<i class="bi bi-x"></i>';
|
||||
deleteBtn.onclick = () => removeFromCart(item.id);
|
||||
deleteBtn.onclick = () => removeFromCart(cartKey);
|
||||
|
||||
row.appendChild(namePrice);
|
||||
row.appendChild(multiplySign);
|
||||
@@ -246,8 +247,8 @@ function renderCart() {
|
||||
document.getElementById('cartTotal').textContent = formatMoney(total);
|
||||
}
|
||||
|
||||
function removeFromCart(id) {
|
||||
cart.delete(id);
|
||||
function removeFromCart(cartKey) {
|
||||
cart.delete(cartKey);
|
||||
renderCart();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user