You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
424 lines
18 KiB
424 lines
18 KiB
jQuery(document).ready(function($) {
|
|
// Открытие/закрытие модалки
|
|
// $(document).on('click', '.cart-contents, .continue-shopping, .modal__close', function(e) {
|
|
// e.preventDefault();
|
|
// $('#modal-basket').toggleClass('active');
|
|
// });
|
|
|
|
// Обновление количества через input
|
|
$(document).on('change', '.counter__input', function () {
|
|
const $input = $(this);
|
|
const key = $input.data('key');
|
|
const quantity = parseInt($input.val(), 10);
|
|
|
|
if (quantity > 0) {
|
|
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;
|
|
|
|
// Получаем текущий символ валюты из разметки
|
|
const currencySymbol = $priceElement.find('.woocommerce-Price-currencySymbol').text().trim();
|
|
|
|
// Формируем новую цену с тем же символом
|
|
$priceElement.find('bdi').html(
|
|
newTotal.toLocaleString('ru-RU', { minimumFractionDigits: 0 }) +
|
|
' <span class="woocommerce-Price-currencySymbol">' + currencySymbol + '</span>'
|
|
);
|
|
|
|
// Обновить значение по умолчанию (чтобы расчёт unitPrice был корректен в следующий раз)
|
|
$input.prop('defaultValue', quantity);
|
|
}
|
|
} else {
|
|
removeItem(key);
|
|
}
|
|
});
|
|
|
|
|
|
$(document).on('click', '.modal__basket .counter__button.plus', function(e) {
|
|
e.preventDefault();
|
|
const key = $(this).data('key');
|
|
const input = $(this).siblings('.counter__input');
|
|
const quantity = parseInt(input.val()) + 1;
|
|
input.val(quantity).trigger('change');
|
|
});
|
|
|
|
// // Уменьшение количества
|
|
$(document).on('click', '.modal__basket .counter__button.minus', function(e) {
|
|
e.preventDefault();
|
|
const key = $(this).data('key');
|
|
const input = $(this).siblings('.counter__input');
|
|
let quantity = parseInt(input.val()) - 1;
|
|
|
|
if (quantity <= 0) {
|
|
removeItem(key); // Вызываем удаление, если количество становится 0
|
|
} else {
|
|
input.val(quantity).trigger('change'); // Обновляем количество, если больше 0
|
|
}
|
|
});
|
|
|
|
$(document).on('click', '.remove-item', function() {
|
|
const key = $(this).data('key');
|
|
removeItem(key);
|
|
});
|
|
|
|
// Удаление товара
|
|
function formatMoney(amount) {
|
|
if (typeof woocommerce_params !== 'undefined' && woocommerce_params.currency_format) {
|
|
const format = woocommerce_params.currency_format;
|
|
return format
|
|
.replace('%1$s', woocommerce_params.currency_symbol)
|
|
.replace('%2$s', parseFloat(amount).toFixed(2));
|
|
}
|
|
return woocommerce_params.currency_symbol + parseFloat(amount).toFixed(2);
|
|
}
|
|
|
|
// Хранилище временно удалённых товаров
|
|
const removedItemsStorageKey = 'woocommerce_removed_items';
|
|
|
|
function restoreRemovedItems() {
|
|
const removedItems = JSON.parse(localStorage.getItem(removedItemsStorageKey)) || [];
|
|
|
|
if (removedItems.length === 0) return;
|
|
|
|
$('#modal-basket').addClass('loading');
|
|
|
|
// Создаем копию массива для работы
|
|
let itemsToRemove = [...removedItems];
|
|
|
|
function processNextItem() {
|
|
if (itemsToRemove.length === 0) {
|
|
// Все элементы обработаны
|
|
localStorage.removeItem(removedItemsStorageKey);
|
|
updateCartFragment();
|
|
$('#modal-basket').removeClass('loading');
|
|
return;
|
|
}
|
|
|
|
const element = itemsToRemove.shift(); // Берем первый элемент
|
|
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: woocommerce_params.ajax_url,
|
|
data: {
|
|
action: 'remove_cart_item',
|
|
cart_item_key: element.key
|
|
},
|
|
success: function(response) {
|
|
if (response.success) {
|
|
// Обновляем localStorage, удаляя только что обработанный элемент
|
|
const currentItems = JSON.parse(localStorage.getItem(removedItemsStorageKey)) || [];
|
|
const updatedItems = currentItems.filter(item => item.key !== element.key);
|
|
localStorage.setItem(removedItemsStorageKey, JSON.stringify(updatedItems));
|
|
}
|
|
// Обрабатываем следующий элемент
|
|
processNextItem();
|
|
},
|
|
error: function() {
|
|
// Продолжаем даже при ошибке
|
|
processNextItem();
|
|
}
|
|
});
|
|
}
|
|
|
|
// Начинаем обработку
|
|
processNextItem();
|
|
}
|
|
|
|
// Инициализация при загрузке
|
|
restoreRemovedItems();
|
|
|
|
// Функция удаления товара с возможностью восстановления
|
|
function removeItem(key) {
|
|
const $item = $(`[data-key="${key}"]`);
|
|
const productId = $item.data('product_id');
|
|
const variationId = $item.data('variation_id') || 0;
|
|
const quantity = parseInt($item.find('.counter__input').val());
|
|
|
|
|
|
$('#modal-basket').addClass('loading');
|
|
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: woocommerce_params.ajax_url,
|
|
data: {
|
|
action: 'remove_cart_item',
|
|
cart_item_key: key
|
|
},
|
|
complete: function() {
|
|
$('#modal-basket').removeClass('loading');
|
|
},
|
|
success: function(response) {
|
|
if (response.success) {
|
|
// Удаляем из временного хранилища
|
|
const removedItems = JSON.parse(localStorage.getItem(removedItemsStorageKey)) || [];
|
|
const updatedItems = removedItems.filter(item =>
|
|
!(item.product_id === productId && item.variation_id === variationId)
|
|
);
|
|
localStorage.setItem(removedItemsStorageKey, JSON.stringify(updatedItems));
|
|
|
|
updateCartFragment();
|
|
// $('[data-key="' + key + '"]').remove()
|
|
}
|
|
}
|
|
});
|
|
|
|
}
|
|
|
|
|
|
// Восстановление товара
|
|
function restoreItem(key, productId, variationId, quantity) {
|
|
$('#modal-basket').addClass('loading');
|
|
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: woocommerce_params.ajax_url,
|
|
data: {
|
|
action: 'restore_cart_item',
|
|
product_id: productId,
|
|
variation_id: variationId,
|
|
quantity: quantity
|
|
},
|
|
complete: function() {
|
|
$('#modal-basket').removeClass('loading');
|
|
},
|
|
success: function(response) {
|
|
if (response.success) {
|
|
// Удаляем из временного хранилища
|
|
const removedItems = JSON.parse(localStorage.getItem(removedItemsStorageKey)) || [];
|
|
const updatedItems = removedItems.filter(item =>
|
|
!(item.product_id === productId && item.variation_id === variationId)
|
|
);
|
|
localStorage.setItem(removedItemsStorageKey, JSON.stringify(updatedItems));
|
|
|
|
// Показываем кнопку Proceed to checkout
|
|
$('.proceed-to-checkout').css('display', '');
|
|
|
|
updateCartFragment();
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// --- Работа с cookie ---
|
|
function setCookie(name, value, days) {
|
|
let expires = '';
|
|
if (days) {
|
|
const date = new Date();
|
|
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
|
|
expires = '; expires=' + date.toUTCString();
|
|
}
|
|
document.cookie = name + '=' + (value || '') + expires + '; path=/';
|
|
}
|
|
function getCookie(name) {
|
|
const nameEQ = name + '=';
|
|
const ca = document.cookie.split(';');
|
|
for(let i=0;i < ca.length;i++) {
|
|
let c = ca[i];
|
|
while (c.charAt(0)==' ') c = c.substring(1,c.length);
|
|
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
|
|
}
|
|
return null;
|
|
}
|
|
// --- Конец работы с cookie ---
|
|
|
|
// Открытие корзины при первом добавлении товара
|
|
function openBasketOnFirstAdd() {
|
|
if (!getCookie('basket_popup_shown')) {
|
|
console.log('[openBasketOnFirstAdd] Срабатывает открытие корзины');
|
|
// Выбираем только модалку, в которой находится корзина
|
|
var $basket = $('#modal-basket');
|
|
var $modal = $basket.closest('.modal');
|
|
var $aside = $modal.find('.modal__aside');
|
|
var device = window.screen.width;
|
|
|
|
// Сброс только внутри этой модалки
|
|
var $items = $modal.find('.modal__item');
|
|
console.log('[openBasketOnFirstAdd] modal:', $modal.get(), 'modal__item:', $items.get());
|
|
$items.removeClass('active').attr('style', '');
|
|
$modal.addClass('active').show();
|
|
$basket.addClass('active').css({opacity: 1, filter: 'blur(0px)'});
|
|
console.log('[openBasketOnFirstAdd] basket:', $basket.get());
|
|
var width = $basket[0] ? $basket[0].clientWidth : 600;
|
|
setTimeout(function() {
|
|
if (device <= 720) {
|
|
$aside.css('width', device + 'px');
|
|
console.log('[openBasketOnFirstAdd] aside width:', device + 'px');
|
|
} else {
|
|
$aside.css('width', width + 'px');
|
|
console.log('[openBasketOnFirstAdd] aside width:', width + 'px');
|
|
}
|
|
}, 10);
|
|
setCookie('basket_popup_shown', '1', 30);
|
|
} else {
|
|
console.log('[openBasketOnFirstAdd] Куки уже установлены, попап не открывается');
|
|
}
|
|
}
|
|
|
|
// Обновление корзины при добавлении товара
|
|
$(document.body).on('added_to_cart', function() {
|
|
updateCartFragment();
|
|
openBasketOnFirstAdd();
|
|
});
|
|
|
|
// Функция обновления количества
|
|
function updateCart(key, quantity, update_full = true) {
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: '/wp-admin/admin-ajax.php', // Используем стандартный параметр WooCommerce
|
|
data: {
|
|
action: 'update_cart_quantity',
|
|
cart_item_key: key,
|
|
quantity: quantity
|
|
},
|
|
beforeSend: function() {
|
|
$('#modal-basket').addClass('loading');
|
|
},
|
|
complete: function() {
|
|
$('#modal-basket').removeClass('loading');
|
|
},
|
|
success: function(response) {
|
|
if (response.success) {
|
|
updateCartFragment(update_full);
|
|
} else {
|
|
console.error('Ошибка при обновлении корзины');
|
|
}
|
|
},
|
|
error: function(xhr, status, error) {
|
|
console.error('AJAX ошибка:', error);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Обновление фрагментов корзины
|
|
function updateCartFragment(update_full=true) {
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: woocommerce_params.ajax_url,
|
|
data: {
|
|
action: 'get_cart_fragment'
|
|
},
|
|
beforeSend: function() {
|
|
$('#modal-basket').addClass('loading');
|
|
},
|
|
complete: function(response) {
|
|
$('#modal-basket').removeClass('loading');
|
|
console.log(response)
|
|
},
|
|
success: function(response) {
|
|
console.log(response);
|
|
if (response.success) {
|
|
if (update_full){
|
|
$('#modal-basket-content').html(response.data.contents);
|
|
}
|
|
$('.modal-block-price__price').html(response.data.total);
|
|
$('#modal-basket-footer').html(response.data.cart_bottom)
|
|
$('.mini-profile__button--counter').text(response.data.count);
|
|
if (response.data.count > 0) {
|
|
$('.mini-profile__button--counter').removeClass('disabled');
|
|
} else {
|
|
$('.mini-profile__button--counter').addClass('disabled');
|
|
}
|
|
}
|
|
},
|
|
error: function(xhr, status, error) {
|
|
console.error('AJAX error:', error);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Добавляем спиннер на кнопку 'Добавить в корзину' в корзине
|
|
$('body').on('click', '.add_to_cart_button', function() {
|
|
var btn = $(this);
|
|
if (!btn.hasClass('loading')) {
|
|
btn.addClass('loading');
|
|
btn.data('original-text', btn.html());
|
|
btn.css('position', 'relative');
|
|
btn.html('<span class="spinner" style="width:20px;height:20px;display:inline-block;"><svg width="20" height="20" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-dasharray="31.415, 31.415" transform="rotate(72.3246 25 25)"><animateTransform attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.7s" repeatCount="indefinite"/></circle></svg></span>');
|
|
}
|
|
});
|
|
|
|
// Убираем спиннер после завершения ajax WooCommerce
|
|
$(document.body).on('added_to_cart', function(e, fragments, cart_hash, $button) {
|
|
if ($button && $button.length) {
|
|
$button.removeClass('loading');
|
|
if ($button.data('original-text')) {
|
|
$button.html($button.data('original-text'));
|
|
$button.removeData('original-text');
|
|
}
|
|
}
|
|
});
|
|
|
|
$('.detail form.cart').on('submit', function(e) {
|
|
e.preventDefault();
|
|
|
|
var $form = $(this);
|
|
product_id = $form.find('button[name=add-to-cart]').val(),
|
|
quantity = $form.find('input.qty').val() || 1;
|
|
console.log(product_id);
|
|
$.ajax({
|
|
url: wc_add_to_cart_params.ajax_url,
|
|
type: 'POST',
|
|
data: {
|
|
action: 'woocommerce_ajax_add_to_cart',
|
|
product_id: product_id,
|
|
quantity: quantity,
|
|
},
|
|
success: function(response) {
|
|
if (response.error && response.product_url) {
|
|
window.location = response.product_url;
|
|
return;
|
|
}
|
|
|
|
updateCartFragment();
|
|
openBasketOnFirstAdd();
|
|
},
|
|
error: function(xhr) {
|
|
console.log('AJAX Error:', xhr.responseText);
|
|
alert('Ошибка добавления товара.');
|
|
}
|
|
});
|
|
});
|
|
});
|
|
|
|
|
|
jQuery(function($){
|
|
$('form.cart').on('submit', function(e){
|
|
e.preventDefault();
|
|
|
|
var $form = $(this);
|
|
var $button = $form.find('button[type="submit"]');
|
|
|
|
var product_id = $button.val();
|
|
var quantity = $form.find('input.qty').val() || 1;
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: wc_add_to_cart_params.ajax_url,
|
|
data: {
|
|
action: 'woocommerce_ajax_add_to_cart',
|
|
product_id: product_id,
|
|
quantity: quantity,
|
|
},
|
|
beforeSend: function() {
|
|
$button.addClass('loading');
|
|
},
|
|
success: function(response) {
|
|
if (response.error && response.product_url) {
|
|
window.location = response.product_url;
|
|
return;
|
|
}
|
|
|
|
$(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $button]);
|
|
$button.removeClass('loading');
|
|
}
|
|
});
|
|
});
|
|
});
|
|
|