Last active
October 29, 2023 20:16
-
-
Save livevasiliy/8d3677bd8eb77bf992ee53619a86f2c1 to your computer and use it in GitHub Desktop.
Импорт из CSV файла на API Битрикс.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Bitrix\Main\ArgumentException; | |
use Bitrix\Main\Loader; | |
use Bitrix\Main\LoaderException; | |
use Bitrix\Main\ObjectPropertyException; | |
use Bitrix\Main\SystemException; | |
/** | |
* Отформатированный вывод массива | |
* | |
* @param $array | |
* | |
* @return void | |
*/ | |
function fprint_r($array) : void | |
{ | |
echo '<pre>'; | |
print_r($array); | |
echo '</pre>'; | |
} | |
/** | |
* Хелпер-функция удаляет лишние пробелы, и приводит с целому число полученную строку. | |
* | |
* Например: 1 950,00 вернёт 1950 | |
* | |
* @param string $str | |
* | |
* @return int | |
*/ | |
function getStrToInt(string $str) : int | |
{ | |
return (int)str_replace(' ', '', trim($str)); | |
} | |
/** | |
* Возвращает массив значении у свойства. | |
* | |
* @param int $iblockId | |
* @param string $searchItem | |
* | |
* @return array | |
*/ | |
function getPropertyValue(int $iblockId, string $searchItem) : array | |
{ | |
$result = array(); | |
try { | |
Loader::includeModule('iblock'); | |
$rsElement = CIBlockElement::GetList( | |
$arOrder = array('SORT' => 'ASC'), | |
$arFilter = array( | |
'ACTIVE' => 'Y', | |
'IBLOCK_ID' => $iblockId, | |
'NAME' => $searchItem | |
), | |
false, | |
false, | |
$arSelectFields = array('ID', 'NAME') | |
); | |
while ($arElement = $rsElement->fetch()) { | |
$result[] = $arElement; | |
} | |
} catch (LoaderException $e) { | |
ShowMessage($e->getMessage()); | |
} | |
return $result; | |
} | |
/*** | |
* Возвращает ID свойства | |
* | |
* @param string $code | |
* @param int $iblockId | |
* @return int|null | |
*/ | |
function getPropsId(string $code, int $iblockId) : ?int | |
{ | |
$res = CIBlockProperty::GetByID($code, $iblockId); | |
if ($ar_res = $res->GetNext()) { | |
return $ar_res['ID']; | |
} | |
return null; | |
} | |
/** | |
* Возвращает ID значения в списке | |
* | |
* @param string $code | |
* @param int $iblockID | |
* @param string $searchItem | |
* | |
* @return null|int | |
*/ | |
function getEnumValue(string $code, int $iblockID, string $searchItem) : ?int | |
{ | |
$enumValues = CIBlockPropertyEnum::GetList( | |
array('DEF' => 'DESC', 'SORT' => 'ASC'), | |
array('IBLOCK_ID' => $iblockID, 'CODE' => $code) | |
); | |
$enumValue = array(); | |
while ($value = $enumValues->GetNext()) { | |
$enumValue[$value['ID']] = $value['VALUE']; | |
} | |
if (empty($enumValue)) { | |
echo 'Значении в списке нету'; | |
return ''; | |
} | |
$searchValue = null; | |
if ($val = array_search($searchItem, $enumValue, true)) { | |
$searchValue = $val; | |
} | |
return $searchValue; | |
} | |
/** | |
* Возвращает Id элемента из выборки полученная GetList | |
* | |
* @param array $data | |
* | |
* @return null|int $elementId | |
*/ | |
function getElementId(array $data) : ?int | |
{ | |
$elementId = null; | |
if (!empty($data)) { | |
foreach ($data as $key => $value) { | |
$elementId = $value['ID']; | |
} | |
} | |
return $elementId; | |
} | |
/** | |
* Получаем список ID товаров по артиклу. | |
* | |
* @param $iblockId | |
* @param int|array $articles | |
* | |
* @return array | |
*/ | |
function getProductByArticle(int $iblockId, $articles) : ?array | |
{ | |
$result = array(); | |
$rsElement = CIBlockElement::GetList( | |
$arOrder = array('SORT' => 'ASC'), | |
$arFilter = array( | |
'ACTIVE' => 'Y', | |
'=IBLOCK_ID' => $iblockId, | |
'=property_CML2_ARTICLE' => $articles | |
), | |
false, | |
false, | |
$arSelectFields = array('ID', 'NAME') | |
); | |
while ($arElement = $rsElement->fetch()) { | |
$result[] = $arElement['ID']; | |
} | |
return $result; | |
} | |
/*** | |
* Get info data from Highload block | |
* @param int $HighLoadBlockID | |
* @param array $selectArray | |
* @param array $filterArray | |
* @param array $orderArray | |
* @param int $limit | |
* @return Result | |
* @throws ArgumentException | |
* @throws ObjectPropertyException | |
* @throws SystemException | |
*/ | |
function getHighloadData( | |
int $HighLoadBlockID, | |
array $selectArray, | |
array $filterArray, | |
array $orderArray, | |
int $limit | |
) : ?Result { | |
$arHLBlock = Bitrix\Highloadblock\HighloadBlockTable::getById($HighLoadBlockID)->fetch(); | |
$obEntity = Bitrix\Highloadblock\HighloadBlockTable::compileEntity($arHLBlock); | |
$strEntityDataClass = $obEntity->getDataClass(); | |
return $strEntityDataClass::getList(array( | |
'select' => $selectArray, | |
'filter' => $filterArray, | |
'order' => $orderArray, | |
'limit' => $limit, | |
)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Bitrix\Catalog\ProductTable; | |
use Bitrix\Main\Application; | |
use Bitrix\Main\ArgumentException; | |
use Bitrix\Main\Loader; | |
use Bitrix\Main\LoaderException; | |
use Bitrix\Main\ObjectPropertyException; | |
use Bitrix\Main\SystemException; | |
/** | |
* Class ImportCsv | |
*/ | |
class ImportCsv | |
{ | |
/** @var int ID Инфоблока каталог */ | |
public const CATALOG_IBLOCK_ID = 17; | |
/** @var int ID Инфоблока Каталога торговые предложения */ | |
public const SKU_CATALOG_IBLOCK_ID = 20; | |
/** @var int ID Инфоблока Бренды */ | |
public const BRAND_IBLOCK_ID = 12; | |
/** @var int ID Инфоблока Сертификаты */ | |
public const SERTIFICATE_IBLOCK_ID = 13; | |
/** @var int ID Highload block Цвета */ | |
public const COLOR_HIGHLOADBLOCK = 3; | |
/** @var array Массив из не разделённых строчек импортируемого файла */ | |
public $items = array(); | |
/** @var array Массив из заголовков и значений импортируемого файла */ | |
public $result = array(); | |
/** @var array Список всех товаров полученных из инфоблока каталога */ | |
public $products = array(); | |
/** @var array Список всех разделов полученных из инфоблока каталог */ | |
public $sections = array(); | |
/** @var array Список всех ID записей найденных из файла в разделе ГОСТы инфоблока Сертификаты */ | |
public $gosts = array(); | |
/** @var array Массив свойств простого товара */ | |
public $propertyValuesProduct = array(); | |
/** @var array Массив свойств торгового предложения */ | |
public $propertyValuesSkuProduct = array(); | |
/** @var array Массив значений простого товара */ | |
public $arFieldsProduct = array(); | |
/** @var array Массив значений для торгового предложения */ | |
public $arFieldsSkuProduct = array(); | |
/** @var string Путь до импортируемого файл */ | |
public $pathToImportableFile; | |
/** @var array Массив значений простого товар для обновления */ | |
public $arFieldsProductUpdate = array(); | |
/** @var array Массив значений торгового предложения для обновления */ | |
public $arFieldsSkuUpdate = array(); | |
/** @var array Массив торговых предложении у существующего товара */ | |
public $arOffers = array(); | |
/** @var array ID существующего товара */ | |
public $existProductIds = array(); | |
/** @var array Сгруппированный массив по артиклу массив $result */ | |
public $groupResult = array(); | |
/** @var array Сгруппированный массив простых товаров */ | |
public $groupSimpleProducts = array(); | |
/** @var array Массив сгруппированных файлов */ | |
public $arFiles = array(); | |
/** @var array Массив существующих файлов */ | |
public $arExFiles = array(); | |
/** | |
* Получить массив найденных существующих простых товаров | |
* | |
* @return array | |
*/ | |
final public function getGroupSimpleProducts() : array | |
{ | |
return $this->groupSimpleProducts; | |
} | |
/** | |
* Добавить в массив найденные существующие простые товары | |
* | |
* @param array $element | |
* @return void | |
*/ | |
private function setGroupSimpleProducts(array $element) : void | |
{ | |
$this->groupSimpleProducts[$element['PROPERTY_CML2_ARTICLE_VALUE']][] = $element; | |
} | |
/** | |
* Получить сгруппированный массив по артиклу массив $this->result | |
* | |
* @return array | |
*/ | |
final public function getGroupResult() : array | |
{ | |
return $this->groupResult; | |
} | |
/** | |
* Добавить значения в сгруппированный массив $this->result по артиклу | |
* | |
* @param array $element | |
* @return void | |
*/ | |
private function setGroupResult(array $element) : void | |
{ | |
$this->groupResult[$element['ARTICLE']][] = $element; | |
} | |
/** | |
* Получить ID существующего товара | |
* | |
* @return array | |
*/ | |
final public function getExistProductId() : array | |
{ | |
return $this->existProductIds; | |
} | |
/** | |
* Установить ID существующего товара | |
* | |
* @param array $existProductId | |
* | |
* @return void | |
*/ | |
private function setExistProductIds(array $existProductId) : void | |
{ | |
$this->existProductIds = array_unique($existProductId); | |
} | |
/** | |
* Получить массив найденных торговых предложении у существующего товара | |
* | |
* @return array | |
*/ | |
final public function getArOffers() : array | |
{ | |
return $this->arOffers; | |
} | |
/** | |
* Добавить найденные торговые предложения у существующего товара | |
* | |
* @param array $arOffers | |
* | |
* @return void | |
*/ | |
private function setArOffers(array $arOffers) : void | |
{ | |
$this->arOffers[] = $arOffers; | |
} | |
/** | |
* Возвращает массив "arFields" для обновления простого товара | |
* | |
* @return array | |
*/ | |
final public function getArFieldsProductUpdate() : array | |
{ | |
return $this->arFieldsProductUpdate; | |
} | |
/** | |
* Устаналивает значения для массива "arFields" для обновления простого товара | |
* | |
* @param array $arFieldsProductUpdate | |
* @param int $sectionId | |
* | |
* @return void | |
*/ | |
private function setArFieldsProductUpdate(array $arFieldsProductUpdate, int $sectionId) : void | |
{ | |
$this->arFieldsProductUpdate = array( | |
'IBLOCK_SECTION_ID' => $sectionId, | |
'CODE' => $this->getTranslitCodeElement($arFieldsProductUpdate['NAME']), | |
'NAME' => $arFieldsProductUpdate['NAME'], | |
'ACTIVE' => $this->getActiveValue($arFieldsProductUpdate), | |
'DETAIL_TEXT' => $arFieldsProductUpdate['DETAIL_TEXT'], | |
'DETAIL_TEXT_TYPE' => 'html', | |
'PROPERTY_VALUES' => $this->getPropertyValuesProduct() | |
); | |
} | |
/** | |
* Возвращает массив "arFields" для обновления торгового предложения | |
* | |
* @return array | |
*/ | |
final public function getArFieldsSkuUpdate() : array | |
{ | |
return $this->arFieldsSkuUpdate; | |
} | |
/** | |
* Устанавливает значения для массива "arFields" для торгового предложения | |
* | |
* @param array $arFieldsSkuUpdate | |
* @param int $sectionId | |
* | |
* @return void | |
*/ | |
private function setArFieldsSkuUpdate(array $arFieldsSkuUpdate, int $sectionId) : void | |
{ | |
$this->arFieldsSkuUpdate = array( | |
'IBLOCK_SECTION_ID' => $sectionId, | |
'CODE' => $this->getTranslitCodeElement($arFieldsSkuUpdate['NAME']), | |
'NAME' => $arFieldsSkuUpdate['NAME'], | |
'ACTIVE' => $this->getActiveValue($arFieldsSkuUpdate), | |
'DETAIL_TEXT' => $arFieldsSkuUpdate['DETAIL_TEXT'], | |
'DETAIL_TEXT_TYPE' => 'html', | |
'PROPERTY_VALUES' => $this->getPropertyValuesSkuProduct() | |
); | |
} | |
/** | |
* ImportCsv constructor. | |
* | |
* @param string $pathImportableCsvFile | |
* | |
* @return void | |
* | |
* @throws Exception | |
*/ | |
public function __construct(string $pathImportableCsvFile) | |
{ | |
try | |
{ | |
$this->init($pathImportableCsvFile); | |
} catch (Exception $e) | |
{ | |
echo $e->getMessage(); | |
} | |
} | |
/** | |
* @param string $pathImportableCsvFile | |
* | |
* @return void | |
*/ | |
private function init(string $pathImportableCsvFile) : void | |
{ | |
$this->loadDependency(); | |
$this->setPathImportableFile($pathImportableCsvFile); | |
$this->setSections(); | |
$this->setProducts(); | |
$this->setItems(); | |
if ($this->getSections() === 0) | |
{ | |
echo 'Нет разделов'; | |
die; | |
} | |
if ($this->getProducts() === 0) | |
{ | |
echo 'Товаров нет'; | |
die; | |
} | |
} | |
/** | |
* Поключаем зависимости от Битрикс. | |
* | |
* @return void | |
*/ | |
private function loadDependency() : void | |
{ | |
try | |
{ | |
Loader::includeModule('iblock'); | |
Loader::includeModule('catalog'); | |
Loader::includeModule('sale'); | |
Loader::includeModule('highloadblock'); | |
} catch (LoaderException $e) | |
{ | |
echo $e->getMessage(); | |
} | |
} | |
/** | |
* Устанавливает путь до импортируемого файла | |
* | |
* @param string $pathToFile | |
* | |
* @return void | |
*/ | |
private function setPathImportableFile(string $pathToFile) : void | |
{ | |
try | |
{ | |
$context = Application::getInstance()->getContext(); | |
$server = $context->getServer(); | |
$this->pathToImportableFile = $server->getDocumentRoot() . $pathToFile; | |
} catch (SystemException $e) | |
{ | |
echo $e->getMessage(); | |
} | |
} | |
/** | |
* Получить массив все разделов из инфоблока "Каталог" | |
* | |
* @return array | |
*/ | |
final public function getSections() : array | |
{ | |
return $this->sections; | |
} | |
/** | |
* Извлекает все разделы из инфоблока "Каталог" | |
* | |
* @return void | |
*/ | |
private function setSections() : void | |
{ | |
$sectionsDB = CIBlockSection::GetList( | |
array(), | |
array( | |
'ACTIVE' => 'Y', | |
'GLOBAL_ACTIVE' => 'Y', | |
'IBLOCK_ID' => self::CATALOG_IBLOCK_ID, | |
), | |
false, | |
array('ID', 'NAME') | |
); | |
while ($arSection = $sectionsDB->GetNext()) | |
{ | |
$this->sections[$arSection['ID']] = $arSection['NAME']; | |
} | |
} | |
/** | |
* Получить массив всех найденных товаров в инфоблоке Каталог | |
* | |
* @return array | |
*/ | |
final public function getProducts() : array | |
{ | |
return $this->products; | |
} | |
/** | |
* Извлекает все созданные ранее товары из инфоблока "Каталог" | |
* | |
* @return void | |
*/ | |
private function setProducts() : void | |
{ | |
$rsElement = CIBlockElement::GetList( | |
$arOrder = array('SORT' => 'ASC'), | |
$arFilter = array( | |
'ACTIVE' => 'Y', | |
'IBLOCK_ID' => self::CATALOG_IBLOCK_ID | |
), | |
false, | |
false, | |
$arSelectFields = array( | |
'ID', | |
'NAME', | |
'IBLOCK_ID', | |
'IBLOCK_SECTION_ID', | |
'CODE', | |
'PROPERTY_CML2_ARTICLE', | |
'CATALOG_GROUP_1' | |
) | |
); | |
while ($arElement = $rsElement->fetch()) | |
{ | |
//$this->products[$arElement['ID']] = $arElement['NAME']; | |
$this->products[] = $arElement; | |
} | |
} | |
/** | |
* Обработчик импорта CSV файла в инфоблок "Каталог" | |
* | |
* @return void | |
*/ | |
final public function import() : void | |
{ | |
try | |
{ | |
$iblockElementDB = new CIBlockElement(); | |
foreach ($this->getResult() as $key => $item) | |
{ | |
$gostsIds = $this->getGostIds($item); | |
if ($sectionID = $this->findSectionIdBy($item['SECTION_NAME'])) | |
{ | |
$haveSKU = (int)$item['HAS_SKU'] === 1; | |
$res = $this->getExistProduct($item, $sectionID); | |
// Если нашли, пропускаем. | |
if ($res->SelectedRowsCount() > 0) | |
{ | |
continue; | |
} | |
$productId = $this->createProduct( | |
$sectionID, | |
$item, | |
$gostsIds, | |
$item['PRICE'], | |
$iblockElementDB | |
); | |
if ($haveSKU) | |
{ | |
$i = 0; | |
foreach ($this->getResult() as $index => $skuItem) | |
{ | |
if ($skuItem['ARTICLE'] === $item['ARTICLE'] | |
&& current($this->result) !== next($this->result)) | |
{ | |
$i++; | |
$this->createProductSku( | |
$sectionID, | |
$productId, | |
$skuItem, | |
$skuItem['PRICE'], | |
$iblockElementDB, | |
$i | |
); | |
} | |
continue; | |
} | |
} | |
} else | |
{ | |
echo "Ошибка - раздел {$item['SECTION_NAME']} не был найден. Пропускаю.. <br/>"; | |
} | |
} | |
} catch (Exception $e) | |
{ | |
echo 'Ошибка при импорте <br/>'; | |
} | |
} | |
/** | |
* Получить сгруппированный массив из путей до сертификатов и/или инструкции | |
* | |
* @return array | |
*/ | |
final public function getArFiles() : array | |
{ | |
return $this->arFiles; | |
} | |
/** | |
* Добавить в сгруппированный массив пути до сертификатов и/или инструкции | |
* | |
* @param array $item | |
* @return void | |
*/ | |
private function setArFiles(array $item) : void | |
{ | |
$this->arFiles = array(); | |
if ($item['INSTRUCTUS'] !== '') | |
{ | |
$this->arFiles[] = $item['INSTRUCTUS']; | |
} | |
if ($item['CE_CERFICATE'] !== '') | |
{ | |
$this->arFiles[] = $item['CE_CERFICATE']; | |
} | |
} | |
/** | |
* Обработчик импорта CSV файла в инфоблок "Каталог" | |
* | |
* @return void | |
*/ | |
final public function update() : void | |
{ | |
try | |
{ | |
$iblockElement = new CIBlockElement(); | |
foreach ($this->getProducts() as $item) | |
{ | |
if ((int)$item['CATALOG_TYPE'] === ProductTable::TYPE_SKU) | |
{ | |
$arExistProduct = $this->getExistProduct($item, $item['IBLOCK_SECTION_ID'])->Fetch(); | |
$arOffers = CCatalogSku::getOffersList( | |
$arExistProduct['ID'], | |
$arExistProduct['IBLOCK_ID'], | |
array(), | |
array( | |
'ID', | |
'IBLOCK_ID', | |
'PROPERTY_ARTICLE' | |
), | |
array(), | |
array() | |
); | |
foreach ($arOffers as $offers) | |
{ | |
$this->setArOffers(array_values($offers)); | |
} | |
} elseif ((int)$item['CATALOG_TYPE'] === ProductTable::TYPE_PRODUCT) | |
{ | |
$this->setGroupSimpleProducts($item); | |
} | |
} | |
// Обновляем найденные простые товары | |
foreach ($this->getGroupResult() as $article => $items) | |
{ | |
foreach ($items as $index => $item) | |
{ | |
$gostsIds = $this->getGostIds($item); | |
foreach ($this->getGroupSimpleProducts() as $cml2Article => $products) | |
{ | |
foreach ($products as $idx => $product) | |
{ | |
if ($index === $idx && $item['ARTICLE'] === $product['PROPERTY_CML2_ARTICLE_VALUE']) | |
{ | |
if ($sectionId = $this->findSectionIdBy($item['SECTION_NAME'])) | |
{ | |
$skuIsUpdate = $this->updateProduct( | |
$product, | |
$sectionId, | |
$item, | |
$gostsIds, | |
$item['PRICE'], | |
$iblockElement | |
); | |
if ($skuIsUpdate) | |
{ | |
echo "[УСПЕХ] - Товар {$item['NAME']} успешно обновился <br/>"; | |
} else | |
{ | |
echo "[ПРОВАЛ] - Товар {$item['NAME']} не обновился <br/>"; | |
} | |
} else | |
{ | |
echo "Ошибка - раздел {$item['SECTION_NAME']} не был найден. Пропускаю.. <br/>"; | |
$iblockElement->LAST_ERROR; | |
continue; | |
} | |
} | |
} | |
} | |
} | |
} | |
// Обновляем найденные торговые предложения | |
foreach ($this->getGroupResult() as $article => $items) | |
{ | |
foreach ($items as $index => $item) | |
{ | |
$gostsIds = $this->getGostIds($item); | |
foreach ($this->getArOffers() as $offers) | |
{ | |
foreach ($offers as $idx => $offer) | |
{ | |
if ($index === $idx && $item['ARTICLE'] === $offer['PROPERTY_ARTICLE_VALUE']) | |
{ | |
if ($sectionId = $this->findSectionIdBy($item['SECTION_NAME'])) | |
{ | |
$parentIsUpdate = $this->updateProduct( | |
$offers[0]['PARENT_ID'], | |
$sectionId, | |
$items[0], | |
$gostsIds, | |
$items[0]['PRICE'], | |
$iblockElement | |
); | |
if ($parentIsUpdate) | |
{ | |
$skuIsUpdate = $this->updateProductSku( | |
$sectionId, | |
$offer['ID'], | |
$offer['PARENT_ID'], | |
$item, | |
$item['PRICE'], | |
$iblockElement | |
); | |
if ($skuIsUpdate) | |
{ | |
echo "[УСПЕХ] - ТП {$offer['NAME']} успешно обновился <br/>"; | |
} else | |
{ | |
echo "[ПРОВАЛ] - ТП {$offer['NAME']} не обновился <br/>"; | |
} | |
} | |
} else | |
{ | |
echo "Ошибка - раздел {$item['SECTION_NAME']} не был найден. Пропускаю.. <br/>"; | |
$iblockElement->LAST_ERROR; | |
continue; | |
} | |
} | |
} | |
} | |
} | |
} | |
} catch (Exception $e) | |
{ | |
echo 'Ошибка при импорте <br/>'; | |
} | |
} | |
/** | |
* Возвращает массив из ГОСТов из импортируемого файла | |
* | |
* @return array | |
*/ | |
final public function getGosts() : array | |
{ | |
return $this->gosts; | |
} | |
/** | |
* Добавляет в массив ГОСТы из разделённой строки в импортируемом файле | |
* | |
* @param array $gosts | |
* | |
* @return void | |
*/ | |
private function setGosts(array $gosts) : void | |
{ | |
$this->gosts = $gosts; | |
} | |
/** | |
* Вернуть сформированный ассотивный массив значений для импорта | |
* | |
* @return array | |
*/ | |
final public function getResult() : array | |
{ | |
return $this->result; | |
} | |
/** | |
* Вернуть сформированный массив "arFields" для создания простого товара | |
* | |
* @return array | |
*/ | |
final public function getArFieldsProduct() : array | |
{ | |
return $this->arFieldsProduct; | |
} | |
/** | |
* Сформировать массив "arFields" для создания нового простого товара | |
* | |
* @param int $sectionId | |
* @param array $arFieldsProduct | |
* | |
* @return void | |
*/ | |
private function setArFieldsProduct(int $sectionId, array $arFieldsProduct) : void | |
{ | |
$this->arFieldsProduct = array( | |
'IBLOCK_ID' => self::CATALOG_IBLOCK_ID, | |
'IBLOCK_SECTION_ID' => $sectionId, | |
'CODE' => $this->getTranslitCodeElement($arFieldsProduct['NAME']), | |
'NAME' => $arFieldsProduct['NAME'], | |
'ACTIVE' => $this->getActiveValue($arFieldsProduct), | |
'DETAIL_TEXT' => $arFieldsProduct['DETAIL_TEXT'], | |
'DETAIL_TEXT_TYPE' => 'html', | |
'PROPERTY_VALUES' => $this->getPropertyValuesProduct() | |
); | |
} | |
/** | |
* Вернуть сформированный массив "arFields" для создания нового торгового предложения | |
* | |
* @return array | |
*/ | |
final public function getArFieldsSkuProduct() : array | |
{ | |
return $this->arFieldsSkuProduct; | |
} | |
/** | |
* Сформировать массив "arFields" для создания нового торгового предложения | |
* | |
* @param int $sectionID | |
* @param array $arFieldsSkuProduct | |
* | |
* @param int $index | |
* @return void | |
*/ | |
private function setArFieldsSkuProduct(int $sectionID, array $arFieldsSkuProduct, int $index) : void | |
{ | |
$this->arFieldsSkuProduct = array( | |
'IBLOCK_ID' => self::SKU_CATALOG_IBLOCK_ID, | |
'IBLOCK_SECTION_ID' => $sectionID, | |
'CODE' => $this->getTranslitCodeElement($arFieldsSkuProduct['NAME']).'-'.$index, | |
'NAME' => $arFieldsSkuProduct['NAME'], | |
'ACTIVE' => $this->getActiveValue($arFieldsSkuProduct), | |
'DETAIL_TEXT' => $arFieldsSkuProduct['DETAIL_TEXT'], | |
'DETAIL_TEXT_TYPE' => 'html', | |
'PROPERTY_VALUES' => $this->getPropertyValuesSkuProduct() | |
); | |
} | |
/** | |
* Вернуть массив "PROPERTY_VALUES" для создания простого товара | |
* | |
* @return array | |
*/ | |
final public function getPropertyValuesProduct() : array | |
{ | |
return $this->propertyValuesProduct; | |
} | |
/** | |
* Сформировать массив "PROPERTY_VALUES" для создания нового простого товара. | |
* | |
* @param array $propertyValuesProduct | |
* @param array $gosts | |
* | |
* @return void | |
*/ | |
private function setPropertyValuesProduct(array $propertyValuesProduct, array $gosts) : void | |
{ | |
try | |
{ | |
$this->propertyValuesProduct = array( | |
'CML2_ARTICLE' => $this->getPropArticleValue($propertyValuesProduct), | |
'IN_STOCK' => $this->getPropInStockValue( | |
$propertyValuesProduct, | |
self::CATALOG_IBLOCK_ID | |
), | |
'TYPE' => $this->getPropTypeValue($propertyValuesProduct), // Тип | |
'VIEW' => $this->getPropViewValue($propertyValuesProduct), | |
'HIT' => $this->getPropHitValue( | |
$propertyValuesProduct, | |
self::CATALOG_IBLOCK_ID | |
), | |
'SIZES' => $this->getPropSizesValue($propertyValuesProduct), | |
'BRAND' => $this->getPropBrandValue($propertyValuesProduct), | |
'GOST' => $this->getPropGostValue($propertyValuesProduct, $gosts), | |
'TIP_PRIVYAZI' => $this->getPropTipPrivyaziValue( | |
$propertyValuesProduct, | |
self::CATALOG_IBLOCK_ID | |
), | |
'POINT_MOUNT' => $this->getPropPointMountValue($propertyValuesProduct), | |
'ADD_PROPERTIES' => $this->getPropAddPropertiesValue($propertyValuesProduct), | |
'LEASH_LINK' => $this->getPropLeashLinkValue($propertyValuesProduct), | |
'MATERIAL_POINT_MOUNT' => $this->getMaterialPointMountValue($propertyValuesProduct), | |
'COLOR_REF2' => $this->getPropColorValue($propertyValuesProduct), | |
'BUCKLE_TYPE' => $this->getPropBuckleTypeValue($propertyValuesProduct), | |
'PROD_MATERIAL' => $this->getPropProdMaterialValue($propertyValuesProduct), | |
'DIAMETER' => $this->getPropDiameterValue($propertyValuesProduct), | |
'MATERIAL' => $this->getPropMaterialValue($propertyValuesProduct), // Материал | |
'COUNT_STRANDS' => $this->getPropCountStrandsValue($propertyValuesProduct), | |
'AMOR_JERK' => $this->getPropAmorJerkValue($propertyValuesProduct), | |
'COUNT_WORK_LOOPS' => $this->getPropCountWorkLoopsValue($propertyValuesProduct), | |
'CARABINE_DISCLOSURE' => $this->getPropCarabineDisclosureValue($propertyValuesProduct), | |
'SPECIAL_USE' => $this->getPropSpecialUseValue($propertyValuesProduct), | |
'KIND_OF_ROPE' => $this->getPropKindOfRopeValue($propertyValuesProduct), | |
'ROPE_TYPE' => $this->getPropRopeTypeValue($propertyValuesProduct), | |
'CONTROL_LENGTH' => $this->getPropControlLengthValue( | |
$propertyValuesProduct, | |
self::CATALOG_IBLOCK_ID | |
), | |
'DOUBLE_STROP' => $this->getPropDoubleStropValue( | |
$propertyValuesProduct, | |
self::CATALOG_IBLOCK_ID | |
), | |
'LONG' => $this->getPropLongValue($propertyValuesProduct), | |
'WEIGHT' => $this->getPropWeightValue($propertyValuesProduct), | |
'WEIGHT_MAX' => $this->getPropWeightMaxValue($propertyValuesProduct), | |
'INSTRUCTIONS' => $this->getPropInstructionsValue($propertyValuesProduct) | |
); | |
} catch (ObjectPropertyException $e) | |
{ | |
ShowMessage($e->getMessage()); | |
} catch (ArgumentException $e) | |
{ | |
ShowMessage($e->getMessage()); | |
} catch (SystemException $e) | |
{ | |
ShowMessage($e->getMessage()); | |
} | |
} | |
/** | |
* Получить сформированный массив "PROPERTY_VALUES" для создания нового торгового предложения. | |
* | |
* @return array | |
*/ | |
final public function getPropertyValuesSkuProduct() : array | |
{ | |
return $this->propertyValuesSkuProduct; | |
} | |
/** | |
* Сформировать массив "PROPERTY_VALUES" для создания нового торгового предложения. | |
* | |
* @param array $propertyValuesSkuProduct | |
* @param int $cml2Link | |
* @param array|null $gostsIds | |
* | |
* @return void | |
*/ | |
private function setPropertyValuesSkuProduct( | |
array $propertyValuesSkuProduct, | |
int $cml2Link, | |
?array $gostsIds | |
) : void { | |
try | |
{ | |
$this->propertyValuesSkuProduct = array( | |
'ARTICLE' => $this->getPropArticleValue($propertyValuesSkuProduct), | |
'CML2_LINK' => $cml2Link, | |
'IN_STOCK' => $this->getPropInStockValue( | |
$propertyValuesSkuProduct, | |
self::SKU_CATALOG_IBLOCK_ID | |
), | |
'TYPE' => $this->getPropTypeValue($propertyValuesSkuProduct), // Тип | |
'VIEW' => $this->getPropViewValue($propertyValuesSkuProduct), | |
'HIT' => $this->getPropHitValue( | |
$propertyValuesSkuProduct, | |
self::SKU_CATALOG_IBLOCK_ID | |
), | |
'SIZES' => $this->getPropSizesValue($propertyValuesSkuProduct), | |
'BRAND' => $this->getPropBrandValue($propertyValuesSkuProduct), | |
'GOST' => $this->getPropGostValue($propertyValuesSkuProduct, $gostsIds), | |
'TIP_PRIVYAZI' => $this->getPropTipPrivyaziValue( | |
$propertyValuesSkuProduct, | |
self::SKU_CATALOG_IBLOCK_ID | |
), | |
'POINT_MOUNT' => $this->getPropPointMountValue($propertyValuesSkuProduct), | |
'ADD_PROPERTIES' => $this->getPropAddPropertiesValue($propertyValuesSkuProduct), | |
'LEASH_LINK' => $this->getPropLeashLinkValue($propertyValuesSkuProduct), | |
'MATERIAL_POINT_MOUNT' => $this->getMaterialPointMountValue($propertyValuesSkuProduct), | |
'COLOR_REF' => $this->getPropColorValue($propertyValuesSkuProduct), | |
'BUCKLE_TYPE' => $this->getPropBuckleTypeValue($propertyValuesSkuProduct), | |
'PROD_MATERIAL' => $this->getPropProdMaterialValue($propertyValuesSkuProduct), | |
'DIAMETER' => $this->getPropDiameterValue($propertyValuesSkuProduct), | |
'MATERIAL' => $this->getPropMaterialValue($propertyValuesSkuProduct), | |
'COUNT_STRANDS' => $this->getPropCountStrandsValue($propertyValuesSkuProduct), | |
'AMOR_JERK' => $this->getPropAmorJerkValue($propertyValuesSkuProduct), | |
'COUNT_WORK_LOOPS' => $this->getPropCountWorkLoopsValue($propertyValuesSkuProduct), | |
'CARABINE_DISCLOSURE' => $this->getPropCarabineDisclosureValue($propertyValuesSkuProduct), | |
'SPECIAL_USE' => $this->getPropSpecialUseValue($propertyValuesSkuProduct), | |
'KIND_OF_ROPE' => $this->getPropKindOfRopeValue($propertyValuesSkuProduct), | |
'ROPE_TYPE' => $this->getPropRopeTypeValue($propertyValuesSkuProduct), | |
'CONTROL_LENGTH' => $this->getPropControlLengthValue( | |
$propertyValuesSkuProduct, | |
self::SKU_CATALOG_IBLOCK_ID | |
), | |
'DOUBLE_STROP' => $this->getPropDoubleStropValue( | |
$propertyValuesSkuProduct, | |
self::SKU_CATALOG_IBLOCK_ID | |
), | |
'LONG' => $this->getPropLongValue($propertyValuesSkuProduct), | |
'WEIGHT' => $this->getPropWeightValue($propertyValuesSkuProduct), | |
'WEIGHT_MAX' => $this->getPropWeightMaxValue($propertyValuesSkuProduct) | |
); | |
} catch (ObjectPropertyException $e) | |
{ | |
ShowMessage($e->getMessage()); | |
} catch (ArgumentException $e) | |
{ | |
ShowMessage($e->getMessage()); | |
} catch (SystemException $e) | |
{ | |
ShowMessage($e->getMessage()); | |
} | |
} | |
/** | |
* Получить ассотивный массив из названия колонки и его значения | |
* | |
* @return array | |
*/ | |
final public function getItems() : array | |
{ | |
return $this->items; | |
} | |
/** | |
* Сформировать ассотивный массив из первой строки с названиями колонки и их значении. | |
* | |
* @return void | |
*/ | |
private function setItems() : void | |
{ | |
$strings = file($this->getPathToImportableFile()); | |
$keys = explode(';', trim($strings[0])); | |
unset($strings[0]); // убрать названия столбцов | |
foreach ($strings as $k => $string) | |
{ | |
$this->items[] = explode(';', trim($string)); | |
} | |
foreach ($this->items as $item) | |
{ | |
$this->result[] = array_combine($keys, $item); | |
} | |
foreach ($this->result as $element) | |
{ | |
$this->setGroupResult($element); | |
} | |
unset($this->items); | |
} | |
/** | |
* Вернуть путь до импортируемого файла. | |
* | |
* @return string | |
*/ | |
final public function getPathToImportableFile() : string | |
{ | |
return $this->pathToImportableFile; | |
} | |
/** | |
* Вернуть существующий товар по артикулу | |
* | |
* @param array $item | |
* @param int $sectionID | |
* | |
* @return CIBlockResult|int | |
*/ | |
final public function getExistProduct(array $item, int $sectionID) : CIBlockResult | |
{ | |
return CIBlockElement::GetList( | |
array(), | |
array( | |
'=IBLOCK_ID' => self::CATALOG_IBLOCK_ID, | |
'=ACTIVE' => 'Y', | |
'=NAME' => trim($item['NAME']), | |
'=SECTION_ID' => $sectionID, | |
'=PROPERTY_CML2_ARTICLE' => trim($item['ARTICLE']) | |
), | |
false, | |
false, | |
array( | |
'ID', | |
'IBLOCK_ID', | |
'IBLOCK_SECTION_ID', | |
'NAME', | |
'PROPERTY_CML2_ARTICLE', | |
'PROPERTY_INSTRUCTIONS', | |
'CATALOG_GROUP_1' | |
) | |
); | |
} | |
/** | |
* Вернуть значение из свойства "Регулировка длины" | |
* | |
* @param array $skuItem | |
* | |
* @param int $iblockId | |
* @return null|int | |
*/ | |
final public function getControlLengthValue(array $skuItem, int $iblockId) : ?int | |
{ | |
if (strtolower(trim($skuItem['CONTROL_LENGTH'])) === 'да') | |
{ | |
return getEnumValue('CONTROL_LENGTH', $iblockId, 'да'); | |
} | |
if (strtolower(trim($skuItem['CONTROL_LENGTH'])) === 'нет') | |
{ | |
return getEnumValue('CONTROL_LENGTH', $iblockId, 'нет'); | |
} | |
return null; | |
} | |
/** | |
* Вернуть значение из свойства "Двойной строп" | |
* | |
* @param array $skuItem | |
* | |
* @param int $iblockId | |
* @return null|int | |
*/ | |
final public function getDoubleStropValue(array $skuItem, int $iblockId) : ?int | |
{ | |
if (strtolower(trim($skuItem['DOUBLE_STROP'])) === 'да') | |
{ | |
return getEnumValue('DOUBLE_STROP', $iblockId, 'да'); | |
} | |
if (strtolower(trim($skuItem['DOUBLE_STROP'])) === 'нет') | |
{ | |
return getEnumValue('DOUBLE_STROP', $iblockId, 'нет'); | |
} | |
return null; | |
} | |
/** | |
* Установить доступное количество для товара / торгового предложения. | |
* | |
* @param int $productOfferId | |
* @param int $quantity | |
* | |
* @return void | |
*/ | |
private function setQuantityProduct(int $productOfferId, int $quantity) : void | |
{ | |
CCatalogProduct::Add( | |
array( | |
'ID' => $productOfferId, | |
'QUANTITY' => $quantity | |
) | |
); | |
} | |
/** | |
* Получить внешний код из Highload-блока "Цвет" | |
* | |
* @param string $xmlId | |
* | |
* @return string|null | |
* | |
* @throws SystemException | |
* @throws ArgumentException | |
* @throws ObjectPropertyException | |
*/ | |
final public function getColorValue(string $xmlId) : ?string | |
{ | |
$color = getHighloadData( | |
self::COLOR_HIGHLOADBLOCK, | |
array('ID', 'UF_NAME', 'UF_XML_ID'), | |
array('=UF_XML_ID' => strtolower(trim($xmlId))), | |
array('ID' => 'ASC'), | |
1 | |
); | |
if ($resColor = $color->fetch()) | |
{ | |
return $resColor['UF_XML_ID']; | |
} | |
return null; | |
} | |
/** | |
* Транслитировать название для создания символьного кода товару | |
* | |
* @param string $string | |
* | |
* @return string | |
*/ | |
final public function getTranslitCodeElement(string $string) : string | |
{ | |
return CUtil::translit( | |
$string, | |
'ru', | |
array('replace_space' => '-', 'replace_other' => '-') | |
); | |
} | |
/** | |
* Найти ID раздела из списка существующих разделов в инфоблоке "Каталог" | |
* | |
* @param $item | |
* | |
* @return false|int|string | |
*/ | |
final public function findSectionIdBy(string $item) : int | |
{ | |
return array_search(trim($item), $this->getSections(), true); | |
} | |
/** | |
* Установить стоимость товару | |
* | |
* @param int $productId | |
* @param string $price | |
* | |
* @return void | |
*/ | |
private function setPriceProduct(int $productId, string $price) : void | |
{ | |
$priceDb = new CPrice(); | |
$priceDb::Add(array( | |
'PRODUCT_ID' => $productId, | |
'CATALOG_GROUP_ID' => 1, | |
'PRICE' => getStrToInt(trim($price)), | |
'CURRENCY' => 'RUB' | |
)); | |
} | |
/** | |
* Создать новый простой товар | |
* | |
* @param int $sectionID | |
* @param array $item | |
* @param array $gostsIds | |
* @param int $quantity | |
* @param string $price | |
* @param CIBlockElement $iblockElementDB | |
* | |
* @return int | |
*/ | |
final public function createProduct( | |
int $sectionID, | |
array $item, | |
array $gostsIds, | |
string $price, | |
CIBlockElement $iblockElementDB, | |
int $quantity = 9999 | |
) : int { | |
$this->setArFiles($item); | |
$this->setPropertyValuesProduct($item, $gostsIds); | |
$this->setArFieldsProduct($sectionID, $item); | |
$productId = $iblockElementDB->Add($this->getArFieldsProduct()); | |
if ($productId) | |
{ | |
$this->setQuantityProduct($productId, $quantity); | |
$this->setPriceProduct($productId, $price); | |
echo "Успешно создал новый товар - {$item['NAME']} <br/>"; | |
} else | |
{ | |
echo $iblockElementDB->LAST_ERROR; | |
} | |
return $productId; | |
} | |
/** | |
* Создать новое торговое предложение. | |
* | |
* @param int $sectionID | |
* @param int $productId | |
* @param array $skuItem | |
* @param int $price | |
* @param CIBlockElement $iblockElementDB | |
* @param int $index | |
* @param int $quantity | |
* | |
* @return int | |
*/ | |
final public function createProductSku( | |
int $sectionID, | |
int $productId, | |
array $skuItem, | |
int $price, | |
CIBlockElement $iblockElementDB, | |
int $index, | |
int $quantity = 9999 | |
) : int { | |
$this->setPropertyValuesSkuProduct($skuItem, $productId, $this->getGostIds($skuItem)); | |
$this->setArFieldsSkuProduct($sectionID, $skuItem, $index); | |
$offerId = $iblockElementDB->Add($this->getArFieldsSkuProduct()); | |
if ($offerId) | |
{ | |
$this->setQuantityProduct($offerId, $quantity); | |
$this->setPriceProduct($offerId, $price); | |
echo "Успешно создано ТП - {$offerId} <br/>"; | |
} | |
return $offerId; | |
} | |
/** | |
* Вернуть значение для поля товара "Активность" | |
* | |
* @param array $arFieldsSkuProduct | |
* | |
* @return string | |
*/ | |
final public function getActiveValue(array $arFieldsSkuProduct) : string | |
{ | |
return (int)$arFieldsSkuProduct['ACTIVE'] === 0 ? 'Y' : 'N'; | |
} | |
/** | |
* Получить значение для свойства "В наличие" | |
* | |
* @param array $propertyValuesSkuProduct | |
* @param int $iblockId | |
* | |
* @return int|null | |
*/ | |
final public function getPropInStockValue(array $propertyValuesSkuProduct, int $iblockId) : ?int | |
{ | |
return (int)trim($propertyValuesSkuProduct['IN_STOCK']) === 1 | |
? getEnumValue('IN_STOCK', $iblockId, 'Y') | |
: null; | |
} | |
/** | |
* Получить значение для свойства "Тип" | |
* | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropTypeValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['TYPE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['TYPE']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Вид" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropViewValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['VIEW']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['VIEW']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение "Новинка" из свойства "Наши предложения" | |
* | |
* @param array $propertyValuesSkuProduct | |
* @param int $iblockId | |
* | |
* @return int|null | |
*/ | |
final public function getPropHitValue(array $propertyValuesSkuProduct, int $iblockId) : ?int | |
{ | |
return (int)trim($propertyValuesSkuProduct['HIT']) === 1 | |
? getEnumValue('HIT', $iblockId, 'Новинка') | |
: null; | |
} | |
/** | |
* Получить значение для свойства "Размер" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropSizesValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['SIZES']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['SIZES']); | |
} | |
return null; | |
} | |
/** | |
* Получить ID найденного бренда | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|int | |
*/ | |
final public function getPropBrandValue(array $propertyValuesSkuProduct) : ?int | |
{ | |
if (trim($propertyValuesSkuProduct['BRAND']) !== '') | |
{ | |
return getElementId(getPropertyValue(self::BRAND_IBLOCK_ID, trim($propertyValuesSkuProduct['BRAND']))); | |
} | |
return null; | |
} | |
/** | |
* Получить ID найденных ГОСТов | |
* | |
* @param array $propertyValuesSkuProduct | |
* @param array|null $gostsIds | |
* | |
* @return array|null | |
*/ | |
final public function getPropGostValue(array $propertyValuesSkuProduct, ?array $gostsIds) : ?array | |
{ | |
return $propertyValuesSkuProduct['GOST'] !== '' ? $gostsIds : null; | |
} | |
/** | |
* Получить значение для свойства "Тип привязи" | |
* | |
* @param array $propertyValuesSkuProduct | |
* @param int $iblockId | |
* | |
* @return int|null | |
*/ | |
final public function getPropTipPrivyaziValue(array $propertyValuesSkuProduct, int $iblockId) : ?int | |
{ | |
if (trim($propertyValuesSkuProduct['TIP_PRIVYAZI']) !== '') | |
{ | |
return getEnumValue('TIP_PRIVYAZI', $iblockId, trim($propertyValuesSkuProduct['TIP_PRIVYAZI'])); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Количество креплений" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropPointMountValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['POINT_MOUNT']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['POINT_MOUNT']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Дополнительные свойства" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropAddPropertiesValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['ADD_PROPERTIES']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['ADD_PROPERTIES']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Линейка привязи" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropLeashLinkValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['LEASH_LINK']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['LEASH_LINK']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Материал точек крепления" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getMaterialPointMountValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['MATERIAL_POINT_MOUNT']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['MATERIAL_POINT_MOUNT']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Цвет" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return string|null | |
* | |
* @throws ArgumentException | |
* @throws ObjectPropertyException | |
* @throws SystemException | |
*/ | |
final public function getPropColorValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
return $this->getColorValue(trim($propertyValuesSkuProduct['COLOR'])); | |
} | |
/** | |
* Получить значение для свойства "Тип пряжек" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropBuckleTypeValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['BUCKLE_TYPE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['BUCKLE_TYPE']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Материал изготовления" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropProdMaterialValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['PROD_MATERIAL']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['PROD_MATERIAL']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Диаметр" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropDiameterValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['DIAMETER']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['DIAMETER']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Материал" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropMaterialValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['MATERIAL']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['MATERIAL']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Количество прядей" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropCountStrandsValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['COUNT_STRANDS']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['COUNT_STRANDS']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Амортизатор рывка" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropAmorJerkValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['AMOR_JERK']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['AMOR_JERK']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Количество рабочих петель" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropCountWorkLoopsValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['COUNT_WORK_LOOPS']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['COUNT_WORK_LOOPS']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Раскрытие концевого карабина" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropCarabineDisclosureValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['CARABINE_DISCLOSURE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['CARABINE_DISCLOSURE']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Особые условия применения" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropSpecialUseValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['SPECIAL_USE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['SPECIAL_USE']); | |
} | |
return null; | |
} | |
/** | |
* Получить значения для свойства "Вид веревки" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropKindOfRopeValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['KIND_OF_ROPE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['KIND_OF_ROPE']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Тип веревки" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropRopeTypeValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['ROPE_TYPE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['ROPE_TYPE']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение для свойства "Регулировка длины" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @param int $iblockId | |
* @return int|null | |
*/ | |
final public function getPropControlLengthValue(array $propertyValuesSkuProduct, int $iblockId) : ?int | |
{ | |
return $this->getControlLengthValue($propertyValuesSkuProduct, $iblockId); | |
} | |
/** | |
* Получить значение для свойства "Двойной строп" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @param int $iblockId | |
* @return int|null | |
*/ | |
final public function getPropDoubleStropValue(array $propertyValuesSkuProduct, int $iblockId) : ?int | |
{ | |
return $this->getDoubleStropValue($propertyValuesSkuProduct, $iblockId); | |
} | |
/** | |
* Получить значение для свойства "Артикул" | |
* | |
* @param array $propertyValuesSkuProduct | |
* | |
* @return null|string | |
*/ | |
final public function getPropArticleValue(array $propertyValuesSkuProduct) : ?string | |
{ | |
if (trim($propertyValuesSkuProduct['ARTICLE']) !== '') | |
{ | |
return trim($propertyValuesSkuProduct['ARTICLE']); | |
} | |
return null; | |
} | |
/** | |
* Возвращает массив найденных ID ГОСТов | |
* | |
* @param array $item | |
* | |
* @return array|null | |
*/ | |
final public function getGostIds(array $item) : ?array | |
{ | |
$this->setGosts(explode(',', str_replace(', ', ',', trim($item['GOST'])))); | |
$gostsIds = null; | |
foreach ($this->getGosts() as $gost) | |
{ | |
if ($gost !== null) | |
{ | |
$gostsIds[] = getElementId(getPropertyValue(self::SERTIFICATE_IBLOCK_ID, $gost)); | |
} | |
} | |
return $gostsIds; | |
} | |
/** | |
* Обновляет указанный товар | |
* | |
* @param array $exProduct | |
* @param int $sectionID | |
* @param array $item | |
* @param array|null $gostsIds | |
* @param string $price | |
* @param CIBlockElement $iblockElementDB | |
* @param int $quantity | |
* | |
* @return bool | |
*/ | |
private function updateProduct( | |
array $exProduct, | |
int $sectionID, | |
array $item, | |
?array $gostsIds, | |
string $price, | |
CIBlockElement $iblockElementDB, | |
int $quantity = 9999 | |
) : bool { | |
$this->updateArFiles($item, $exProduct['ID'], $exProduct['PROPERTY_CML2_ARTICLE_VALUE']); | |
$this->setPropertyValuesProduct($item, $gostsIds); | |
$this->setArFieldsProduct($sectionID, $item); | |
$successUpdate = $iblockElementDB->Update($exProduct['ID'], $this->getArFieldsProduct()); | |
if ($successUpdate) | |
{ | |
$this->updateQuantityProduct($exProduct['ID'], $quantity); | |
$this->updatePriceProduct($exProduct['ID'], $price); | |
echo "Успешно обновил товар - {$item['NAME']} <br/>"; | |
} else | |
{ | |
echo $iblockElementDB->LAST_ERROR; | |
} | |
return $successUpdate; | |
} | |
/** | |
* Обновляет указанное торговое предложение | |
* | |
* @param int $sectionID | |
* @param int $skuId | |
* @param int $cml2Link | |
* @param array $skuItem | |
* @param string $price | |
* @param CIBlockElement $iblockElementDB | |
* @param int $quantity | |
* | |
* @return bool | |
*/ | |
private function updateProductSku( | |
int $sectionID, | |
int $skuId, | |
int $cml2Link, | |
array $skuItem, | |
string $price, | |
CIBlockElement $iblockElementDB, | |
int $quantity = 9999 | |
) : bool { | |
$this->setPropertyValuesSkuProduct($skuItem, $cml2Link, $this->getGostIds($skuItem)); | |
$this->setArFieldsSkuProduct($sectionID, $skuItem); | |
$offerIsUpdate = $iblockElementDB->Update($skuId, $this->getArFieldsSkuProduct()); | |
if ($offerIsUpdate) | |
{ | |
$this->updateQuantityProduct($skuId, $quantity); | |
$this->updatePriceProduct($skuId, $price); | |
echo "Успешно обновил ТП - {$skuId} <br/>"; | |
} | |
return $offerIsUpdate; | |
} | |
/** | |
* Удаляет старое значение кол-во и устанавливает новое значение. | |
* | |
* @param int $productId | |
* @param int $quantity | |
* | |
* @return void | |
*/ | |
private function updateQuantityProduct(int $productId, int $quantity = 9999) : void | |
{ | |
$el = new CCatalogProduct; | |
$el::Update($productId, [ | |
'QUANTITY' => $quantity | |
]); | |
} | |
/** | |
* Удаляет старую цену и устанавливает новую | |
* | |
* @param int $productId | |
* @param string $price | |
* | |
* @return void | |
*/ | |
private function updatePriceProduct(int $productId, string $price) : void | |
{ | |
$existPrice = CPrice::GetList( | |
array(), | |
array('PRODUCT_ID' => $productId), | |
false, | |
false, | |
array() | |
)->Fetch(); | |
if ($existPrice && CPrice::Delete($existPrice['ID'])) | |
{ | |
$this->setPriceProduct($productId, $price); | |
} else | |
{ | |
$this->setPriceProduct($productId, $price); | |
} | |
} | |
/** | |
* Получить знание свойства "Длина" | |
* | |
* @param array $propertyValues | |
* | |
* @return string|null | |
*/ | |
private function getPropLongValue(array $propertyValues) : ?string | |
{ | |
if (trim($propertyValues['LONG']) !== '') | |
{ | |
return trim($propertyValues['LONG']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение свойства "Вес" | |
* | |
* @param array $propertyValues | |
* | |
* @return string|null | |
*/ | |
private function getPropWeightValue(array $propertyValues) : ?string | |
{ | |
if (trim($propertyValues['WEIGHT']) !== '') | |
{ | |
return trim($propertyValues['WEIGHT']); | |
} | |
return null; | |
} | |
/** | |
* Получить значение свойства "Максимальный вес работника, кг" | |
* | |
* @param array $propertyValues | |
* | |
* @return string|null | |
*/ | |
private function getPropWeightMaxValue(array $propertyValues) : ?string | |
{ | |
if (trim($propertyValues['WEIGHT_MAX']) !== '') | |
{ | |
return trim($propertyValues['WEIGHT_MAX']); | |
} | |
return null; | |
} | |
/** | |
* Возвращает уже подготовленный массив загруженных сертификатов и/или инструкции | |
* для создания нового простого товара | |
* | |
* @param array $propertyValuesProduct | |
* | |
* @return null|array | |
*/ | |
private function getPropInstructionsValue(array $propertyValuesProduct) : ?array | |
{ | |
$paths = array(); | |
if ( | |
(trim($propertyValuesProduct['INSTRUCTUS']) !== '') || | |
(trim($propertyValuesProduct['CE_CERFICATE']) !== '') | |
) | |
{ | |
foreach ($this->getArFiles() as $index => $file) | |
{ | |
$paths["n{$index}"]['VALUE'] = CFile::MakeFileArray(Application::getDocumentRoot() . $file); | |
} | |
return $paths; | |
} | |
return null; | |
} | |
/** | |
* Проверяет на дубликаты текущий загружаемых файл с существующими. | |
* И формирует массив "$arFiles" | |
* | |
* @param array $item | |
* @param int $productId | |
* @param string $article | |
* | |
* @return void | |
*/ | |
private function updateArFiles(array $item, int $productId, string $article) : void | |
{ | |
$this->arFiles = array(); | |
$this->setExistFilesProduct($productId); | |
// Проходимся по существующим файлам и сравним на дубликаты | |
if (!in_array($this->getUploadedFilename($item['INSTRUCTUS']), $this->arExFiles, false)) | |
{ | |
$this->arFiles = array(); | |
if ($item['INSTRUCTUS'] !== '') | |
{ | |
$this->arFiles[] = $item['INSTRUCTUS']; | |
} | |
} | |
if ($item['CE_CERFICATE'] !== '' && | |
!in_array($this->getUploadedFilename($item['CE_CERFICATE']), $this->arExFiles, false)) | |
{ | |
$this->arFiles[] = $item['CE_CERFICATE']; | |
} | |
} | |
/** | |
* Получить массив из найденных загруженных файлов у существующего товара | |
* | |
* @return array | |
*/ | |
final public function getArExFiles() : array | |
{ | |
return $this->arExFiles; | |
} | |
/** | |
* Добавляет в массив $arExFiles найденные существующие файлы | |
* | |
* @param array $arExFiles | |
* | |
* @return void | |
*/ | |
private function setArExFiles(array $arExFiles) : void | |
{ | |
if ($arExFiles !== null) | |
{ | |
$this->arExFiles[] = trim($arExFiles['ORIGINAL_NAME']); | |
} | |
} | |
/** | |
* Добавляет в массив exArFiles все добавленные файлы | |
* | |
* @param int $productId | |
* | |
* @return void | |
*/ | |
private function setExistFilesProduct(int $productId) : void | |
{ | |
$fileIds = []; | |
$propInstructionsId = getPropsId('INSTRUCTIONS', self::CATALOG_IBLOCK_ID); | |
$iterator = CIBlockElement::GetPropertyValues( | |
self::CATALOG_IBLOCK_ID, | |
array('ACTIVE' => 'Y', '=ID' => $productId), | |
true, | |
array('=ID' => array($propInstructionsId)) | |
); | |
while ($row = $iterator->Fetch()) | |
{ | |
$fileIds = $row[$propInstructionsId]; | |
} | |
$paths = []; | |
foreach ($fileIds as $id) | |
{ | |
$paths[] = CFile::GetByID($id); | |
} | |
$this->arExFiles = []; | |
foreach ($paths as $idx => $arResult) | |
{ | |
foreach ($arResult as $index => $arFiles) | |
{ | |
foreach ($arFiles as $key => $file) | |
{ | |
$this->setArExFiles($file); | |
} | |
} | |
} | |
} | |
/** | |
* Возвращает название файла загружаемого файла из CSV файла | |
* | |
* @param $str | |
* | |
* @return false|string | |
*/ | |
private function getUploadedFilename(string $str) : string | |
{ | |
return trim(substr(strrchr(trim($str), '/'), 1)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Хелперы функции | |
require_once __DIR__ . '/Helpers/BitrixHelper.php'; | |
// Обработчик импорта CSV файла в инфоблок "Каталог". | |
require_once __DIR__ . '/ImportCsv.php'; | |
/** | |
* Функция для вызова импорта CSV файла в инфоблок "Каталог". | |
* | |
* @param string $path Путь до импортируемого CSV файла | |
*/ | |
function importCSVToCatalog(string $path) | |
{ | |
try | |
{ | |
(new ImportCsv($path))->import(); | |
} catch (Exception $e) | |
{ | |
die('Ошибка импорта. <br/>'); | |
} | |
} | |
/** | |
* Функция для вызова импорта CSV файла в инфоблок "Каталог". | |
* | |
* @param string $path Путь до импортируемого CSV файла | |
*/ | |
function updateCSVToCatalog(string $path) | |
{ | |
try | |
{ | |
(new ImportCsv($path))->update(); | |
} catch (Exception $e) | |
{ | |
die('Ошибка импорта. <br/>'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment