PageSourceSearch

https://inreko.ru/local/templates/inreko/components/bitrix/sale.basket.basket/new2026/script.js

js inreko.ru collected 2026-10-08 13:18:48 UTC 6,781 bytes, 185 lines download raw bytes

1document.addEventListener('DOMContentLoaded', function() {
2    let syncTimeout;
3    let isOrderSuccessful = false;
4
5    // 1. Инициализация итогов при загрузке
6    recalculateTotal();
7
8    /**
9     * СЛЕЖКА ЗА УСПЕХОМ ФОРМЫ
10     */
11    const orderPopup = document.getElementById('order-popup');
12    const overlay = document.querySelector('.overlay');
13    
14    if (orderPopup) {
15        const observer = new MutationObserver(function() {
16            const hasSuccess = orderPopup.querySelector('.form-order__done') || 
17                               orderPopup.innerText.includes('принята') || 
18                               orderPopup.innerText.includes('Спасибо');
19
20            if (hasSuccess) {
21                isOrderSuccessful = true;
22                console.log('Заказ зафиксирован успешно.');
23            }
24        });
25        observer.observe(orderPopup, { childList: true, subtree: true });
26    }
27
28    /**
29     * Глобальные функции для работы с попапом
30     */
31    window.openOrderPopup = function() {
32        if (orderPopup) {
33            orderPopup.classList.add('show');
34            overlay.classList.add('show');
35        }
36    };
37
38    window.closeOrderPopup = function() {
39        if (orderPopup && orderPopup.classList.contains('show')) {
40            orderPopup.classList.remove('show');
41            overlay.classList.remove('show');
42            
43            // Если заказ был успешен, при закрытии попапа чистим корзину
44            if (isOrderSuccessful) {
45                clearBasketAfterOrder();
46            }
47        }
48    };
49
50    /**
51     * Очистка корзины после заказа
52     */
53    async function clearBasketAfterOrder() {
54        const params = new URLSearchParams();
55        params.append('action', 'clear_basket_after_order');
56        params.append('sessid', window.bitrixSessid);
57
58        try {
59            await fetch(window.location.href, {
60                method: 'POST',
61                body: params,
62                headers: { 'X-Requested-With': 'XMLHttpRequest' }
63            });
64            window.location.reload();
65        } catch (e) {
66            window.location.href = window.location.pathname;
67        }
68    }
69
70    /**
71     * Главная функция расчета (визуал)
72     */
73    function recalculateTotal() {
74        let totalSum = 0;
75        let totalWeight = 0;
76        let totalItemsQty = 0; 
77        let orderItemsStrings = [];
78
79        const items = document.querySelectorAll('.basket-new__item');
80        
81        items.forEach(item => {
82            const qtyInput = item.querySelector('.qty-input');
83            const qty = parseInt(qtyInput ? qtyInput.value : 0) || 0;
84            const price = parseFloat(item.getAttribute('data-price')) || 0;
85            const weight = parseFloat(item.getAttribute('data-weight')) || 0;
86            
87            const itemSum = qty * price;
88            
89            const priceDisplay = item.querySelector('.basket-new__item-price span') || item.querySelector('.basket-new__item-price');
90            if (priceDisplay) {
91                priceDisplay.innerText = itemSum.toLocaleString() + ' ₽';
92            }
93
94            totalSum += itemSum;
95            totalWeight += qty * weight;
96            totalItemsQty += qty;
97
98            const name = item.querySelector('.basket-new__item-title')?.innerText.trim() || '';
99            const art = item.querySelector('.basket-new__item-article span')?.innerText.trim() || '—';
100            
101            if (qty > 0) {
102                orderItemsStrings.push(`${name} (Арт: ${art}) — ${qty} шт.`);
103            }
104        });
105
106        if (typeof window.updateCartCounter === 'function') {
107            window.updateCartCounter(totalItemsQty);
108        }
109
110        const totalPriceEl = document.getElementById('total-price-val');
111        const sumBefore = document.getElementById('total-sum-before');
112        const totalWeightEl = document.getElementById('total-weight-val');
113        const totalCountWrapper = document.querySelector('.basket-new__total-row span:first-child');
114
115        if (totalCountWrapper) {
116            const word = getNoun(totalItemsQty, 'товар', 'товара', 'товаров');
117            totalCountWrapper.innerHTML = `<span>${totalItemsQty}</span> ${word}`;
118        }
119
120        if(totalPriceEl) totalPriceEl.innerText = totalSum.toLocaleStr
120ing() + ' ₽';
121        if(sumBefore) sumBefore.innerText = totalSum.toLocaleString() + ' ₽';
122        if(totalWeightEl) {
123            totalWeightEl.innerText = (totalWeight / 1000).toFixed(3).replace('.', ',') + ' кг';
124        }
125
126        const hiddenField = document.getElementById('productPopupId');
127        if (hiddenField) hiddenField.value = orderItemsStrings.join('\n');
128    }
129
130    /**
131     * Изменение количества (Глобальная)
132     */
133    window.changeQty = function(id, delta) {
134        const itemRow = document.querySelector(`.basket-new__item[data-id="${id}"]`);
135        if (!itemRow) return;
136
137        const input = itemRow.querySelector('.qty-input');
138        const productId = itemRow.getAttribute('data-product-id'); 
139        let newQty = (parseInt(input.value) || 1) + delta;
140
141        if (newQty < 1) return;
142        input.value = newQty;
143
144        recalculateTotal();
145
146        clearTimeout(syncTimeout);
147        syncTimeout = setTimeout(() => {
148            const params = new URLSearchParams();
149            params.append('id', productId);
150            params.append('count', newQty);
151            params.append('action', 'update');
152
153            fetch('/ajax/add_to_cart.php', {
154                method: 'POST',
155                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
156                body: params
157            })
158            .then(res => res.json())
159            .then(data => {
160                if (!data.success) console.error('Ошибка бэкенда:', data.error);
161            })
162            .catch(err => console.error('Ошибка сети:', err));
163        }, 500);
164    };
165
166    function getNoun(n, one, two, five) {
167        n = Math.abs(n) % 100;
168        let n1 = n % 10;
169        if (n > 10 && n < 20) return five;
170        if (n1 > 1 && n1 < 5) return two;
171        if (n1 == 1) return one;
172        return five;
173    }
174
175    window.deleteItem = function(id) {
176        if (confirm('Удалить товар из корзины?')) {
177            window.location.href = window.location.pathname + '?basketAction=delete&id=' + id;
178        }
179    };
180    
181    // Закрытие по клику на фон
182    if (overlay) {
183        overlay.addEventListener('click', window.closeOrderPopup);
184    }
185});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.