Jump to content

Выборочная выгрузка в Яндекс.Маркет + фильтр в админке


Recommended Posts

Всем еще раз доброго дня!

 

Нашел на форуме тему с направлением "Выборочная выгрузка в Ya.Market"

 

как я понял автор темы:

   ссылка на тему

   http://www.simplashop.com/article/simpla-2-vyborochnaya-vygruzka-v-yandeksmarket

  

Все работает (ну как мин с Админ части), но вот в комментах на сайте был вопрос "возможность фильтрации в админке по принципу Рекоммендуемые, Акции и т.д.

 

 

api/Products.php
по аналогии

 

$is_featured_filter = '';

 

добавляем 

 

$yandex_filter = ''; 

 

simpla/ProductsAdmin
в 

if($f = $this->request->get('filter', 'string')) 

 

добавляем 

elseif($f == 'yandex')
$filter['yandex'] = 1; 

 


simpla/design/html/products.tpl
<!-- Меню -->
       <!-- Фильтры -->
Добавляем

<li {if $filter=='yandex'}class="selected"{/if}><a href="{url keyword=null brand_id=null category_id=null page=null filter='yandex'}">Yandex</a></li>

 


Все радуемся и пользуемся :)

Link to post
Share on other sites

В api/Products.php уже есть этот фильтр, его надо добавить только в метод count_products - в остальном верно.

Писал для этого случаю другую статью "Фильтрация в админке" - постараюсь на днях (или этих) выходных закончить.

Предполагалось фильтрация

  • по новинкам и яндексу (т.е. новым полям, что объяснялись в других статьях)
  • по товарам со скидкой,
  • товарам без картинок,
  • товарам с нулевым остатком.

Моей целью является не написать подробное руководство, а просто объяснить принципы с какой стороны подойти - развивать проект можно бесконечно и для каждого индивидуально.

Link to post
Share on other sites
  • 8 months later...
if(!empty($filter['featured']))
			$is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
			
		if(!empty($filter['yandex']))
			$is_featured_filter = $this->db->placehold('AND p.yandex=?', intval($filter['yandex']));

Вот такая штука в count_products сосчитает сколько товаров таких.

Link to post
Share on other sites
  • 3 weeks later...

Всем еще раз доброго дня!

 

Нашел на форуме тему с направлением "Выборочная выгрузка в Ya.Market"

 

как я понял автор темы:

   ссылка на тему

   http://www.simplashop.com/article/simpla-2-vyborochnaya-vygruzka-v-yandeksmarket

  

Все работает (ну как мин с Админ части), но вот в комментах на сайте был вопрос "возможность фильтрации в админке по принципу Рекоммендуемые, Акции и т.д.

 

 

api/Products.php

по аналогии

 

$is_featured_filter = '';

 

добавляем 

 

$yandex_filter = ''; 

 

simpla/ProductsAdmin

в 

if($f = $this->request->get('filter', 'string')) 

 

добавляем 

elseif($f == 'yandex')
$filter['yandex'] = 1; 

 

 

simpla/design/html/products.tpl

<!-- Меню -->

       <!-- Фильтры -->

Добавляем

<li {if $filter=='yandex'}class="selected"{/if}><a href="{url keyword=null brand_id=null category_id=null page=null filter='yandex'}">Yandex</a></li>

 

 

Все радуемся и пользуемся :)

Где-то что-то было упущено. Не работает такой метод %(

Link to post
Share on other sites
  • 1 year later...

Коллеги, установила модуль, но получила такую проблему : В админ панели не отображается включен товар или нет, причем все работает. Но после обновления страницы все товары светятся как не отправленные в яндекс маркет, хотя они отправлены. Помогите пожалуйста!!)) 

Edited by Yana
Link to post
Share on other sites

посмотрите внимательно, все ли вы сделали правильно

Если конкретно, у товаров, отправленных в Яндекс, должнен добавляться класс, подобно рекомендуемым.

Или напишите мне в скайп kosjak1976

Как землячке - помогу бесплатно :)

 

Есть еще 1 приятная мелочь - аяксовые кнопочки напротив каждого товара и мы сделаем свои для Yandex.Market. Выше в этом же файле найдем (62 строка)

62
{if $product->featured}featured{/if}

и добавим после него

62
{if $product->to_yandex}yandex{/if}
Link to post
Share on other sites

посмотрите внимательно, все ли вы сделали правильно

Если конкретно, у товаров, отправленных в Яндекс, должнен добавляться класс, подобно рекомендуемым.

Или напишите мне в скайп kosjak1976

Как землячке - помогу бесплатно :)

Буду очень признательна ))) Отправила запрос в скайп 

Link to post
Share on other sites

Вот она моя 62 строка : 
 

<div id="list">
        {foreach $products as $product}
        <div class="{if !$product->visible}invisible{/if} {if $product->featured}featured{/if} {if $product->to_yandex}yandex{/if} row">
            <input type="hidden" name="positions[{$product->id}]" value="{$product->position}">
            <div class="move cell"><div class="move_zone"></div></div>
             <div class="checkbox cell">
                <input type="checkbox" name="check[]" value="{$product->id}"/>                


Вроде бы все правильно (((( Хелп ми  :unsure:
Link to post
Share on other sites

Уже нашла ошибку ) Видимо когда делала не сохранила, 

Не хватало вот этого: 
 

Чтобы Ваше поле to_yandex выводилось в списке товаров надо модифицировать класс товара api/Products.php - после строки (141)

141
p.visible,

добавим поле

142
p.to_yandex,
Link to post
Share on other sites
  • 1 year later...
Вышеописанные способы у меня не работают.
Вот мой рабочий вариант для simpla 2.3.6
 
В api/Products.php
 
public function get_products($filter = array())
	{		
		// По умолчанию
		$page = 1;
		$category_id_filter = '';
		$brand_id_filter = '';
		$product_id_filter = '';
		$features_filter = '';
		$keyword_filter = '';
		$visible_filter = '';
		$is_featured_filter = '';
		$yandex_filter = '';
		$discounted_filter = '';
		$in_stock_filter = '';
		$group_by = '';
		$order = 'p.position DESC';

		if(isset($filter['limit']))
			$limit = max(1, intval($filter['limit']));

		if(isset($filter['page']))
			$page = max(1, intval($filter['page']));

		if(isset($limit) && isset($page))
			$sql_limit = $this->db->placehold(' LIMIT ?, ? ', ($page-1)*$limit, $limit);

		if(!empty($filter['id']))
			$product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']);

		if(!empty($filter['category_id']))
		{
			$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']);
			$group_by = "GROUP BY p.id";
		}

		if(!empty($filter['brand_id']))
			$brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']);

		if(isset($filter['featured']))
			$is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
		
		if(isset($filter['yandex']))
			$yandex_filter = $this->db->placehold('AND p.to_yandex=?', intval($filter['yandex']));

		if(isset($filter['discounted']))
			$discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted']));

		if(isset($filter['in_stock']))
			$in_stock_filter = $this->db->placehold('AND (SELECT count(*)>0 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock']));

		if(isset($filter['visible']))
			$visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible']));

 		if(!empty($filter['sort']))
			switch ($filter['sort'])
			{
				case 'position':
				$order = 'p.position DESC';
				break;
				case 'name':
				$order = 'p.name';
				break;
				case 'created':
				$order = 'p.created DESC';
				break;
				case 'price':
				//$order = 'pv.price IS NULL, pv.price=0, pv.price';
				$order = '(SELECT -pv.price FROM __variants pv WHERE (pv.stock IS NULL OR pv.stock>0) AND p.id = pv.product_id AND pv.position=(SELECT MIN(position) FROM __variants WHERE (stock>0 OR stock IS NULL) AND product_id=p.id LIMIT 1) LIMIT 1) DESC';
				break;
			}

		if(!empty($filter['keyword']))
		{
			$keywords = explode(' ', $filter['keyword']);
			foreach($keywords as $keyword)
			{
				$kw = $this->db->escape(trim($keyword));
				$keyword_filter .= $this->db->placehold("AND (p.name LIKE '%$kw%' OR p.meta_keywords LIKE '%$kw%' OR p.id in (SELECT product_id FROM __variants WHERE sku LIKE '%$kw%'))");
			}
		}

		if(!empty($filter['features']) && !empty($filter['features']))
			foreach($filter['features'] as $feature=>$value)
				$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value);

		if(!empty($filter['min_price']) && !empty($filter['max_price']))
			$prices = $this->db->placehold('AND p.id in(SELECT v.product_id FROM __variants v WHERE v.price >= ? AND v.price <= ? AND v.product_id = p.id)', intval($filter['min_price']), intval($filter['max_price']));
			
		$query = "SELECT  
					p.id,
					p.url,
					p.brand_id,
					p.name,
					p.featured,
                    p.rating,
                    p.votes,
					p.annotation,
					p.body,
					p.position,
					p.created as created,
					p.visible,
					p.to_yandex,					
					p.featured, 
					p.meta_title, 
					p.meta_keywords, 
					p.meta_description,
					p.garanty,
					b.name as brand,
					b.url as brand_url
				FROM __products p		
				$category_id_filter 
				LEFT JOIN __brands b ON p.brand_id = b.id
				WHERE 
					1
					$product_id_filter
					$brand_id_filter
					$features_filter
					$keyword_filter
					$is_featured_filter
					$yandex_filter
					$discounted_filter
					$in_stock_filter
					$visible_filter
					$prices
				$group_by
				ORDER BY $order
					$sql_limit";

		$this->db->query($query);

		return $this->db->results();
	}

	/**
	* Функция возвращает количество товаров
	* Возможные значения фильтра:
	* category_id - id категории или их массив
	* brand_id - id бренда или их массив
	* keyword - ключевое слово для поиска
	* features - фильтр по свойствам товара, массив (id свойства => значение свойства)
	*/
	public function count_products($filter = array())
	{		
		$category_id_filter = '';
		$brand_id_filter = '';
		$product_id_filter = '';
		$keyword_filter = '';
		$visible_filter = '';
		$is_featured_filter = '';
		$yandex_filter = '';
		$in_stock_filter = '';
		$discounted_filter = '';
		$features_filter = '';
		
		if(!empty($filter['category_id']))
			$category_id_filter = $this->db->placehold('INNER JOIN __products_categories pc ON pc.product_id = p.id AND pc.category_id in(?@)', (array)$filter['category_id']);

		if(!empty($filter['brand_id']))
			$brand_id_filter = $this->db->placehold('AND p.brand_id in(?@)', (array)$filter['brand_id']);

		if(!empty($filter['id']))
			$product_id_filter = $this->db->placehold('AND p.id in(?@)', (array)$filter['id']);
		
		if(isset($filter['keyword']))
		{
			$keywords = explode(' ', $filter['keyword']);
			foreach($keywords as $keyword)
				$keyword_filter .= $this->db->placehold('AND (p.name LIKE "%'.$this->db->escape(trim($keyword)).'%" OR p.meta_keywords LIKE "%'.$this->db->escape(trim($keyword)).'%") ');
		}

		if(isset($filter['featured']))
			$is_featured_filter = $this->db->placehold('AND p.featured=?', intval($filter['featured']));
		
		if(isset($filter['yandex']))
			$yandex_filter = $this->db->placehold('AND p.to_yandex=?', intval($filter['yandex']));

		if(isset($filter['in_stock']))
			$in_stock_filter = $this->db->placehold('AND (SELECT count(*)>0 FROM __variants pv WHERE pv.product_id=p.id AND pv.price>0 AND (pv.stock IS NULL OR pv.stock>0) LIMIT 1) = ?', intval($filter['in_stock']));

		if(isset($filter['discounted']))
			$discounted_filter = $this->db->placehold('AND (SELECT 1 FROM __variants pv WHERE pv.product_id=p.id AND pv.compare_price>0 LIMIT 1) = ?', intval($filter['discounted']));

		if(isset($filter['visible']))
			$visible_filter = $this->db->placehold('AND p.visible=?', intval($filter['visible']));
		
		
		if(!empty($filter['features']) && !empty($filter['features']))
			foreach($filter['features'] as $feature=>$value)
				$features_filter .= $this->db->placehold('AND p.id in (SELECT product_id FROM __options WHERE feature_id=? AND value=? ) ', $feature, $value);
		
		if(!empty($filter['min_price']) && !empty($filter['max_price']))
			$prices = $this->db->placehold('AND p.id in(SELECT v.product_id FROM __variants v WHERE v.price >= ? AND v.price <= ? AND v.product_id = p.id)', intval($filter['min_price']), intval($filter['max_price']));
			
		$query = "SELECT count(distinct p.id) as count
				FROM __products AS p
				$category_id_filter
				WHERE 1
					$brand_id_filter
					$product_id_filter
					$keyword_filter
					$is_featured_filter
					$yandex_filter
					$in_stock_filter
					$discounted_filter
					$visible_filter
					$prices
					$features_filter ";

		$this->db->query($query);	
		return $this->db->result('count');
	}

 

Edited by snagovskiy
Link to post
Share on other sites
  • 1 year later...

Всем еще раз доброго дня!

 

Нашел на форуме тему с направлением "Выборочная выгрузка в Ya.Market"

 

как я понял автор темы:

ссылка на тему

http://www.simplashop.com/article/simpla-2-vyborochnaya-vygruzka-v-yandeksmarket

 

Все работает (ну как мин с Админ части), но вот в комментах на сайте был вопрос "возможность фильтрации в админке по принципу Рекоммендуемые, Акции и т.д.

 

 

api/Products.php

по аналогии

 

$is_featured_filter = '';

добавляем

$yandex_filter = '';

simpla/ProductsAdmin

в

if($f = $this->request->get('filter', 'string'))

добавляем

elseif($f == 'yandex')$filter['yandex'] = 1;

 

simpla/design/html/products.tpl

<!-- Меню -->

<!-- Фильтры -->

Добавляем

<li {if $filter=='yandex'}class="selected"{/if}><a href="{url keyword=null brand_id=null category_id=null page=null filter='yandex'}">Yandex</a></li>

 

Все радуемся и пользуемся :)

все описано отлично все сделал с первого раза спасибо!!!

Edited by Tarasbulba
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...