Fix | Фикс бага при одновременном изменении кол-ва товаров и удалении товаров из мини-корзины

dev_10_refactoring
parent 6121332038
commit d1e33b17d2
  1. 123
      wp-content/themes/cosmopet/modules/footer/assets/js/footer.js
  2. 47
      wp-content/themes/cosmopet/modules/shop/components/cart/assets/js/cart.js

@ -136,97 +136,6 @@
}); });
}); });
$('body').on('click', '.modal-basket__item .counter__button', function(){
var input = $(this).closest('.counter').find('.counter__input').val()
var price = $(this).closest('.modal-basket-item__control').find('.modal-basket-item__price')
var productID = $(this).data('id')
var pr = $(this).closest('.modal-basket__item').find('.modal-basket__item-before').data('pr')
$(price).html(Number(input) * $(price).data('basecost'))
$(this).closest('.modal-basket__item').data('cost', Number(price.html()))
$('#cart_total').html(wc_cart_summary_upd())
var title = $(this).closest('.cart_item').find('.modal-basket-item__title').html()
if ($(this).hasClass('minus')){
$(this).attr('data-value', Number( $(this).attr('data-value')) - 1)
if(Number($(this).attr('data-value')) == 0){
$(this).closest('.modal-basket__item').find('.modal-basket__item-before').click()
}
dataLayer.push({
"ecommerce": {
"currencyCode": "RUB",
"remove": {
"products": [
{
"id": pr,
"name": title,
"quantity": 1,
}
]
}
}
});
}
else{
var min = $(this).closest('.counter--small').find('.minus')
$(min).attr('data-value', Number($(min).attr('data-value')) + 1)
dataLayer.push({
"ecommerce": {
"currencyCode": "RUB",
"add": {
"products": [
{
"id": pr,
"name": title,
"quantity": 1,
}
]
}
}
});
}
// if ($(this).hasClass('minus') && Number(input) == 1){
// $(this).closest('.modal-basket__item').find('.modal-basket__item-before').click()
// }
var data = {
action: 'get_cartprice',
quantity: input,
product: productID
};
$.ajax({
type: 'post',
url: '/wp-admin/admin-ajax.php',
data: data,
beforeSend: function (response) {
// $thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
// $thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error) {
} else {
// $('#cart_total').html(response)
initCounters()
if(response['cart_count'] > 0){
$('.mini-profile__button--counter').removeClass('disabled').html(response['cart_count'])
}
else{
$('.mini-profile__button--counter').addClass('disabled').html(response['cart_count'])
}
}
},
});
})
// $('body').on('click', '.product-item-overlay__field .counter__button', function(){
// var input = $(this).closest('.counter').find('.counter__input').val()
// var price = $(this).closest('.product-item__form').find('.product-item-overlay__price')
// $(price).html(Number(input) * $(price).data('basecost'))
// })
$('body').on('click', '.modal-basket__item-before', function(){ $('body').on('click', '.modal-basket__item-before', function(){
var key = $(this).data('id') var key = $(this).data('id')
var p_ID = $(this).data('pr'); var p_ID = $(this).data('pr');
@ -723,38 +632,6 @@ selects.forEach(select => {
} }
initSelect() initSelect()
// counter
function initCounters(){
let counters = document.querySelectorAll('.counter');
counters.forEach(e => {
let minus = e.querySelector('.minus'),
plus = e.querySelector('.plus'),
input = e.querySelector('.counter__input');
minus.onclick = function (e) {
e.preventDefault();
let number = input.value;
if (number >= 2){
input.value = Number(number) - 1;
input.setAttribute('value', input.value)
}
}
plus.onclick = function (e) {
e.preventDefault();
let number = input.value;
let max = input.dataset.maxcount
if (number <= max - 1) {
input.value = Number(number) + 1;
input.setAttribute('value', input.value)
}
}
})
}
initCounters()
// counter // counter
// checkbox // checkbox

@ -6,18 +6,40 @@ jQuery(document).ready(function($) {
// }); // });
// Обновление количества через input // Обновление количества через input
$(document).on('change', '.counter__input', function() { $(document).on('change', '.counter__input', function () {
const key = $(this).data('key'); const $input = $(this);
const quantity = $(this).val(); const key = $input.data('key');
const quantity = parseInt($input.val(), 10);
if (quantity > 0) { if (quantity > 0) {
updateCart(key, quantity); updateCart(key, quantity, false);
const $item = $input.closest('.modal-basket-item__control');
const $priceElement = $item.find('.woocommerce-Price-amount');
const currentPriceText = $priceElement.text().replace(/[^\d,]/g, '').replace(',', '.');
const currentTotal = parseFloat(currentPriceText);
// Защита от деления на 0
if (!isNaN(currentTotal) && currentTotal > 0) {
const oldQuantity = parseInt($input.prop('defaultValue'), 10);
const unitPrice = currentTotal / oldQuantity;
const newTotal = unitPrice * quantity;
// Обновить цену
$priceElement.find('bdi').html(
newTotal.toLocaleString('ru-RU', { minimumFractionDigits: 0 }) + '&nbsp;<span class="woocommerce-Price-currencySymbol">₽</span>'
);
// Обновить значение по умолчанию (чтобы расчёт unitPrice был корректен в следующий раз)
$input.prop('defaultValue', quantity);
}
} else { } else {
removeItem(key); removeItem(key);
} }
}); });
// Увеличение количества
$(document).on('click', '.modal__basket .counter__button.plus', function(e) { $(document).on('click', '.modal__basket .counter__button.plus', function(e) {
e.preventDefault(); e.preventDefault();
const key = $(this).data('key'); const key = $(this).data('key');
@ -26,7 +48,7 @@ jQuery(document).ready(function($) {
input.val(quantity).trigger('change'); input.val(quantity).trigger('change');
}); });
// Уменьшение количества // // Уменьшение количества
$(document).on('click', '.modal__basket .counter__button.minus', function(e) { $(document).on('click', '.modal__basket .counter__button.minus', function(e) {
e.preventDefault(); e.preventDefault();
const key = $(this).data('key'); const key = $(this).data('key');
@ -192,7 +214,8 @@ jQuery(document).ready(function($) {
); );
localStorage.setItem(removedItemsStorageKey, JSON.stringify(updatedItems)); localStorage.setItem(removedItemsStorageKey, JSON.stringify(updatedItems));
updateCartFragment(); updateCartFragment(false);
$('[data-key="' + key + '"]').remove()
} }
} }
}); });
@ -294,7 +317,7 @@ jQuery(document).ready(function($) {
}); });
// Функция обновления количества // Функция обновления количества
function updateCart(key, quantity) { function updateCart(key, quantity, update_full = true) {
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '/wp-admin/admin-ajax.php', // Используем стандартный параметр WooCommerce url: '/wp-admin/admin-ajax.php', // Используем стандартный параметр WooCommerce
@ -311,7 +334,7 @@ jQuery(document).ready(function($) {
}, },
success: function(response) { success: function(response) {
if (response.success) { if (response.success) {
updateCartFragment(); updateCartFragment(update_full);
} else { } else {
console.error('Ошибка при обновлении корзины'); console.error('Ошибка при обновлении корзины');
} }
@ -323,7 +346,7 @@ jQuery(document).ready(function($) {
} }
// Обновление фрагментов корзины // Обновление фрагментов корзины
function updateCartFragment() { function updateCartFragment(update_full=true) {
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: woocommerce_params.ajax_url, url: woocommerce_params.ajax_url,
@ -339,7 +362,9 @@ jQuery(document).ready(function($) {
success: function(response) { success: function(response) {
console.log(response); console.log(response);
if (response.success) { if (response.success) {
if (update_full){
$('#modal-basket-content').html(response.data.contents); $('#modal-basket-content').html(response.data.contents);
}
$('.modal-block-price__price').html(response.data.total); $('.modal-block-price__price').html(response.data.total);
$('#modal-basket-footer').html(response.data.cart_bottom) $('#modal-basket-footer').html(response.data.cart_bottom)
$('.mini-profile__button--counter').text(response.data.count); $('.mini-profile__button--counter').text(response.data.count);

Loading…
Cancel
Save