OC v3.х Как поправить скрипт счетчика добавления товара в закладки Unishop?

alexein66

Разрушитель (V)
Сообщения
191
Симпатии
83
Баллы
2 270
Поставил модификатор, который делает возможным добавления товара в закладки без регистрации, но счетчик после обновления страницы сбрасывается на 0. Если нажимаю на кнопку удалить из избранного то товар удаляется только после перезагрузки страницы.
Код:
<modification>
    <name>likeDev - wishlist without login</name>
    <code>likedev_wishlist_without_login</code>
    <version>1.2.3</version>
    <author>Seriusis</author>
    <link>https://likeDev.pro</link>

    <file path="catalog/controller/account/wishlist.php">

        <operation>
            <search><![CDATA['remove'     => $this->url->link('account/wishlist', 'remove=' . $product_info['product_id'])]]></search>
            <add position="replace"><![CDATA['remove'     => $this->customer->isLogged() ? $this->url->link('account/wishlist', 'remove=' . $product_info['product_id']) : $this->url->link('account/wishlist', 'remove_cookie_wishlist=' . $product_info['product_id'])]]></add>
        </operation>


        <operation>
            <search><![CDATA[
      if (!$this->customer->isLogged()) {]]></search>
            <add position="replace" offset="4"><![CDATA[]]></add>
        </operation>
        <operation>
            <search><![CDATA[
                if (isset($this->request->get['remove'])) {]]></search>
            <add position="before"><![CDATA[

               //remove product from wishlist by guest
            if (isset($this->request->get['remove_cookie_wishlist'])) {

            $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
            $wishlist = array_unique($wishlist);
            foreach ($wishlist as $k => $value){
                if($value == $this->request->get['remove_cookie_wishlist']){
                    unset($wishlist[$k]);
                }
            }
                setcookie('cookieWishlist', json_encode($wishlist), time()+3600*24*365,'/');

                $this->response->redirect($this->url->link('account/wishlist'));
            }
            /*end remove product from wishlist by guest*/



            ]]></add>
        </operation>
        <operation>
            <search><![CDATA[$results = $this->model_account_wishlist->getWishlist();]]></search>
            <add position="replace"><![CDATA[
            if ($this->customer->isLogged()) {
                $results = $this->model_account_wishlist->getWishlist();
                }else{
                 $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
                 $wishlist = array_unique($wishlist);
                    $results = [];
                    foreach ($wishlist as $value){
                        $results[]['product_id'] = $value;
                    }
            }
            ]]></add>
        </operation>
        <operation>
            <search><![CDATA[$this->session->data['wishlist'][] = $this->request->post['product_id'];]]></search>
            <add position="after"><![CDATA[
                 /*add product in wishlist by guest*/
                $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
                $wishlist = array_unique($wishlist);
                $wishlist_total = count($wishlist);
                  if(!in_array($this->request->post['product_id'], $wishlist)){
                    $this->load->model('catalog/product');
                    $product_info = $this->model_catalog_product->getProduct($this->request->post['product_id']);
                    if($product_info){
                     $wishlist[] = $this->request->post['product_id'];
                        $wishlist_total += 1;
                     }
                }

                 setcookie('cookieWishlist', json_encode($wishlist), time()+3600*24*365, '/');

                $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
                $wishlist = array_unique($wishlist);
                /*end add product in wishlist by guest*/
            ]]></add>
        </operation>
        <operation>
            <search><![CDATA[$json['total'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));]]></search>
            <add position="replace"><![CDATA[
            $json['total'] = sprintf($this->language->get('text_wishlist'), $wishlist_total);
            ]]></add>
        </operation>
        <operation>
            <search><![CDATA[$json['success'] = sprintf($this->language->get('text_login'), $this->url->link('account/login', '', true), $this->url->link('account/register', '', true), $this->url->link('product/product', 'product_id=' . (int)$this->request->post['product_id']), $product_info['name'], $this->url->link('account/wishlist'));]]></search>
            <add position="replace"><![CDATA[$json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . (int)$this->request->post['product_id']), $product_info['name'], $this->url->link('account/wishlist'));]]></add>
        </operation>
        <operation><!--oc2.1-->
            <search><![CDATA[$json['success'] = sprintf($this->language->get('text_login'), $this->url->link('account/login', '', 'SSL'), $this->url->link('account/register', '', 'SSL'), $this->url->link('product/product', 'product_id=' . (int)$this->request->post['product_id']), $product_info['name'], $this->url->link('account/wishlist'));]]></search>
            <add position="replace"><![CDATA[$json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . (int)$this->request->post['product_id']), $product_info['name'], $this->url->link('account/wishlist'));]]></add>
        </operation>
    </file>
    <file path="catalog/controller/common/header.php">
        <operation>
        <search><![CDATA[$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));]]></search>
        <add position="replace"><![CDATA[
      $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
      $wishlist = array_unique($wishlist);
        $data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), count($wishlist));
        ]]></add>
        </operation>
    </file>
    
    <!--fix wishlist saving after login-->
    <file path="catalog/controller/account/login.php">
          <operation>
            <search index="0"><![CDATA[$this->load->model('account/customer');]]></search>
            <add position="after"><![CDATA[
             $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
            $wishlist = array_unique($wishlist);
                  if ($wishlist) {
                    $this->load->model('account/wishlist');
                    $this->load->model('catalog/product');

                    foreach ($wishlist as $id) {
                        $product_info = $this->model_catalog_product->getProduct($id);
                        if ($product_info) {
                            $this->model_account_wishlist->addWishlist($id);
                        }
                    }

                    setcookie('cookieWishlist', '', time()-3600*24*365,'/');
                }
            ]]></add>
        </operation>
    </file>
      <file path="catalog/controller/account/register.php">
          <operation>
            <search index="0"><![CDATA[if ($this->customer->isLogged()) {]]></search>
            <add position="after"><![CDATA[
            $wishlist = isset($_COOKIE['cookieWishlist']) ? json_decode($_COOKIE['cookieWishlist'],1) : [];
            $wishlist = array_unique($wishlist);
                if ($wishlist) {
                    $this->load->model('account/wishlist');
                    $this->load->model('catalog/product');
    
                    foreach ($wishlist as $id) {
                        $product_info = $this->model_catalog_product->getProduct($id);
                        if ($product_info) {
                            $this->model_account_wishlist->addWishlist($id);
                        }
                    }

                    setcookie('cookieWishlist', '', time()-3600*24*365,'/');
                }
            
            ]]></add>
        </operation>
    </file>
    
</modification>

Код:
var wishlist = {
    'add': function(product_id) {
        $.ajax({
            url: $('base').attr('href')+'index.php?route=account/wishlist/add',
            type: 'post',
            data: 'product_id=' + product_id,
            dataType: 'json',
            success: function(json) {
                if (json['redirect']) {
                    window.location = json['redirect'];
                }

                if (json['success']) {
                    if(json['success'].indexOf('account/login') !== -1) {
                        uniFlyAlert('warning', json['success']);
                    } else {
                        uniFlyAlert('success', json['success']);
                    }

                    let wishlist_total = (json['success'].indexOf('account/login') == -1) ? json['total'].replace(/\s+/g, '').match(/(\d+)/g) : 0;

                    wishlist.uniWishlistUpd(wishlist_total);
                }
            }
        });
    },
    'remove': function(product_id) {
        $.ajax({
            url: 'index.php?route=extension/module/uni_new_data/wishlistRemove',
            type: 'post',
            data: 'product_id='+product_id,
            dataType: 'json',
            success: function(json) {
                if (json['success']) {
                    uniFlyAlert('warning', json['success']);

                    wishlist.uniWishlistUpd(json['total']);

                    $('.product-thumb__wishlist, .product-page__wishlist-btn').each(function() {
                        let pid = Number($(this).attr('onclick').replace(/\D+/g,''));

                        if(product_id == pid) {
                            $(this).attr('onclick', $(this).attr('onclick').replace('wishlist.remove', 'wishlist.add')).attr('title', uniJsVars.wishlist_btn.text).removeClass('active').find('span').text(uniJsVars.wishlist_btn.text);
                        }
                    });
                }
            }
        });
    },
    'uniWishlistUpd': function(total){
        $('.fly-block__wishlist-total, .fly-menu__wishlist-total, .top-menu__wishlist-total, .header-wishlist__total-items').text(total);

        typeof(uniDelPageCache) === 'function' && uniDelPageCache();

        $.get('index.php?route=account/wishlist', (data) => {
            $('.top-menu__wishlist').data('products', $(data).find('.top-menu__wishlist').data('products'));
        });
    }
}

Пробовал менять в скрипте строку
JavaScript:
let wishlist_total = (json['success'].indexOf('account/login') == -1) ? json['total'].replace(/\s+/g, '').match(/(\d+)/g) : 0;

на

JavaScript:
let wishlist_total = json['total'].replace(/\s+/g, '').match(/(\d+)/g);

Счетчик также сбрасывается на 0 после перезагрузки страницы
 
Если добавить в закладки на одной странице, и не обновить ее же, а открыть другую, которую до этого не открывал - тоже будет 0?
 
Какая версия? 2? Поставил два шаблона на 3, delux сохраняет закладки даже после выхода с сайта. unishop2 только для зарегистрированых.
 
Последнее редактирование:
Назад
Верх