Your IP : 18.117.187.15


Current Path : /home/bitrix/ext_www/ballu.in.ua/local/modules/rusklimat.exchange/classes/general/
Upload File :
Current File : /home/bitrix/ext_www/ballu.in.ua/local/modules/rusklimat.exchange/classes/general/exchange_wh.php

<?php
/*
 * RusKlimat CatalogModule
 * Основной класс обновления наличия
 * Основная функция - Update
 * 
 * @author  Alex
 * @date   22/12/2017
*/
use Bitrix\Main\Diag;
use Bitrix\Main\Diag\Debug;

IncludeModuleLangFile(__FILE__);

class RusklimatExchangeWH extends RusklimatMain
{
	protected $ib_catalog = 0; // инфоблок каталога
	protected $ib_globus = 0; // инфоблок каталога
	protected $arGateWh = array(); // данные со шлюза
	protected $id_frc = array(); // id склада Кержач
	protected $arRegionWh = array(); // привязка регионов к складам
	protected $arWhRegion = array(); // привязка складов к регионам
	protected $arAllWhXmlId = array(); // привязка xml_склада => ID_склада, все склады из базы данных
	protected $arWh = array(); // массив складов для обновления наличия
	protected $arAllIdsWh = array(); // список всех обновляемых складов
	protected $arRegions = array(); // массив всех регионов из ИБ (БД)
	
	
	public function __construct()
    {
		parent::__construct();
		
		$this->ib_catalog = COption::GetOptionInt("rusklimat.exchange", "RK_EXCHANGE_CATALOG_IBLOCK_ID");
		$this->ib_globus = COption::GetOptionInt("rusklimat.exchange", "RK_EXCHANGE_MAIN_GLOBUS_IBLOCK_ID");
		$this->id_frc = $this->setIdFrc();
		
		if(empty($this->ib_catalog || $this->ib_globus))
			$this->setError('Empty setting Catalog or Globus Iblock ID from Rusklimat Module');
		
		if(empty($this->id_frc))
			$this->setError('Empty ID store - Kergach');

		if(!empty($this->errors))
			RusklimatMain::showAndWriteError( $this->errors, "wh.error.txt" );
	}
	
	/*
	 * Установим ID склада Кержача
	 */
	protected function setIdFrc()
	{
		$res = CCatalogStore::GetList([],['XML_ID' => 'WH_frc'],false);
		if (!$arWH_frc = $res->Fetch()){
			$iWH_frc = CCatalogStore::Add(array('XML_ID' => 'WH_frc', 'TITLE' => 'Склад Киржач'));
		} else {
			$iWH_frc = $arWH_frc['ID'];
		}
		return $iWH_frc;
	}
	
	/*
	 * Устанавливаем данные по наличию из шлюза
	 */
	function setGateWh() 
	{
		$this->arGateWh = $this->connection->getRest("ostatki_make");
	}
	
	/*
	 * Создаем вспомогательные массивы соответсвий регион-склад, и данные из БД
	 */
	function setPropArray()
	{
		if(empty($this->arGateWh))
			throw new Exception('Empty array arGateWH from setPropArray function');
		
		foreach($this->arGateWh["data"] as $wh => $data) {
			foreach($data["regions"] as $region){
				$this->arRegionWh[$region] = $wh;
				$this->arWhRegion[$wh] = $region;
			}
		}
		// делаем массив xml_склада => ID_склада
		$res = CCatalogStore::GetList(["XML_ID"=>"DESC"],[],false);
		while($row = $res->Fetch()){
			$this->arAllWhXmlId[$row["XML_ID"]]=$row["ID"];
		}
		
		// готовим массив только нужных складов для обновления
		foreach($this->arWhRegion as $wh => $region){
			
			$arFields = Array(
				"TITLE" => "WH_main_".$wh,
				"ACTIVE" => "Y",
				"XML_ID" => $wh,
			);
			
			$arFields2 = Array(
				"TITLE" => "WH_order_".$wh,
				"ACTIVE" => "Y",
				"XML_ID" => $wh."-or",
			);
			
			$arFields3 = Array(
				"TITLE" => "WH_general_".$wh,
				"ACTIVE" => "Y",
				"XML_ID" => $wh."-gen",
			);
			// если склад уже есть в БД, запишем ID
			if(!empty($this->arAllWhXmlId[$wh])){
				$ID = $this->arAllWhXmlId[$wh];
				$ID2 = $this->arAllWhXmlId[$wh."-or"];
				$ID3 = $this->arAllWhXmlId[$wh."-gen"];
			} else { // Если нет, добавим новый
				$ID = CCatalogStore::Add($arFields);
				$ID2 = CCatalogStore::Add($arFields2);
				$ID3 = CCatalogStore::Add($arFields3);
			}

			$this->arWh[$wh]["WH"] = $ID;
			$this->arWh[$wh]["WH2"] = $ID2;
			$this->arWh[$wh]["WH3"] = $ID3;
			$this->arAllIdsWh[] = $ID;
			$this->arAllIdsWh[] = $ID2;
			$this->arAllIdsWh[] = $ID3;
		}
		$this->arAllIdsWh[] = $this->id_frc; // + Киржач
		unset($this->arWhRegion); // далее он не нужен
		
		$this->arRegions = RusklimatElement::getElements( array("IBLOCK_ID" => $this->ib_globus), array("ID","NAME","XML_ID"), "XML_ID" );
		$this->arElements = RusklimatElement::getElements( array("IBLOCK_ID" => $this->ib_catalog), array("ID","NAME","XML_ID"), "XML_ID" );
	}
	
	/*
	 * Обновляем информацию по складам в ИБ
	 */
	function updateWh()
	{
		if(empty($this->arRegionWh) || empty($this->arWh) || empty($this->arRegions))
			throw new Exception('Empty array [arRegionWh|arWh|arRegions] from updateWh function');
		
		foreach($this->arRegionWh as $region => $wh){
			$id = $this->arRegions[$region]["ID"];
			if(!empty($id))
			{
				// обновляется свойства инфоблока регионов
				CIBlockElement::SetPropertyValueCode($id, "WH_HASH", $wh);
				CIBlockElement::SetPropertyValueCode($id, "WH", $this->arWh[$wh]["WH"]);
				CIBlockElement::SetPropertyValueCode($id, "WH_ORDER", $this->arWh[$wh]["WH2"]);
				CIBlockElement::SetPropertyValueCode($id, "WH_GENERAL", $this->arWhH[$wh]["WH3"]);
			}
		}
	}
	
	/*
	 * Обновляем информацию наличия товаров по складам
	 */
	function updateAvailable()
	{
		if(empty($this->arRegionWh) || empty($this->arWh) || empty($this->arRegions) || empty($this->arAllIdsWh))
			throw new Exception('Empty array [arRegionWh|arWh|arRegions|arAllIdsWh] from updateAvailable function');
	
		$stores = array();
		
		// получаем привязку товаров и группируем по складам
		// [ID_склада] => (ID_Товара => ID_записи_наличия_в_БД, ...), ...
		$resStore = CCatalogStoreProduct::GetList(array(), array('STORE_ID' => $this->arAllIdsWh), false, false, array()); 
		while ($arStore = $resStore->Fetch()){ 
			$stores[$arStore["STORE_ID"]][$arStore["PRODUCT_ID"]] = $arStore["ID"];
		}
		
		$addresWh = $this->connection->getAddress("ostatki_wh");
		
		foreach($this->arWh as $wh => $arWh){
			
			$content = $this->connection->getRest($addresWh.$wh, array(), "GET", true, "http://api.rusklimat.ru/v1/");

			foreach($content["data"] as $xmlid => $amounts){
				// массив amounts: первая цифра Available, вторая Preorder
				
				$product_id = $this->arElements[$xmlid]["ID"];
				$amounts_WH3 = 0;
				$responsive_wh = array();
				
				if(empty($product_id))
					continue;
				
				if(($amounts[1] + $amounts[0]) > 0)
					$amounts_WH3 = 1;
				
				$id_db_store_1 = $stores[$arWh["WH"]][$product_id]; // ID записи наличия по складу в Базе данных, для обновления
				$id_db_store_2 = $stores[$arWh["WH2"]][$product_id];
				$id_db_store_3 = $stores[$arWh["WH3"]][$product_id];
				$id_db_store_4 = $stores[$this->id_frc][$product_id];
			
				$responsive_wh[0] = RusklimatProduct::updateStoreAvailable($product_id, $arWh["WH"], $amounts[0], $id_db_store_1 );
				$responsive_wh[1] = RusklimatProduct::updateStoreAvailable($product_id, $arWh["WH2"], $amounts[1], $id_db_store_2 );
				$responsive_wh[2] = RusklimatProduct::updateStoreAvailable($product_id, $arWh["WH3"], $amounts_WH3, $id_db_store_3 );
				$responsive_wh[3] = RusklimatProduct::updateStoreAvailable($product_id, $this->id_frc, $amounts[2], $id_db_store_4 );
				
				foreach($responsive_wh as $r_wh){
					if($r_wh == 1 || is_int($r_wh))
						$this->setResult("Product ID [".$product_id."] update available!");
					else
						$this->setResult("ERROR: Product ID [".$product_id."] - not update", true);
				}
			}
		}
	}

	/*
	 * Основная функция обновления наличия товаров
	 */
    public function runExchange($showResult = false)
    {
		if(!empty($this->errors))
			return false;
		
		try
		{
			Debug::startTimeLabel("setGateWh");
			$this->setGateWh(); // получаем данные со шлюза
			Debug::endTimeLabel("setGateWh");
			
			Debug::startTimeLabel("setPropArray");
			$this->setPropArray(); // подготавливаем массивы для обновления
			Debug::endTimeLabel("setPropArray");
			
			Debug::startTimeLabel("updateWh");
			$this->updateWh(); // обновляем информацию по складам в ИБ
			Debug::endTimeLabel("updateWh");
			
			Debug::startTimeLabel("updateAvailable");
			$this->updateAvailable(); // обновляем информацию по наличию
			Debug::endTimeLabel("updateAvailable");
						
			
		} catch (Exception $e) {
			$this->setError($e->GetMessage());
		}
		
		// выводим время выполнения
		$this->showTimeline();
		
		if(!empty($this->errors))
			RusklimatMain::showAndWriteError($this->errors, "error.wh.txt");
		
		if($showResult)
			$this->showResult();
		
    }
}