/* Устанавливает цену в блоке товара при добавлении параметров При добавлении нескольких параметров добавляет обработчик для select и option Выбрав определенный параметр изменяет цену у продукта */ /** * Init products * * @param {string} recId - rec id * @returns {undefined} - exit function */ function t_prod__init(recId) { var rec = document.querySelector('#rec' + recId); if (!rec) return; var productElements = rec.querySelectorAll('.js-product'); Array.prototype.forEach.call(productElements, function (productElement) { if (productElement.querySelector('.js-product-option, .js-product-multioption')) { t_prod__initProduct(productElement); } }); } /** * Init product card * * @param {string} recId - rec id * @param {Node} productElement - product card */ function t_prod__initProduct(productElement, options) { let element = productElement; if (typeof element === 'string') { element = options; } t_prod__initPrice(element); t_prod__addEvents__options(element); t_prod__updatePrice(element, options); } /** * Init price * * @param {Node} productElement - product card */ function t_prod__initPrice(productElement) { let element = productElement; // TODO: jqeury in js if (!(element instanceof Element)) element = element[0]; if (!element) return; var productPrice = element.querySelector('.js-product-price'); if (!productPrice) { element.insertAdjacentHTML('beforeend', '
'); productPrice = element.querySelector('.js-product-price'); } var priceValue = productPrice.textContent; var productDef = productPrice.getAttribute('data-product-price-def'); var productDefStr = productPrice.getAttribute('data-product-price-def-str'); // Базовую цену запоминаем один раз. Пустая строка тоже остаётся: у товара нет своей цены, её даёт опция. // Если прочитать цену из карточки ещё раз, надбавка опции прибавится повторно. if (productDef !== null || productDefStr !== null) return; if (priceValue) { var price = t_prod__cleanPrice(priceValue); productPrice.setAttribute('data-product-price-def', price); productPrice.setAttribute('data-product-price-def-str', priceValue.replace(/"/g, '')); } else { productPrice.setAttribute('data-product-price-def', 0); } } /** * Update the price when changing * * @param {Node} productElement - product card * @returns {undefined} - exit function */ function t_prod__updatePrice(productElement, options) { let element = productElement; // TODO: jqeury in js if (!(element instanceof Element)) element = element[0]; if (!element) return; var productPrice = element.querySelector('.js-product-price'); var productSelects = element.querySelectorAll('.js-product-option-variants'); var totalPrice; var add = 0; if (!productPrice) return; var priceContainer = productPrice.parentNode; const hasContainerClass = priceContainer?.classList.value.split(/\s+/).some(cls => cls.endsWith('__price')); priceContainer = hasContainerClass ? priceContainer : null; var priceWrapper = priceContainer?.parentNode; const hasWrapperClass = priceWrapper?.classList.value.split(/\s+/).some(cls => cls.endsWith('__price-wrapper')); priceWrapper = hasWrapperClass ? priceWrapper : null; var priceValue = productPrice.getAttribute('data-product-price-def'); priceValue = priceValue * 1; var optionPriceEmptyCount = 0; var handlePrice = function (optionPrice) { if (optionPrice) { var price = t_prod__cleanPrice(optionPrice); if (optionPrice.indexOf('+') !== -1) { add += price; } else if (parseFloat(price) !== 0) { priceValue = price; } } else { optionPriceEmptyCount += 1; } }; // Обработка для одиночных опций Array.prototype.forEach.call(productSelects, function (select) { var optionPrice = select.querySelector('option:checked').getAttribute('data-product-variant-price'); handlePrice(optionPrice); }); // Обработка для мультиопций var multioptionCheckedCheckboxes = element.querySelectorAll( '.js-product-multioption input[type="checkbox"]:checked' ); Array.prototype.forEach.call(multioptionCheckedCheckboxes, function (checkbox) { var optionPrice = checkbox.getAttribute('data-product-variant-price'); handlePrice(optionPrice); }); totalPrice = priceValue + add; var priceRange = productPrice.classList.contains('js-store-prod-price-range-val') || productPrice.classList.contains('js-catalog-prod-price-range-val'); if (priceRange) { productPrice.setAttribute('data-product-price-range-val', t_prod__roundPrice(totalPrice)); } else if (totalPrice > 0) { if (priceWrapper && priceWrapper.style.visibility === 'hidden') { priceWrapper.style.visibility = ''; } if (priceContainer && priceContainer.style.display === 'none') { priceContainer.style.display = ''; } var priceHandled = t_prod__showPrice(t_prod__roundPrice(totalPrice), options); var priceUserInput = productPrice.getAttribute('data-product-price-def-str'); var isAllOptionsPriceEmpty = optionPriceEmptyCount === productSelects.length; var isCatalogProduct = element.classList.contains('js-store-product') || element.classList.contains('js-catalog-product'); if (isAllOptionsPriceEmpty && !isCatalogProduct) { var priceHandledUserInput = t_prod__saveUserInputInPrice(totalPrice, priceHandled, priceUserInput); productPrice.innerHTML = priceHandledUserInput; } else { productPrice.innerHTML = priceHandled; } } else { if (priceWrapper && priceWrapper.style.visibility === '') { priceWrapper.style.visibility = 'hidden'; } if (priceContainer && priceContainer.style.display === '') { priceContainer.style.display = 'none'; } productPrice.innerHTML = productPrice.getAttribute('data-product-price-def-str'); } } /** * Функция объединяет пользовательский ввод и правильно сформированную цену. Например: * Пользователь ввёл в input "от 1550". В этом случае, функции t_prod__roundPrice и t_prod__showPrice * вернут 1 550 / 1 550.00 (второй вариант в случае если в настройках указана currency). Данная функция увидит, * что пользователь так же написал слово "от" и смержит эти 2 вариант, в итоге получим "от 1 550.00" * * @param {number} total - подсчитанная итоговая цена * @param {string} handled - обработанная цена (с учётом настроек проекта) * @param {string} userInput - необработанная строка (то, что пользователь ввёл в input) * @returns {string} - объединение обработанной цены с сохранением доп. символов, которые ввёл пользователь */ function t_prod__saveUserInputInPrice(total, handled, userInput) { if (!userInput) return handled; if (userInput.indexOf(handled) !== -1) { return userInput; } const totalStr = total.toString(); if (handled !== userInput) { if (window.tcart && window.tcart['currency_dec'] === '00') { var separator = window.tcart['currency_sep']; var handledWithoutCurrency = handled.replace(separator + '00', ''); if (userInput.indexOf(handledWithoutCurrency) !== -1) { return userInput.replace(handledWithoutCurrency, handled); } if (userInput.indexOf(totalStr) !== -1) { return userInput.replace(totalStr, handled); } } else if (userInput.indexOf(totalStr) !== -1) { return userInput.replace(totalStr, handled); } } return handled; } /** * Add events for select * * @param {Node} productElement - product card */ function t_prod__addEvents__options(productElement) { let element = productElement; // TODO: jqeury in js if (!(element instanceof Element)) element = element[0]; if (!element) return; var productSelects = element.querySelectorAll('.js-product-option-variants'); // Для одиночных опций Array.prototype.forEach.call(productSelects, function (select) { var product = select.closest('.js-product'); select.addEventListener('change', function () { t_prod__updatePrice(product); t_triggerEvent(document.body, 'twishlist_addbtn'); }); }); // Для мультиопций var multioptionCheckboxes = element.querySelectorAll('.js-product-multioption input[type="checkbox"]'); Array.prototype.forEach.call(multioptionCheckboxes, function (checkbox) { var product = checkbox.closest('.js-product'); checkbox.addEventListener('change', function () { t_prod__updatePrice(product); t_triggerEvent(document.body, 'twishlist_addbtn'); }); }); } /** * Clear price from symbols * * @param {string} price - string convert number price * @returns {number} - return price */ function t_prod__cleanPrice(price) { let newPrice = price; if (newPrice) { newPrice = newPrice.toString(); newPrice = newPrice.replace(',', '.').replace(/[^0-9.]/g, ''); newPrice = parseFloat(newPrice).toFixed(2); if (isNaN(newPrice)) newPrice = 0; newPrice = parseFloat(newPrice); newPrice = newPrice * 1; if (newPrice < 0) newPrice = 0; } else { newPrice = 0; } return newPrice; } /** * Number rounding * * @param {number} price - price * @returns {number} - price */ function t_prod__roundPrice(price) { let newPrice = price; if (newPrice) { newPrice = parseFloat(newPrice).toFixed(2); newPrice = parseFloat(newPrice); newPrice = newPrice * 1; if (newPrice < 0) newPrice = 0; } else { newPrice = 0; } return newPrice; } /** * Transform price in string price * * @param {number} price - price * @returns {string} - str price */ function t_prod__showPrice(price, options) { let priceToShow = price; if (!priceToShow) { priceToShow = ''; } else { priceToShow = priceToShow.toString(); if ( (window.tcart && window.tcart['currency_dec'] && window.tcart['currency_dec'] === '00') || (options && options.currencyDecimal && options.currencyDecimal === '00') ) { if (priceToShow.indexOf('.') === -1 && priceToShow.indexOf(',') === -1) { priceToShow = priceToShow + '.00'; } else { var foo = priceToShow.substr(priceToShow.indexOf('.') + 1); if (foo.length === 1) priceToShow = priceToShow + '0'; } } priceToShow = priceToShow.replace(/\B(?=(\d{3})+(?!\d))/g, ' '); if ( (window.tcart && window.tcart['currency_sep'] && window.tcart['currency_sep'] === '.') || (options && options.currencySeparator && options.currencySeparator === '.') ) { priceToShow = priceToShow.replace(',', '.'); } else { priceToShow = priceToShow.replace('.', ','); } } return priceToShow; } // Функция временно продублирована из tilda-scrits для избежания проблем с кэшем function t_triggerEvent(el, eventName) { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); } else if (document.createEventObject) { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; if (el.dispatchEvent) { el.dispatchEvent(event); } else if (el.fireEvent) { el.fireEvent('on' + event.eventType, event); } else if (el[eventName]) { el[eventName](); } else if (el['on' + eventName]) { el['on' + eventName](); } }