// Backend логика для корзины ST100 Tilda
$(document).ready(function() {
// Настройки
const USER_POINTS = 6000;
const PROMO_PRICE = 490;
const PRODUCT_PRICE = 3000;
const MIN_PRODUCTS_FOR_PROMO = 3;
let userPoints = USER_POINTS;
let originalTildaCheckout = null;
// Инициализация после загрузки Tilda
setTimeout(initPointsSystem, 1000);
function initPointsSystem() {
addPointsBalance();
interceptTildaButtons();
observeCartChanges();
interceptCheckout();
}
function addPointsBalance() {
if ($('#points-balance').length > 0) return;
const pointsHtml = `
Ваш баланс: ${userPoints} баллов Выберите 2 товара для бесплатного получения
`;
if ($('.t706__cartwin-products').length > 0) {
$('.t706__cartwin-products').before(pointsHtml);
} else if ($('.t-cart__content').length > 0) {
$('.t-cart__content').prepend(pointsHtml);
} else if ($('.t-store').length > 0) {
$('.t-store').prepend(pointsHtml);
}
}
function interceptTildaButtons() {
$(document).on('click', '.js-store-prod-btn, .t-btn, .js-product-btn', function(e) {
setTimeout(updateCartCalculation, 500);
});
$(document).on('change', '.t-cart__prod-quantity input, .t706__product-quantity input', function() {
setTimeout(updateCartCalculation, 100);
});
$(document).on('click', '.t-cart__prod-del, .t706__product-del', function() {
setTimeout(updateCartCalculation, 100);
});
}
function updateCartCalculation() {
const cartData = getCartData();
const calculation = calculatePrice(cartData);
updateCartInterface(calculation);
}
function getCartData() {
let items = [];
let totalQuantity = 0;
$('.t-cart__prod-row, .t706__product, .js-cart-item').each(function() {
const $item = $(this);
let quantity = 1;
const $quantityInput = $item.find('input[type="number"], .t-input__quantity input');
if ($quantityInput.length > 0) {
quantity = parseInt($quantityInput.val()) || 1;
}
const name = $item.find('.t-cart__prod-name, .t-name, .js-product-name').text().trim();
const priceText = $item.find('.t-cart__prod-price, .t-price, .js-product-price').text().trim();
let price = PRODUCT_PRICE;
const priceMatch = priceText.match(/(\d+)/);
if (priceMatch) {
price = parseInt(priceMatch[1]);
}
if (name) {
items.push({
name: name,
price: price,
quantity: quantity
});
totalQuantity += quantity;
}
});
return {
items: items,
totalQuantity: totalQuantity,
totalItems: items.length
};
}
function calculatePrice(cartData) {
const { totalQuantity } = cartData;
let finalPrice = 0;
let paymentMethod = 'regular';
let canUsePoints = false;
let canUsePromo = false;
let message = '';
if (totalQuantity === 0) {
return {
finalPrice: 0,
paymentMethod: 'regular',
canUsePoints: false,
canUsePromo: false,
message: 'Корзина пуста',
totalQuantity: 0
};
}
if (totalQuantity === 2 && userPoints >= USER_POINTS) {
canUsePoints = true;
paymentMethod = 'points';
finalPrice = 0;
message = 'Можете получить 2 товара бесплатно за баллы!';
} else if (totalQuantity >= MIN_PRODUCTS_FOR_PROMO) {
canUsePromo = true;
paymentMethod = 'promo';
finalPrice = PROMO_PRICE;
message = `Акция активна! Все ${totalQuantity} товара за ${PROMO_PRICE}₽`;
} else {
paymentMethod = 'regular';
finalPrice = totalQuantity * PRODUCT_PRICE;
if (totalQuantity === 1) {
message = `Добавьте ещё 1 товар для бесплатного получения или ${MIN_PRODUCTS_FOR_PROMO - totalQuantity} для акции ${PROMO_PRICE}₽`;
} else if (totalQuantity === 2 && userPoints < USER_POINTS) {
message = `Недостаточно баллов для бесплатного получения. Добавьте ещё ${MIN_PRODUCTS_FOR_PROMO - totalQuantity} товар для акции ${PROMO_PRICE}₽`;
}
}
return {
finalPrice: finalPrice,
paymentMethod: paymentMethod,
canUsePoints: canUsePoints,
canUsePromo: canUsePromo,
message: message,
totalQuantity: totalQuantity
};
}
function updateCartInterface(calculation) {
const { finalPrice, paymentMethod, message } = calculation;
let $infoBlock = $('#cart-calculation-info');
if ($infoBlock.length === 0) {
const infoHtml = `
`;
if ($('.t-cart__btn, .t706__cartwin-bottom, .js-cart-submit-btn').length > 0) {
$('.t-cart__btn, .t706__cartwin-bottom, .js-cart-submit-btn').before(infoHtml);
$infoBlock = $('#cart-calculation-info');
}
}
if ($infoBlock.length > 0) {
$('#calculation-message').text(message);
if (paymentMethod === 'points') {
$('#final-price-display').html('
БЕСПЛАТНО (за баллы)').css('color', '#28a745');
$infoBlock.css('background', '#d4edda').css('border-color', '#c3e6cb');
} else if (paymentMethod === 'promo') {
$('#final-price-display').html(`
ИТОГО: ${finalPrice}₽ ${calculation.totalQuantity * PRODUCT_PRICE}₽`).css('color', '#dc3545');
$infoBlock.css('background', '#f8d7da').css('border-color', '#f5c6cb');
} else {
$('#final-price-display').html(`
ИТОГО: ${finalPrice}₽`).css('color', '#6c757d');
$infoBlock.css('background', '#f8f9fa').css('border-color', '#dee2e6');
}
}
updateTildaPrice(finalPrice, paymentMethod);
}
function updateTildaPrice(price, method) {
const priceSelectors = [
'.t-cart__total-price .t-cart__total-value',
'.t706__cartwin-totalamount-num',
'.js-cart-total-price',
'.t-cart__subtotal-price',
'.js-total-price'
];
priceSelectors.forEach(selector => {
const $priceElement = $(selector);
if ($priceElement.length > 0) {
if (method === 'points') {
$priceElement.html('
БЕСПЛАТНО');
} else {
$priceElement.text(price + '₽');
}
}
});
}
function interceptCheckout() {
if (window.tcart && window.tcart.checkout && !originalTildaCheckout) {
originalTildaCheckout = window.tcart.checkout;
window.tcart.checkout = function() {
const cartData = getCartData();
const calculation = calculatePrice(cartData);
if (calculation.paymentMethod === 'points') {
processPointsPayment(cartData);
return false;
} else if (calculation.paymentMethod === 'promo') {
processPromoPayment(cartData, calculation);
return false;
} else {
return originalTildaCheckout.apply(this, arguments);
}
};
}
$(document).on('click', '.t-cart__btn, .t706__cartwin-btn, .js-cart-submit-btn', function(e) {
const cartData = getCartData();
const calculation = calculatePrice(cartData);
if (calculation.paymentMethod === 'points' || calculation.paymentMethod === 'promo') {
e.preventDefault();
e.stopPropagation();
if (calculation.paymentMethod === 'points') {
processPointsPayment(cartData);
} else {
processPromoPayment(cartData, calculation);
}
return false;
}
});
}
function processPointsPayment(cartData) {
const productNames = cartData.items.map(item => `${item.name} (${item.quantity} шт.)`).join('\n');
if (confirm(`Подтвердите бесплатное получение товаров:\n\n${productNames}\n\nС вашего баланса будет списано ${USER_POINTS} баллов.`)) {
userPoints = 0;
$('#points-balance').find('strong').text(`Ваш баланс: ${userPoints} баллов`);
sendOrderData('points', cartData, 0);
alert('Поздравляем! Товары заказаны бесплатно.\nСсылки будут отправлены на вашу почту.');
clearCart();
}
}
function processPromoPayment(cartData, calculation) {
const productNames = cartData.items.map(item => `${item.name} (${item.quantity} шт.)`).join('\n');
if (confirm(`Подтвердите заказ по акции:\n\n${productNames}\n\nК оплате: ${PROMO_PRICE}₽`)) {
sendOrderData('promo', cartData, PROMO_PRICE);
alert(`Перенаправляем на оплату ${PROMO_PRICE}₽...`);
if (originalTildaCheckout) {
updateCartForPayment(PROMO_PRICE);
setTimeout(() => {
originalTildaCheckout.call(window.tcart);
}, 100);
}
}
}
function updateCartForPayment(totalPrice) {
$('.t-cart__prod-row, .t706__product').each(function(index) {
const $priceElement = $(this).find('.t-cart__prod-price, .js-product-price');
if (index === 0) {
$priceElement.attr('data-product-price', totalPrice);
} else {
$priceElement.attr('data-product-price', 0);
}
});
}
function sendOrderData(paymentType, cartData, price) {
const orderData = {
paymentType: paymentType,
products: cartData.items,
totalPrice: price,
userPoints: userPoints,
timestamp: new Date().toISOString()
};
console.log('Order data:', orderData);
// Отправка на сервер
/*
$.ajax({
url: '/api/process-order',
method: 'POST',
data: JSON.stringify(orderData),
contentType: 'application/json',
success: function(response) {
console.log('Order processed:', response);
}
});
*/
}
function clearCart() {
if (window.tcart && window.tcart.empty) {
window.tcart.empty();
} else {
$('.t-cart__prod-del, .t706__product-del').click();
}
}
function observeCartChanges() {
const observer = new MutationObserver(function(mutations) {
let shouldUpdate = false;
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' ||
(mutation.type === 'attributes' && mutation.attributeName === 'value')) {
shouldUpdate = true;
}
});
if (shouldUpdate) {
setTimeout(updateCartCalculation, 100);
}
});
const cartSelectors = ['.t-cart', '.t706__cartwin', '.js-store-cart'];
cartSelectors.forEach(selector => {
const element = document.querySelector(selector);
if (element) {
observer.observe(element, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['value']
});
}
});
}
// События Tilda
$(document).on('tcart:item:add', updateCartCalculation);
$(document).on('tcart:item:remove', updateCartCalculation);
$(document).on('tcart:item:update', updateCartCalculation);
});
// Глобальные функции
window.TildaPointsSystem = {
updatePoints: function(points) {
const script = $('script:contains("userPoints")');
if (script.length > 0) {
userPoints = points;
$('#points-balance').find('strong').text(`Ваш баланс: ${userPoints} баллов`);
}
}
};