PageSourceSearch

https://pay-me.ru/assets/88bb12e0/cart.js

js pay-me.ru collected 2026-09-30 12:06:33 UTC 14,470 bytes, 301 lines download raw bytes

1/**
2 * Cart.js module for shopfront
3 *
4 * Denis Khomyakov [email protected]
5 */
6
7Number.prototype.format = function(n, x, s, c) {
8    var re = '\\\\d(?=(\\\\d{' + (x || 3) + '})+' + (n > 0 ? '\\\\D' : '$') + ')',
9        num = this.toFixed(Math.max(0, ~~n));
10
11    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
12};
13
14(function($) {
15    $.Cart = {
16
17        init : function(settings){
18            var defaults = {
19                page_content: '.content__container',
20                content : '.cart__content', // селектор главного блока на странице корзины
21                summ : '.checkout__total', // общая сумма
22                add : '.js-add-to-cart', // селектор элемента, при нажатии на который товар будет добавлен в корзину
23                orderattr: '.js-make-order', // селектор элемента, при нажатии на который будет создаваться заказ
24                idattr : 'data-id', // атрибут элемента, содержащий ID товара
25                counta : '.checkout-item__quantity-input', // поле содержащее количество товаров одного наименования в корзине
26                nameattr : 'data-name', // атрибут поля, содержащий ID товара
27                priceattr : 'data-price', // атрибут поля, содержащий цену товаров
28                imageattr : 'data-image', // атрибут поля, содержащий картинку товара
29                del : '.js-checkout-item__remove', // селектор элемента, при нажатии на который 1 наименование товара будет удалено из корзины
30                delattr : 'name', // атрибут элемента, содержащий ID товара
31                topcart : '.cart__block', // селектор ссылки ведущей в корзину
32                type_message : 'flash', // тип сообщения при добавлении товара в корзину
33                time_message : 3000, // время показа сообщения
34                interval : 10000, // интервал времени, через который будет обновляться блок с информацией о количестве товаров в корзине и общей сумме
35                cart_name: 'cart', // назавние корзины в сторэдже
36                storage : 1, // Сторэдж 1 - localstorage; 0 - cookie
37                image_url: 'https://api-storage.pay-me.ru/public/get',
38                user_url: 'https://bo.pay-me.ru/shopfront/order-user'
39            };
40
41            $.extend(defaults, settings);
42            this.settings = defaults;
43
44            this.update(); // обновляем блок
45
46            /*setInterval(function(){
47                $.Cart.update(); // обновляем блок через заданный в параметрах интервал
48            }, this.settings.interval);*/
49
50            $(this.settings.add).on('click', function(){
51                $.Cart.add(this); // добавляем товар в корзину при клике на элемент settings.add, в качестве параметра передаем сам элемент
52            });
53
54            $(document)
55                .on('blur', this.settings.counta, function(){
56                    $.Cart.count(this); // при потере фокуса поля, содержащего количество товаров одного наименования в корзине, передаем информацию на сервер
57                })
58                .on('click',this.settings.del, function(){
59                    $.Cart.del(this); // удаляем наименование товара при нажатии на элемент "удалить"
60                })
61                .on('click', this.settings.orderattr, function(){
62                    $.Cart.order(this);
63                })
64                .on('keypress',this.settings.counta, function (e){
65                    if (e.which == 13){
66                        $.Cart.count(this);
67                        return false;
68                    }
69                })
70                .on('keydown', this.settings.counta, function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110])||/65|67|86|88/.test(e.keyCode)&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()
71                });
72
73            if(typeof Storage !== "undefined")
74            {
75                $.Cart.settings.storage = 1;
76            }
77            else
78            {
79                $.Cart.settings.storage = 0;
80            }
81
82            return this;
83        },
84        add : function(context){
85            var good = {
86                'id':$(context).attr($.Cart.settings.idattr),
87                'name':$(context).attr($.Cart.settings.nameattr),
88                'price':parseInt($(context).attr($.Cart.settings.priceattr)),
89                'image':$(context).attr($.Cart.settings.imageattr),
90                'qty': 1
91            };
92            var cart = $.Cart.getFromStorage($.Cart.settings.cart_name);
93
94            if (cart !== null){
95                var inArr = false;
96                cart.items.forEach(function(item, i){
97                    if (item.id == good.id){
98                        cart.items[i].qty += 1;
99                        cart.total_qty += 1;
100                        cart.total_cost += good.price;
101                        inArr = true;
102                    }
103                });
104                if (!inArr){
105                    cart.total_qty += 1;
106                    cart.total_cost += good.price;
107                    cart.items.push(good);
108                }
109                $.Cart.addToStorage(cart);
110            } else {
111                cart = {};
112                cart.items = [];
113                cart.total_qty = 1;
114                cart.total_cost = good.price;
115                cart.items.push(good);
116                $.Cart.addToStorage(cart);
117            }
118            $.Cart.update();
119
120        },
121        update : function(){
122            var cart = this.getFromStorage();
123            var cart_block = $($.Cart.settings.topcart);
124            var cart_content = $($.Cart.settings.content);
125            var cart_html;
126
127            cart_block.hide();
128            if (cart !== null){
129                cart_block.find('.basket__size').html(cart.total_qty);
130                cart_block.show();
131                cart_html = '<div class ="checkout_step-1"><div class="checkout__table"><div class="checkout-table__header">'+
132                    '<div class="checkout-table__item checkout-table__item_price">Стоимость</div>'+
133                    '<div class="checkout-table__item checkout-table__item_amount">Количество</div>'+
134                    '<div class="checkout-table__item checkout-table__item_total">Итого</div>'+
135                    '</div>';
136
137                cart.items.forEach(function (item,i){
138                    cart_html += '<div class="checkout-table__row">'+
139                        '<a href="javascript:void(0);" class="checkout-item"><img src="'+$.Cart.settings.image_url+'?id='+item.image+'" alt="" class="checkout-item__img">'+
140                            '<div class="checkout-item__title">'+item.name+'</div>'+
141                        '</a><div class="checkout-item__price">'+item.price.format(0,3,' ')+' <small><i class="fa fa-rub"></i></small></div>'+
142                        '<div class="checkout-item__quantity">'+
143                            '<input data-id="'+item.id+'" type="text" value="'+item.qty+'" class="checkout-item__quantity-input" maxlength="5">'+
144                        '</div>'+
145                        '<div class="checkout-item__total">'+(item.qty*item.price).format(0,3,' ')+' <small><i class="fa fa-rub"></i></small></div>'+
146                        '<div data-id="'+item.id+'" class="checkout-item__remove js-checkout-item__remove"></div>'+
147                    '</div>';
148                });
149                cart_html += '</div></div><div class="checkout__footer"></div><div class="checkout__total t-a_r">Всего к оплате: <span>'+cart.total_cost+' <small><i class="fa fa-rub"></i></small></span></div>'+
150                '<div class="checkout__delivery t-a_r">Доставка:<span>бесплатно</span></div>'+
151                '<div class="row checkout_padding">'+
152                    '<div class="col_6 t-a_l">'+
153                    '</div>'+
154                    '<div class="col_6 col-md-offset-6 t-a_r">'+
155                        '<div class="checkout-next-step-wrapper">'+
156                        '<div class="btn btn_next-step js-btn_step1 js-make-order">Оформить заказ</div>'+
157                    '</div></div>'+
158                '</div>';
159                cart_content.html(cart_html);
160            } else {
161                cart_content.html($('<div class="checkout_step-1"><div class="checkout-table__row"><div class="">Вы не добавили товары в корзину</div></div></div>'));
162
163            }
164        },
165        count : function(context) {
166            var item_id = $(context).attr($.Cart.settings.idattr);
167            var new_item_qty = $(context).val();
168            var new_item_price;
169            var cart = $.Cart.getFromStorage();
170
171            if (new_item_qty == 0){
172                $.Cart.del(context);
173                return false;
174            }
175
176            cart.items.forEach( function (item,i) {
177                if (item.id == item_id){
178
179                    var old_item_price = item.price*item.qty;
180                    var old_item_qty = item.qty;
181                    var changed_item_qty;
182                    var changed_item_price;
183                    if (!(new_item_qty == old_item_qty)){
184                        if (old_item_qty > new_item_qty){
185                            changed_item_qty = old_item_qty - new_item_qty;
186                            item.qty -= changed_item_qty;
187                            cart.total_qty -= changed_item_qty;
188                        } else {
189                            changed_item_qty = new_item_qty - old_item_qty;
190                            item.qty += changed_item_qty;
191                            cart.total_qty += changed_item_qty;
192                        }
193                        new_item_price = item.price * item.qty;
194                        if (old_item_price > new_item_price){
195                            changed_item_price = old_item_price - new_item_price;
196                            cart.total_cost -= changed_item_price;
197                        } else {
198                            changed_item_price = new_item_price - old_item_price;
199                            cart.total_cost += changed_item_price;
200                        }
201                    }
202                }
203            });
204            $.Cart.addToStorage(cart);
205            $.Cart.update();
206        },
207        del : function(context) {
208            var item_id = $(context).attr($.Cart.settings.idattr);
209            var cart = $.Cart.getFromStorage();
210            var index = false;
211            var item_cost = 0;
212            var item_qty = 0;
213            var items_count = 0;
214            cart.items.forEach(function(item, i){
215                if (item.id == item_id){
216                    index = i;
217                    item_qty = item.qty;
218                    item_cost = item.price * item.qty;
219                }
220                items_count += 1;
221            });
222
223            if (index !== false) {
224                cart.items.splice(index,1);
225                cart.total_cost = cart.total_cost - item_cost;
226                cart.total_qty = cart.total_qty - item_qty;
227
228                if (cart.total_qty == 0){
229                    $.Cart.deleteFromStorage($.Cart.settings.cart_name);
230                } else {
231                    $.Cart.addToStorage(cart);
232                }
233            }
234            $.Cart.update();
235        },
236        order: function(){
237            $.ajax({
238                method: 'GET',
239                xhrFields: {
240                    withCredentials: true
241                },
242                url: $.Cart.settings.user_url,
243                statusCode: {
244                    404: function() {
245                        var user = null;
246                        $.Cart.checkout(user);
247                    }
248                },
249                success: function (result) {
250                    $.Cart.checkout(result);
251                },
252            });
253        },
254        showMessage : function(message) {
255            // показ сообщения при добавлении товара
256        },
257        getFromStorage: function(){
258            var cart_obj;
259            if ($.Cart.settings.storage){
260                return this._toJSONObject(localStorage.getItem($.Cart.settings.cart_name));
261            } else {
262                cart_obj = Document.cookie.get($.Cart.settings.cart_name);
263            }
264        },
265        addToStorage: function(cart_obj) {
266            if ($.Cart.settings.storage){
267                return localStorage.setItem($.Cart.settings.cart_name,this._toJSONString(cart_obj));
268            } else {
269
270            }
271        },
272        deleteFromStorage: function (cart){
273            if ($.Cart.settings.storage){
274                return localStorage.removeItem(cart);
275            } else {
276
277            }
278        },
279        checkout: function (user) {
280            var csrfToken = $('meta[name="csrf-token"]').attr("content");
281            $.ajax({
282                url: '/order/index',
283                method: 'POST',
284                data: {'_csrf': csrfToken, 'user': user, 'order': $.Cart.getFromStorage()},
285                success: function (result) {
286                    var content = $($.Cart.settings.page_content);
287                    $(content).html(result);
288                }
289            });
290        },
291        _toJSONObject: function( str ) {
292            var obj = JSON.parse( str );
293            return obj;
294        },
295
296        _toJSONString: function( obj ) {
297            var str = JSON.stringify( obj );
298            return str;
299        }
300    }
301})(jQuery);

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.