Your IP : 18.224.61.190


Current Path : /home/bitrix/ext_www/rk_shared_core/local/modules/webprofy.offersgroup/lib/
Upload File :
Current File : /home/bitrix/ext_www/rk_shared_core/local/modules/webprofy.offersgroup/lib/propertiesmain.php

<?php
/**
 * Created by PhpStorm.
 * User: Alya
 * Date: 04.06.2016
 * Time: 20:16
 */

namespace Webprofy\Offersgroup;

use Bitrix\Highloadblock\HighloadBlockTable;
use Bitrix\Iblock\ElementTable;
use Bitrix\Main\Entity\Query;
use Bitrix\Main\Loader;

/**
 * Class productsList
 * @package Webprofy\Offersgroup
 * Класс для списка товаров
 */
class PropertiesMain
{

    public static $priceID = 1;

    /**
     * Выборка товаров из инфоблока
     * @return array
     * @throws \Bitrix\Main\ArgumentException
     * @throws \Bitrix\Main\LoaderException
     */
    public static function getProducts()
    {
        $productsData = RelationMain::getProductsInfo();
        $productIblockID = $productsData['RELATION_BITRIX_ID'];
        if (!$productIblockID) {
            return false;
        }

        Loader::includeModule('iblock');

        $arProducts = array();

        $arResult = ElementTable::getList(
            array(
                'filter' => array(
                    'IBLOCK_ID' => $productIblockID,
                    'ACTIVE' => 'Y'
                ),
                'select' => array(
                    'ID',
                    'NAME'
                ),
                'order' => array(
                    'NAME' => 'ASC'
                )
            )
        )->fetchAll();

        if (!empty($arResult)) {
            foreach ($arResult as $item) {
                $arProducts[$item['ID']] = $item['NAME'];
            }
        }

        return $arProducts;
    }

    /**
     * @param $filter
     * @param $hlID
     * @param $getXML_ID
     * @return array
     * @throws \Bitrix\Main\LoaderException
     * Выборка элементов из Хайлоада
     */
    public static function getHLData($filter, $hlID, $getXML_ID = false)
    {
        if (!is_array($filter) || empty($filter)) {
            return;
        }

        Loader::IncludeModule('highloadblock');
        $highLoadData = array();
        $rsData = HighloadBlockTable::getById($hlID);
        if ($arData = $rsData->fetch()) {
            $Entity = HighloadBlockTable::compileEntity($arData);
            // Создадим объект - запрос
            $Query = new Query($Entity);
            // Зададим параметры запроса
            $Query->setSelect(Array(
                'ID',
                'UF_NAME',
                'UF_XML_ID'
            ));
            // Установим фильтр
            $Query->setFilter(array(
                'ID' => $filter
            ));
            // Выполним запрос
            $result = $Query->exec();
            // Получаем результат
            while ($res = $result->fetch()) {
                $highLoadData[$res['ID']] = $getXML_ID ? $res['UF_XML_ID'] : $res['UF_NAME'];
            }
        }

        return $highLoadData;
    }

    /**
     * @param $groupID
     * @return string
     * @throws \Bitrix\Main\ArgumentException
     * @throws \Exception
     */
    public static function deletePropertyByGroup($groupID)
    {

        $arProperty = PropertiesTable::getList(array(
            'filter' => array(
                'GROUP_ID' => $groupID
            ),
            'select' => array(
                'ID'
            )
        ))->fetchAll();

        $count = 0;
        if (!empty($arProperty)) {
            foreach ($arProperty as $item) {
                if (PropertiesTable::delete($item['ID'])->isSuccess()) {
                    $count++;
                }
            }
        }

        return $count;
    }

    /**
     * @param $groupID
     * @param $arDeleted
     * @return string
     */
    public static function deletePropertyByGroupAndValue($groupID, $arDeleted)
    {
        $arRelation = RelationMain::getAllRelationGroupByCode();
        $count = 0;
        foreach ($arDeleted as $key => $item) {
            $arRes = PropertiesTable::getList(array(
                'filter' => array(
                    'RELATION_ID' => $arRelation[$key],
                    'VALUE_ID' => $item,
                    'GROUP_ID' => $groupID,
                ),
                'select' => array(
                    'ID'
                )
            ));

            while ($res = $arRes->fetch()) {
                $arDeletedID[] = $res['ID'];
                if (PropertiesTable::delete($res['ID'])->isSuccess()) {
                    $count++;
                }
            }
        }

        return $count;
    }

    /**
     * @param $groupID
     * @param $arDeleted
     * @return bool|int
     */
    public static function deletePropertyByGroupAndProduct($groupID, $arDeleted)
    {
        $count = 0;
        $arRes = PropertiesTable::getList(array(
            'filter' => array(
                'VALUE_XML_ID' => 'product',
                'VALUE_ID' => $arDeleted,
                'GROUP_ID' => $groupID,
            ),
            'select' => array(
                'ID'
            )
        ));

        while ($res = $arRes->fetch()) {
            $arDeletedID[] = $res['ID'];
            if (PropertiesTable::delete($res['ID'])->isSuccess()) {
                $count++;
            }

        }

        return ($count > 0) ? $count : false;
    }

    /**
     * @param $mode
     * @param $groupID
     * @param $arDeletedProperties
     * @param $generateForExists
     * @return bool|string
     * @throws \Bitrix\Main\LoaderException
     */
    public static function switchOffersModeBeforeAction($mode, $groupID, $arDeletedProperties = false, $generateForExists = false)
    {
        $count = 0;
        if ($mode == 'skip_offers') {
            return false;
        }

        $arProducts = self::getProductsByGroup($groupID);
		$arProducts = array_flip($arProducts);

		while ($arOffers = self::searchOffer($groupID, $arProducts)) {
			$count += self::switchOffersMode($mode, $arOffers, $groupID);
		}
        return $count;
    }

    /**
     * @param $groupID
     * @return array
     * @throws \Bitrix\Main\ArgumentException
     */
    public static function getProductsByGroup($groupID)
    {
        $arProducts = array();
        $arResult = PropertiesTable::getList(
            array(
                'filter' => array(
                    'GROUP_ID' => $groupID,
                    'VALUE_XML_ID' => 'product'
                ),
                'select' => array(
                    'ID',
                    'VALUE_ID'
                )
            )
        )->fetchAll();

        if (!empty($arResult)) {
            foreach ($arResult as $item) {
                $arProducts[$item['ID']] = $item['VALUE_ID'];
            }
        }
        return $arProducts;
    }

    /**
     * @param $arProducts
     * @return array|void
     * @throws \Bitrix\Main\LoaderException
     */
    public static function searchOffersByFilter($arProducts)
    {
        Loader::includeModule('iblock');
        Loader::includeModule('catalog');

        $arProductsInfo = RelationMain::getProductsInfo();
        $productIblockID = $arProductsInfo['RELATION_BITRIX_ID'];

        //Получить ID каталога и id свойств
        $arCatalog = \CCatalog::GetByID($productIblockID);
        if (!$arCatalog) {
            return;
        }

        $offersIblockID = $arCatalog['OFFERS_IBLOCK_ID']; // ID предложений

        $filter = [];
        $arTempDataID = [];
        $combinations = TempTable::getData();
        if(empty($combinations)){
            return false;
        }

        foreach ($combinations as $combination) {
            $filter[md5($combination['DATA'])] = $combination['DATA'];
            $arTempDataID[] = $combination['ID'];
        }

        $filterKeys = array_keys($filter);

        foreach ($arProducts as $product) {
            //Сформируем фильтр для поиска торговых предложений, в которых указан данный товар, и совпадает код комбинации
            $arSearchFilter = [];
            $arSearchFilter['PROPERTY_COMBINATION_CODE'] = $filterKeys;
            $arSearchFilter['PROPERTY_CML2_LINK'] = $product;
            $arSearchFilter['IBLOCK_ID'] = $offersIblockID;
            $arExistOffer = \CIBlockElement::GetList(array(), $arSearchFilter, false, false,
                array('ID', 'CATALOG_GROUP_' . self::$priceID, 'ACTIVE', 'PROPERTY_COMBINATION_CODE'));

            //Торговые преждложения найдены,
            while ($offer = $arExistOffer->Fetch()) {
                $result[] = $offer;
            }
        }

        if (!empty($arTempDataID)) {
            TempTable::delTempData($arTempDataID);
        }

        return $result;
    }

    /**
     * @param $mode
     * @param $arOffers
     * @return string
     */
    public static function switchOffersMode($mode, $arOffers)
    {
        $count = 0;

        switch ($mode) {
            case 'skip_offers':
                break;

            case 'delete_offers':
                foreach ($arOffers as $offer) {
                    $res = self::delete_offers($offer['ID']);
                    if ($res) {
                        $count++;
                    }
                }
                break;

            case 'deactivate_offers':
                foreach ($arOffers as $offer) {
                    $res = self::deactivate_offers($offer['ID']);
                    if ($res) {
                        $count++;
                    }
                }
                break;

            case 'activate_offers':
                foreach ($arOffers as $offer) {
                    $res = self::activate_offers($offer['ID']);
                    if ($res) {
                        $count++;
                    }
                }
                break;

            default:
                break;
        }
        return $count;
    }

    /**
     * @param $offersID
     * @return bool
     */
    public static function delete_offers($offersID)
    {
        return \CIBlockElement::Delete($offersID);
    }

    /**
     * @param $offersID
     * @return bool
     * @throws \Bitrix\Main\LoaderException
     */
    public static function deactivate_offers($offersID)
    {
        Loader::includeModule('iblock');

        $obElement = new \CIBlockElement;
        $arFields = Array(
            "ACTIVE" => "N"
        );
        return $obElement->Update($offersID, $arFields);
    }

    /**
     * @param $offersID
     * @return bool
     * @throws \Bitrix\Main\LoaderException
     */
    public static function activateOffers($offersID)
    {
        Loader::includeModule('iblock');

        $obElement = new \CIBlockElement;
        $arFields = Array(
            "ACTIVE" => "Y"
        );
        return $obElement->Update($offersID, $arFields);
    }

    public static function combinationForDeletedProps($groupID, $arDeletedProperties)
    {
        $arProperty = OffersGroupMain::getPropertiesID($groupID, true);

        if ($arDeletedProperties && is_array($arDeletedProperties)) {
            foreach ($arDeletedProperties as $referenceKey => $arDeletedProperty) {
                //создадим новый массив из старого
                $arNewProperty = $arProperty;
                //Поменяем ключи и значения
                $arDeletedProperty = array_flip($arDeletedProperty);
                //Заполним xml_value для удаленных свойств
                foreach ($arDeletedProperty as $propertyKey => &$item) {
                    $item = $arNewProperty[$referenceKey][$propertyKey];
                }

                //Создадим набор значений для поиска комбинаций
                $arNewProperty[$referenceKey] = $arDeletedProperty;

                $generator = new Combination();
                $arPropertyFormat = $generator->sort($arNewProperty);
                $generator->generate($arPropertyFormat);
            }
        }
    }

    /**
     * @param $mode
     * @param $groupID
     * @param $arProducts
     * @return bool|string
     */
    public static function switchProductsModeBeforeAction($mode, $groupID, $arProducts)
    {
        Loader::includeModule('iblock');

        if ($mode == 'skip_offers') {
            return false;
        }

        $count = 0;
        while ($arOffers = self::searchOffer($groupID, $arProducts)) {
            $count += self::switchOffersMode($mode, $arOffers, $groupID);
        }

        return $count;
    }

	public static function searchOffer($groupID, $arProducts, $offersIblockID = false)
	{
		Loader::includeModule('iblock');
		$res = array();
		$arSearchFilter['PROPERTY_COMBINATION_CODE'] = $groupID;
		$arSearchFilter['PROPERTY_CML2_LINK'] = $arProducts;
		if($offersIblockID){
			$arSearchFilter['IBLOCK_ID'] = $offersIblockID;
		}
		$arExistOffer = \CIBlockElement::GetList(array(), $arSearchFilter, false, false,
			array('ID', 'CATALOG_GROUP_' . self::$priceID, 'PROPERTY_COMBINATION_CODE', 'PROPERTY_CML2_LINK'));

		while ($offer = $arExistOffer->Fetch()) {
			$res[$offer['PROPERTY_CML2_LINK_VALUE']][] = $offer;
		}
		return $res;
    }


    /**
     * @param $offer
     * @param $arFields
     * @param $price
     * @return array|void
     * @throws \Bitrix\Main\LoaderException
     */
    public static function updateOffers($offer, $arFields, $price)
    {
		$obElement = new \CIBlockElement;
		$element = $obElement->Update($offer['ID'], $arFields);
		if(intval($offer['CATALOG_PRICE_1']) !== $price){
			self::setPrice($offer['ID'], $price,
				$offer['CATALOG_CURRENCY_1']);
		}
		return $element;
    }

	public static function addOffer($arFields, $price)
	{
		$obElement = new \CIBlockElement();
		$offerID = $obElement->Add($arFields);
		if($offerID){
			\CCatalogProduct::Add(array("ID" => $offerID));
			$arPrice = Array(
				"PRODUCT_ID" => $offerID,
				"CATALOG_GROUP_ID" => self::$priceID,
				"PRICE" => $price,
				"CURRENCY" => "RUB",
			);
			\CPrice::Add($arPrice);
		}
		return $offerID ? $offerID : false;
    }


    /**
     * @param $filter
     * @param $iblockID
     * @return array
     * @throws \Bitrix\Main\ArgumentException
     * @throws \Bitrix\Main\LoaderException
     * Выборка Элементов из Инфоблока
     */
    public static function getIblockData($filter, $iblockID)
    {
        Loader::includeModule('iblock');

        $arProducts = array();
        $arResult = ElementTable::getList(
            array(
                'filter' => array(
                    'IBLOCK_ID' => $iblockID,
                    'ID' => $filter
                ),
                'select' => array(
                    'ID',
                    'NAME'
                ),
                'order' => array(
                    'NAME' => 'ASC'
                )
            )
        )->fetchAll();

        if (!empty($arResult)) {
            foreach ($arResult as $item) {
                $arProducts[$item['ID']] = $item['NAME'];
            }
        }

        return $arProducts;
    }

    /**
     * @param $offerID
     * @param $price
     * @param $currency
     * @return bool|\CDBResult|mixed
     * Устанавливает цену для предложения
     */
    public static function setPrice($offerID, $price, $currency)
    {
        Loader::includeModule('catalog');

        $arPrice = Array(
            "PRODUCT_ID" => $offerID,
            "CATALOG_GROUP_ID" => self::$priceID,
            "PRICE" => $price,
            "CURRENCY" => $currency,
			"QUANTITY_FROM" => false,
			"QUANTITY_TO" => false
        );

        $res = \CPrice::GetList(
            array(),
            array(
                "PRODUCT_ID" => $offerID,
                "CATALOG_GROUP_ID" => self::$priceID
            )
        );

        if ($arr = $res->Fetch()) {
            $res = \CPrice::Update($arr['ID'], $arPrice);
        } else {
            $res = \CPrice::Add($arPrice);
        }

        return $res;
    }


}