Current Path : /home/bitrix/ext_www/dev.ballu.in.ua/import/ |
Current File : /home/bitrix/ext_www/dev.ballu.in.ua/import/.integration.functions.php |
<? function getCategoriesWithSortedCharacteristics(&$catalog) { $result = array(); foreach ($catalog['data'] as $string => $item) { $key = $item['ИдентификаторВБазе']; foreach ($item['ХарактеристикиНоменклатурыГруппы'] as $kk => $value) { if ($value['Титул'] == 'true') { if (!isset($result[$key])) { $result[$key] = array('Характеристика' => array()); } $result[$key]['Характеристика'][$value['Характеристика']['Идентификатор'] ?: $value['Характеристика']['ИдентификаторВБазе']] = $value['НомерТитула']; } } if (isset($result[$key])) { asort($result[$key]['Характеристика']); $result[$key]['строка'] = $string; $result[$key]['название'] = $item['ПолноеНаименование']; } } return $result; } function getCategoriesWithSortedCharacteristicsOnIBlock(&$result) { $rsResult = CIBlockSection::GetList(array("SORT" => "ASC"), array("IBLOCK_ID" => 18)); while($arSection = $rsResult -> GetNext()) { if (isset($result[$arSection['XML_ID']])){ $result[$arSection['XML_ID']]['ID']=$arSection['ID']; } } $arFilter = Array("IBLOCK_ID" => 16, 'ACTIVE' => 'Y'); $arSelect = ['ID', 'XML_ID']; $categories = array(); $res = \CIBlockElement::GetList(array(), $arFilter, false, false, $arSelect); while ($arElement = $res->Fetch()) { $categories[$arElement['XML_ID']] = $arElement['ID']; } foreach ($result as $key => $item) { $result[$key]['UF_ORDER_PARAMETERS'] = array(); foreach ($item['Характеристика'] as $k => $i) { $result[$key]['UF_ORDER_PARAMETERS'][$i] = $categories[$k]; } } return $result; } function saveCategories($tempCategory) { $CIBlockSection = new \CIBlockSection(); foreach($tempCategory as $code => $prop){ if ($prop['ID']){ $CIBlockSection->Update( $prop['ID'], array('UF_ORDER_PARAMETERS' => $prop['UF_ORDER_PARAMETERS']) ); echol( " done with UF_ORDER_PARAMETERS in " . $prop['название'] . "(" . $prop['ID'] . ") = " . json_encode($prop['UF_ORDER_PARAMETERS']) ); } } } function getRest1($address, $data=[], $method="GET"){ global $API_URL; global $API_ADDRESS; global $API_KEY; $service = $API_ADDRESS[$address]; $url = $API_URL.$service; //echo $url; $opts = array('http' => array( 'method' => $method, 'header' => "Authorization: ".$API_KEY, ) ); if(!empty($data) && $method!="GET"){ $opts['http']['content'] = http_build_query($data); }elseif(!empty($data) && $method=="GET"){ $toSend = http_build_query($data); $url.="?".$toSend; } echol($opts); echol($url); $context = stream_context_create($opts); $result = file_get_contents($url, false, $context); // !!!! TBD write responce log if($result!==false) $responce = json_decode($result, true); else $responce = "error"; return $responce; } function checkValForFile($val) { //73ad50bb-e69a-11e5-b14a-ac162d7b6f40 if(empty($val) || strlen($val)!=36) return false; if(substr_count($val, "-")==4) return true; return false; } function arFormatPrices($arIn){ foreach($arIn as $k=>$item){ $out[$item["Goods_ID"]][$item["PriceBush_ID"]]["norm"] = $item["Price"]; $out[$item["Goods_ID"]][$item["PriceBush_ID"]]["old"] = $item["PriceOLD"]; } return $out; } function updatePricePack($id=0,$arPrice = false){ if($id <= 0) return false; global $base_price; global $BASE_BUSH; global $priceConfig; if(empty($priceConfig)) $priceConfig = getPriceTypes(); if(!empty($arPrice)){ $boolResult = CPrice::DeleteByProduct($id); foreach($arPrice as $code => $price){ addProductPrice($id, $priceConfig[$code], $price); } if(!empty($arPrice[$BASE_BUSH])){ addProductPrice($id, "BASE", $arPrice[$BASE_BUSH]); addProductPrice($id, "DISCOUNT", $arPrice[$BASE_BUSH."_NODISCOUNT"]); } //echo "\n$id ".count($arPrice)." prices"; } return true; } function setBasePrice($id=0,$arPrice = false){ if($id <= 0) return false; global $base_price; global $BASE_BUSH; global $priceConfig; if(!empty($arPrice)){ echol($id." => ".$arPrice[$BASE_BUSH]); //echol($arPrice); checkCatalogable($id); $boolResult = CPrice::DeleteByProduct($id); addProductPrice($id, 1, $arPrice[$BASE_BUSH]); } return true; } function checkCatalogable($id){ if(CCatalogProduct::GetByID($id)==false){ $arFields = array( "ID" => $id, "CAN_BUY_ZERO" => "Y", "QUANTITY_TRACE" => "N", "CAN_BUY_ZERO" => "Y", "NEGATIVE_AMOUNT_TRACE" => "N" ); CCatalogProduct::Add($arFields); } } function addProductPrice($id, $code, $price){ if($price<=0) return; $arFields = Array( "PRODUCT_ID" => $id, "CATALOG_GROUP_ID" => $code, "PRICE" => $price, "CURRENCY" => "RUB", ); //echol($arFields); CPrice::Add($arFields); //echo "\nprice Updated"; } function startTimer($id="start"){ global $arTimers; $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $arTimers[$id] = $time; //echol($arTimers[$id]); } function stopTimer($id = "start"){ global $arTimers; $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $out = $arTimers["stopped"][$id] = $time - $arTimers[$id]; return $out; } function outTimer($id="start") { global $arTimers; return $arTimers["stopped"][$id]; } function outTimers() { global $arTimers; $artm = $arTimers["stopped"]; echol($artm); } if (!function_exists('_i')) { function _i($str){ //Родитель|SECTION_ID //ИдентификаторВБазе|ID //ПометкаУдаления|TO_DELETE //Код|CODE //Наименование|NAME //ПолноеНаименование|FULL_NAME //ВидКлассификатора|TYPE $trans = [ "Родитель"=>"SECTION_ID", "ИдентификаторВБазе"=>"ID", "Идентификатор" => "ID2", "ПометкаУдаления"=>"TO_DELETE", "Код"=>"NSI_CODE", "Наименование"=>"NAME", "ПолноеНаименование"=>"FULL_NAME", "НаименованиеПолное"=>"NAME_FULL", "МеждународноеСокращение" => "INTERNATIONAL_SHORTNAME", "ВидКлассификатора"=>"TYPE", "ТипХарактеристики"=>"PROPERTY_GROUP", "Описание"=>"DETAIL_TEXT", "ТипЗначения"=>"VALUE_TYPE", "ЕдиницаИзмерения"=>"MEASURE", "МножественныйВыбор"=>"MULTIPLE", "Порядок" => "SORT", "Характеристики" => "PROPERTIES", "ХарактеристикиНоменклатурыГруппы" => "ELEMENT_PROPERTIES", "Характеристика" => "PROPERTY", "Титул" => "TITUL", "НомерТитула" =>"TITUL_SORT", //товары "ПредварительнаяКарточка" => "TEMPORARY_ELEMENT", "ТипЗаказногоОборудования" => "PREORDER_TYPE", "Значение" => "VALUE", "ОсновнаяЕдиницаИзмерения" => "MAIN_MEASURE", "Артикул" => "ARTIKUL", "Марка" => "BRAND", "БазоваяЕИ" => "BASE_MEASURE", "ВидНоменклатуры" => "ELEMENT_TYPE", "ПродажаЗапрещена" => "AVAILABLE_TO_BUY", "ИспользоватьНаСайтах" => "WEB_ACTIVE", "РегистрацияНаСайтах" => "SITE_AVAILABLE", "СайтВладелец" => "SITE_ID", "Отображать" => "SHOW", "Категории" => "ELEMENT_CATEGORIES", "СтранаПроисхождения" => "COUNTRY_ORIGIN", "Категории" => "CATEGORIES", "Категория" => "CATEGORY", "КлассификацияДляСайтов" => "SECTION", "Группа" => "GROUP", "ТипЗаказногоОборудования" => "PREORDER_TYPE", // характеристики "ОбязательноеЗаполнение" => "REQUIRED_IN", "ХарактеристикиФильтров" => "FILTER_CATS_XML", "Диапазон" => "FILTER_N_CATS_XML", "КодНаСайте" => "CODE", ]; $transrev = array_flip($trans); if(isset($trans[$str])) return $trans[$str]; elseif(isset($transrev[$str])) return $transrev[$str]; else return false; } } function formatUnits($arIn){ foreach($arIn as $el){ $ar = [ "NAME" => $el[ _i("NAME_FULL") ], "ACTIVE" => ($el[ _i("TO_DELETE") ]=="false"?"Y":"N"), "XML_ID" => $el["_id"], "NSI_CODE" => $el[ _i("NSI_CODE") ], "SHORT_NAME" => $el[ _i("NAME") ], "INTERNATIONAL_SHORTNAME" => $el[ _i("INTERNATIONAL_SHORTNAME") ], "MEASURE_XML" => $el[ _i("MEASURE") ][ _i("ID") ], "REST" => $el ]; $out[ $ar["XML_ID"] ]=$ar; } return ($out); } function formatElements($arIn, $Props){ global $SITE_TYPE_XML_ID; foreach($arIn as $el){ $ar = [ "PROPERTY_NAME" => $el[ _i("NAME") ], "FULL_NAME" => $el[ _i("FULL_NAME") ], "TEMPORARY_ELEMENT" => $el[ _i("TEMPORARY_ELEMENT") ], "XML_ID" => $el["_id"], "NSI_CODE" => $el[ _i("NSI_CODE") ], "PREORDER" => ($el[ _i("PREORDER_TYPE") ]=="НеЗаказное")?"N":"Y", "ACTIVE" => ($el[ _i("TO_DELETE") ]=="false"?"Y":"N"), "AVAILABLE_TO_BUY" => ($el[ _i("AVAILABLE_TO_BUY") ]=="false"?"Y":"N"), "WEB_ACTIVE" => ($el[ _i("WEB_ACTIVE") ]=="true"?"Y":"N"), "ELEMENT_TYPE" => $el[ _i("ELEMENT_TYPE") ], "MEASURE" => $el[ _i("MEASURE") ][ _i("ID") ], "MAIN_MEASURE" => $el[ _i("MEASURE") ][ _i("ID") ], "BASE_MEASURE" => $el[ _i("BASE_MEASURE") ][ _i("ID") ], "BRAND" => $el[ _i("BRAND") ][ _i("ID") ], "ARTIKUL" => !is_array($el[ _i("ARTIKUL") ])?$el[ _i("ARTIKUL") ]:"", "COUNTRY_ORIGIN" => $el[ _i("COUNTRY_ORIGIN") ][ _i("ID") ], "REST" => $el ]; //unset($ar["REST"][_i("PROPERTIES")]); // обрабатываем мультипривязку к разделам-родителям if(!empty($el[_i("SECTION")][0])){ //echo "here\n"; foreach($el[_i("SECTION")] as $k=> $sec){ if($sec[ _i("TYPE") ][ _i("ID") ] == $SITE_TYPE_XML_ID) $ar["SECTION"] = [ "TYPE" => $el[ _i("SECTION") ][$k][ _i("TYPE") ][ _i("ID") ], "GROUP" => $el[ _i("SECTION") ][$k][ _i("GROUP") ][ _i("ID") ], ]; } }else{ $ar["SECTION"] = [ "TYPE" => $el[ _i("SECTION") ][ _i("TYPE") ][ _i("ID") ], "GROUP" => $el[ _i("SECTION") ][ _i("GROUP") ][ _i("ID") ], ]; } //обработка категорий if(is_array($el[_i("CATEGORIES")][1])) $cat = $el[_i("CATEGORIES")][count($el[_i("CATEGORIES")])-1][_i("CATEGORY")][_i("ID")]; else $cat = $el[_i("CATEGORIES")][_i("CATEGORY")][_i("ID")]; if(!empty($cat)) { //echol($cat); if($cat == "7270a0d0-8504-4fb8-babd-65eb489f0f2a") // новинка $ar["IS_NEW"]="Y"; elseif($cat=="5034bd5e-9c71-4040-94ec-d8238fed3ec3" || $cat=="3a4f493b-7960-4d14-97c8-aab2e134c549") // ликвидация или зачистка $ar["TO_KILL"]="Y"; //else $ar["CATEG"] = $cat; } foreach($el[_i("PROPERTIES")] as $k=>$prop){ if(is_array($prop[_i("VALUE")])){ $val = $prop[_i("VALUE")][_i("ID")]; }else $val = $prop[_i("VALUE")]; $ar["PROPERTIES"][ $prop[_i("PROPERTY")][_i("ID")] ] = $val; } // РЕгистрация на сайтах foreach($el[_i("SITE_AVAILABLE")] as $k=>$prop){ if(is_array($prop[_i("SITE_ID")])){ $ar["SITE_AVAILABLE"][ $prop[_i("SITE_ID")][_i("ID")] ] = $prop[_i("SHOW")]; } } if($el[_i("ELEMENT_TYPE")]!="Услуга") $out[$el["_id"]] = $ar; // $out["PROPERTIES"][ $ar["XML_ID"] ]=$ar; // $out["PROPERTIES"][ $ar["XML_ID"] ]["source"]=$el; // $pg = $el[_i("PROPERTY_GROUP")]; // if(!empty($pg[_i("NAME")])) // $out["PROPERTY_TYPES"][ $pg[_i("ID")] ]["DATA"] = [ // "NAME" => $pg[_i("NAME")], // "SORT" => $pg[_i("SORT")], // "CODE" => $pg[_i("CODE")], // "ID" => $pg[_i("ID")], // "ACTIVE" => ($pg[ _i("TO_DELETE") ]=="false"?"Y":"N"), // ]; // $out["PROPERTY_TYPES"][ $pg[_i("ID")] ]["LINK"][]=$el["_id"]; // $out["VALUE_TYPES"][$el[ _i("VALUE_TYPE") ]]+=1; } //echol(count($arIn)." __=__ ".count($out)); return ($out); } function formatProperty($arIn){ foreach($arIn as $el){ $ar = [ "NAME" => $el[ _i("NAME") ], "XML_ID" => $el["_id"], "NSI_CODE" => $el[ _i("NSI_CODE") ], "CODE" => $el[ _i("CODE") ], "ACTIVE" => ($el[ _i("TO_DELETE") ]=="false"?"Y":"N"), "GROUP_XML_ID" => $el[ _i("PROPERTY_GROUP") ][ _i("ID") ], "GROUP_SORT" => $el[ _i("PROPERTY_GROUP")][ _i("SORT")], "GROUP_NAME" => $el[_i("PROPERTY_GROUP")][_i("NAME")], "GROUP_CODE" => $el[_i("PROPERTY_GROUP")][_i("NSI_CODE")], "GROUP_ACTIVE" => ($el[_i("PROPERTY_GROUP")][ _i("TO_DELETE") ]||empty($el[_i("PROPERTY_GROUP")][ _i("TO_DELETE") ])=="false"?"Y":"N"), "VALUE_TYPE" => $el[ _i("VALUE_TYPE") ], "MULTIPLE" => ($el[ _i("MULTIPLE") ]=="false"?"N":"Y"), "DETAIL_TEXT" => $el[ _i("DETAIL_TEXT") ], "MEASURE_XML" => $el[ _i("MEASURE") ][ _i("ID") ], "REST" => $el ]; $out["PROPERTIES"][ $ar["XML_ID"] ]=$ar; //$out["PROPERTIES"][ $ar["XML_ID"] ]["source"]=$el; $pg = $el[_i("PROPERTY_GROUP")]; if(!empty($pg[_i("NAME")])) $out["PROPERTY_TYPES"][ $pg[_i("ID")] ]["DATA"] = [ "NAME" => $pg[_i("NAME")], "SORT" => $pg[_i("SORT")], "NSI_CODE" => $pg[_i("NSI_CODE")], "XML_ID" => $pg[_i("ID")], "ACTIVE" => ($pg[ _i("TO_DELETE") ]=="false"?"Y":"N"), ]; $out["PROPERTY_TYPES"][ $pg[_i("ID")] ]["LINK"][]=$ar["NAME"];//$el["_id"]; $out["VALUE_TYPES"][$el[ _i("VALUE_TYPE") ]]+=1; } return ($out); } function mergePropsWithCatalog($arIn){ if(empty($arIn)) return false; foreach($arIn as $k=>$prop){ if(empty($prop["FROM_CATALOG"])) continue; $mprop = $prop["FROM_CATALOG"]; unset($arIn[$k]["FROM_CATALOG"]); foreach(["FILTER_CATS_XML","TILE_CATS_XML","FILTER_N_CATS_XML"] as $key){ if(!empty($mprop[$key])) $arIn[$k][$key] = $mprop[$key]; } foreach(["XML_ID","NAME","MEASURE","ACTIVE","VALUE_TYPE","NSI_CODE","GROUP_XML_ID"] as $key){ if(empty($prop[$key]) && !empty($mprop[$key])) $arIn[$k][$key] = $mprop[$key];; } } return $arIn; } function setPropertiesCode($arIn) { foreach($arIn as $k=>$prop){ if(!empty($prop["CODE"])){ $prop["CODE"] = str_replace(".", "_", $prop["CODE"]); if (substr($prop["CODE"], 0, 2) == '3d') { $prop["CODE"] = 'prop_'.$prop["CODE"]; $prop["FILE_TYPE"] = ''; } }elseif(!empty($prop["NSI_CODE"])){ if(!empty($prop["FILTER_CATS_XML"])) $prop["CODE"] = "filter_".$prop["NSI_CODE"]; else $prop["CODE"] = "prop_".$prop["NSI_CODE"]; } $arIn[$k] = $prop; } return $arIn; } // -------------------------------- CATALOG---------------------------- function formatCatalog($arIn, $searchType=false){ $out =[]; foreach($arIn as $el){ //echol( $el[ _i("ID") ] ); $xmlid = $el[ _i("ID") ]; $ar = [ "NAME" => $el[ _i("NAME") ], "ACTIVE" => (($el[ _i("TO_DELETE") ]=="false")?"Y":"N"), "SECTION_ID" => $el[ _i("SECTION_ID") ][ _i("ID") ], "TYPE" => $el[ _i("TYPE") ][ _i("ID") ], "NSI_CODE" => $el[ _i("NSI_CODE") ], "REST" => $el ]; //echol($ar); //unset($ar["REST"]); if($searchType!=false) { if( $ar["TYPE"] != $searchType ){ continue; } else { $par = $ar["SECTION_ID"]; $out["PARENTS"][(empty($par)?"root":$par)][]=$xmlid; //echol($xmlid." -> ".$ar["NSI_CODE"]." == ".$ar["SECTION_ID"]); //if($xmlid == "5a9a4410-5149-459c-a974-e8b3f1f6c5f0") echol($el); //if(empty($par)) echol($el); } } foreach($el[_i("ELEMENT_PROPERTIES")] as $k => $prop){ if(!empty($prop[_i("PROPERTY")][_i("ID2")])) $idp = $prop[_i("PROPERTY")][_i("ID2")]; else $idp = $prop[_i("PROPERTY")][_i("ID")]; $arProp = [ "XML_ID" => $idp, "NAME" => $prop[_i("NAME")], "MEASURE_XML" => $prop[_i("PROPERTY")][_i("MEASURE")][_i("ID")], "ACTIVE" => (($prop[_i("PROPERTY")][ _i("TO_DELETE") ]=="false")?"Y":"N"), "VALUE_TYPE" => $prop[_i("PROPERTY")][_i("VALUE_TYPE")], "NSI_CODE" => $prop[_i("PROPERTY")][_i("NSI_CODE")], "GROUP_XML_ID" => $prop[_i("PROPERTY")][_i("PROPERTY_GROUP")][_i("ID")], //"REST" => $prop ]; if(empty($out["PROPERTIES"][$idp])) $out["PROPERTIES"][$idp] = $arProp; if(!empty($prop[_i("TITUL")]) && $prop[_i("TITUL")]=="true") $out["PROPERTIES"][$idp]["TILE_CATS_XML"][$xmlid]= $prop[_i("TITUL_SORT")]; if(!empty($prop[_i("REQUIRED_IN")]) && $prop[_i("REQUIRED_IN")]=="true") $out["PROPERTIES"][$idp]["REQUIRED_IN"][]=$xmlid; if(!empty($prop[_i("FILTER_N_CATS_XML")]) && $prop[_i("FILTER_N_CATS_XML")]=="true") $out["PROPERTIES"][$idp]["FILTER_N_CATS_XML"][$xmlid]+=1; if(!empty($prop[_i("FILTER_CATS_XML")]) && $prop[_i("FILTER_CATS_XML")]=="true") $out["PROPERTIES"][$idp]["FILTER_CATS_XML"][$xmlid]+=1; /*$ar["EL_PROPS"][]=[ "XML_ID" => $idp, "NAME" => $prop[_i("NAME")], "TITUL" => $prop[_i("TITUL")], "TITUL_SORT" => $prop[_i("TITUL_SORT")], ];*/ //if(empty($idp)) echol($prop); //else echol($prop); } foreach($el[_i("PROPERTIES")] as $k => $prop){ //if(!empty($prop[_i("NAME")])) $ar["PROPS"][]= $prop[_i("PROPERTY")][_i("ID")]; //крупногабарит if( $prop[_i("PROPERTY")][_i("ID")] =="2cbcf88a-ab09-11e6-be4f-ac162d7b6f40" && $prop[_i("VALUE")] == "Да" ) $ar["KGT"]="1"; else $ar["KGT"]="0"; $out["GROUP_PROPERTIES"][$prop[_i("PROPERTY")][_i("ID")]]+=1; } if(is_array($ar)){ $out["TYPES"][$ar["TYPE"]] +=1; $out["BY_XML"][ $xmlid ] = $ar; } } return $out; } function findLevel($arParents){ $arIn = [ "DATA" => $arParents, "LEVELS" => [ 1 => $arParents["root"]] ]; //echol("123"); $depth=0; do{ $depth++; $children = $arIn["LEVELS"][$depth]; foreach($children as $child){ if(!empty($arIn["DATA"][$child])) foreach($arIn["DATA"][$child] as $ch2) $arIn["LEVELS"][$depth+1][]=$ch2; } }while(!empty($arIn["LEVELS"][$depth])); return $arIn["LEVELS"]; } function LoadSections($arData, $arLevels){ global $IBLOCK; global $bs; global $UNSET_PARENT_ON_UPDATE; $arSections = getSectionList($IBLOCK, "all", "Y", false); foreach($arSections as $k=>$secAr){ if($secAr["XML_ID"]!="") $Sections[$secAr["XML_ID"]] = $secAr["ID"]; } //echol($Sections); //echol($arLevels); unset ($Sections[""]); $arparams = [ "max_len" => 200, "change_case" => "U", "replace_space" => "_", "replace_other" => "", "delete_repeat_replace" => true ]; foreach($arLevels as $depth => $sections){ //echol ("here"); foreach($sections as $section) if(!empty($arData[$section])) { // сделаем загрузку $id = $section; $sec = $arData[$id]; $arFields = formatSectionForLoad($sec, $Sections[$sec["SECTION_ID"]]); echol($id."___".$sec["SECTION_ID"]." +++ ".$Sections[$sec["SECTION_ID"]]); $arFields["XML_ID"] = $id; $arFields["EXTERNAL_ID"] = $id; if(empty($Sections[$id])) { // add $arFields["CODE"] = Cutil::translit($arFields["NAME"],"ru",$arParams); $ID = $bs->Add($arFields); $Sections[$id] = $ID; $res = ($ID>0); echol("added $ID"); } else { //UPDATE $ID = $Sections[$id]; echol($arFields); if($UNSET_PARENT_ON_UPDATE == true) unset($arFields["IBLOCK_SECTION_ID"]); // костыль на zzz для home-comfort if( $arFields["XML_ID"]=="dc419151-5c4b-4ddc-9b88-62b0761599fa" || $arFields["XML_ID"]=="e5d64653-253e-4193-bbbe-fcbd5d79ab36" ) $arFields["ACTIVE"]="N"; $res = $bs->Update($ID, $arFields); echol("updated $ID"); $Sections[$id] = $ID; } if(!$res) echo $bs->LAST_ERROR; } } CIBlockSection::ReSort($IBLOCK); } function formatSectionForLoad($arSec, $SECTION_ID) { global $IBLOCK; //echol($arSec); //$bs = new CIBlockSection; if(empty($SECTION_ID)) $SECTION_ID = "false"; $arFields = Array( "ACTIVE" => $arSec["ACTIVE"], "IBLOCK_SECTION_ID" => $SECTION_ID, "IBLOCK_ID" => $IBLOCK, "NAME" => $arSec["NAME"], "UF_NSI_CODE" => $arSec["NSI_CODE"] ); //if($SECTION_ID=="false")echol($arFields); return $arFields; } // -------------------------- /CATALOG ------------------------------ function leaveActiveElements($arIn, $arSearch) { global $SITE_TO_SHOW_XML_ID; $activeEls = array_keys($arSearch); foreach($arIn as $k => $el){ if(is_set($arSearch[$k])){ $out["TO_UPDATE"][$k]=$el; }elseif($el["SITE_AVAILABLE"][$SITE_TO_SHOW_XML_ID]=="true"){ $out["TO_ADD"][$k]=$el; }else{ $out["LOST"][$k]="true"; } } return $out; } function echopart($arIn, $limit=10, $offset=0){ $cnt = count($arIn); $keys = array_keys($arIn); for($i=0; ($i<$limit+$offset && $i<$cnt); $i++){ if(!empty($keys[$i])&& $i>$offset){ $out[$keys[$i]] = $arIn[$keys[$i]]; } if($i>($limit+$offset)) break; } echol($out); } function CheckCanBuy($arIn) { foreach($arIn as $k => $el){ if($el["WEB_ACTIVE"]=="Y" && $el["ACTIVE"]=="Y" && $el["AVAILABLE_TO_BUY"]=="Y"){ $el["GLOBAL_AVAILABLE"]="Y"; }else { $el["GLOBAL_AVAILABLE"]="N"; //echol($el); } $arIn[$k]=$el; } return $arIn; } function countActive($arIn){ foreach($arIn as $k=>$el){ foreach(["ACTIVE","AVAILABLE_TO_BUY","WEB_ACTIVE","GLOBAL_AVAILABLE"] as $key){ if($el[$key]=="Y") $arOut[$key]+=1; elseif($el[$key]=="N") $arOut["NOT_".$key]+=1; elseif(empty($el[$key])) $arOut["EMPTY_".$key] +=1; } } return $arOut; } function mergeProductSection($arIn,$arSections) { foreach($arIn as $k=>$el){ if(!empty($el["SECTION"]["GROUP"])) $el["SECTION"]["PARENT"] = $arSections["BY_XML"][$el["SECTION"]["GROUP"]]; $out[$k] = $el; } return $out; } function checkSections($arIn){ foreach($arIn as $k=>$el){ if(empty($el["SECTION"])){ $arOut["EMPTY_SECTIONS"]+=1; $arOut["skip"][]=$k; } elseif(empty($el["SECTION"]["GROUP"])) { $arOut["EMPTY_GROUPS"]+=1; $arOut["EMPTY_GROUP"][$el["NSI_CODE"]]+=1; $arOut["skip"][]=$k; } elseif(empty($el["SECTION"]["PARENT"])){ $arOut["EMPTY_PARENT"]+=1; $arOut["NOT_FOUND"][]=$el["SECTION"]["GROUP"]; $arOut["skip"][]=$k; } } return $arOut; } function mergeElementProps($arEls, $arProps){ foreach($arEls as $el){ foreach($el["PROPERTIES"] as $pid => $pval){ if(empty($arProps["PROPERTIES"][$pid])) $out["LOST"][$pid] = $pval; elseif(!empty($pval)){ $pr = $arProps["PROPERTIES"][$pid]; $out[$pid]["DATA"] = $pr; $out[$pid]["VALUES"][$pval] += 1; if($pr["VALUE_TYPE"]=="Файл") { } } } } //echopart($arProps["PROPERTIES"]); // [2c3526d5-637f-11e5-b5fc-ac162d7b6f40] => Array // ( // [NAME] => 3D изображение_2 // [XML_ID] => 2c3526d5-637f-11e5-b5fc-ac162d7b6f40 // [NSI_CODE] => 00158 // [ACTIVE] => Y // [PROPERTY_GROUP] => ee550ddb-6379-11e5-b5fc-ac162d7b6f40 // [VALUE_TYPE] => Файл // [MULTIPLE] => N // [DETAIL_TEXT] => Array // ( // ) // [MEASURE] => // [source] => Array // ( // [_id] => 2c3526d5-637f-11e5-b5fc-ac162d7b6f40 // [ПометкаУдаления] => false // [Код] => 00158 // [Наименование] => 3D изображение_2 // [ТипЗначения] => Файл // [Описание] => Array // ( // ) // [КодНаСайте] => 3d_2_ru.new // [МножественныйВыбор] => false // [ТипХарактеристики] => Array // ( // [@xsi:type] => d5p1:ПередаваемаяЗапись // [ИдентификаторВБазе] => ee550ddb-6379-11e5-b5fc-ac162d7b6f40 // ) // ) // ) return $out; } function preparePropsLoad($arIn){ global $PROPS_GROUPER_IBLOCK_ID; global $PROPERTIES_IBLOCK_ID; global $IBLOCK; global $MEASURES_IBLOCK; //get Config $arList = getPropsList(); foreach($arList as $pr){ if($pr["XML_ID"]!=""){ $out[$pr["XML_ID"]] = $pr; } } $arList = $out; $arKeys = array_keys($arList); $arIBList = allElements( $PROPERTIES_IBLOCK_ID, array("ID","NAME","XML_ID","PROPERTY_TILE_CATS_XML","PROPERTY_FILTER_CATS_XML","PROPERTY_FILTER_N_CATS_XML","PROPERTY_MEASURE_XML"), "XML_ID"); $arIBList = cleanTilda($arIBList); $ibkeys = array_keys($arIBList); //echol($arIBList); // получить подсказки // !!! сначала должен быть загружен список единиц измерения в инфоблок $MEASURES_IBLOCK $arIBUnits = allElements( $MEASURES_IBLOCK, array("ID","NAME","XML_ID", "ACTIVE","PROPERTY_SHORT_NAME"), "XML_ID"); //echol($arIBUnits); $arIBGroups = allElements( $PROPS_GROUPER_IBLOCK_ID, array("ID","NAME","XML_ID"), "XML_ID"); foreach($arIn as $id => $prop){ if(!empty($prop["GROUP_XML_ID"])) $Groups[$prop["GROUP_XML_ID"]] = parseGroupInfo($prop, $Groups[$prop["GROUP_XML_ID"]]); $Groups[$prop["GROUP_XML_ID"]]["IBLOCK_ID"] = $PROPS_GROUPER_IBLOCK_ID; if(!empty($arIBGroups[$prop["GROUP_XML_ID"]])) $Groups[$prop["GROUP_XML_ID"]]["ID"] = $arIBGroups[$prop["GROUP_XML_ID"]]["ID"]; //echol($prop); // Готовим к загрузке в инфоблок со связями $outIblock = [ "NAME" => $prop["NAME"], "XML_ID" => $prop["XML_ID"], "CODE" => $prop["CODE"], "ACTIVE" => $prop["ACTIVE"], "IBLOCK_ID" => $PROPERTIES_IBLOCK_ID, "PROPERTY_VALUES" => ["MEASURE_XML" => $prop["MEASURE_XML"] ] ]; // if(!empty($prop["TILE_CATS_XML"])) { // $outIblock["PROPERTY_VALUES"]["TILE_CATS_XML"] = $prop["TILE_CATS_XML"]; // $outIblock["PROPERTY_VALUES"]["TILE"] = "Y"; // } if(!empty($prop["TILE_CATS_XML"]) && ($prop["TILE_CATS_XML"] != "false")) foreach($prop["TILE_CATS_XML"] as $val => $c) $outIblock["PROPERTY_VALUES"]["TILE_CATS_XML"][] = $val; else $outIblock["PROPERTY_VALUES"]["TILE_CATS_XML"] = array(); if(!empty($prop["FILTER_CATS_XML"])) foreach($prop["FILTER_CATS_XML"] as $val => $c) $outIblock["PROPERTY_VALUES"]["FILTER_CATS_XML"][] = $val; else $outIblock["PROPERTY_VALUES"]["FILTER_CATS_XML"] = array(); if(!empty($prop["FILTER_N_CATS_XML"])) foreach($prop["FILTER_N_CATS_XML"] as $val => $c) $outIblock["PROPERTY_VALUES"]["FILTER_N_CATS_XML"][] = $val; else $outIblock["PROPERTY_VALUES"]["FILTER_N_CATS_XML"] = array(); /*if($prop["XML_ID"]=="fcb88ca0-6103-11e5-b5fc-ac162d7b6f40"){ echol($outIblock); }*/ // Поля для свойсва $arFields = Array( "NAME" => $prop["NAME"], "ACTIVE" => $prop["ACTIVE"], "SORT" => ($prop["SORT"]>0)? $prop["SORT"]:100, "CODE" => $prop["CODE"], "XML_ID" => $id, //"HINT" => $param['edinicaIzmereniya']['Наименование'], "COL_COUNT" => "50", "FILTRABLE" => "Y", "PROPERTY_TYPE" => "S", "DISPLAY_TYPE"=>"F", "USER_TYPE" => "", "IBLOCK_ID" => $IBLOCK, "HINT" => $arIBUnits[ $prop["MEASURE_XML"] ]["PROPERTY_SHORT_NAME_VALUE"], ); $arFields2=""; // Проверяем тип свойства if(!empty($prop["FILTER_CATS_XML"])){ $arFields['SMART_FILTER']="Y"; /*if (!empty($prop["FILTER_N_CATS_XML"])) { $prop['DISPLAY_TYPE']='A'; $prop['PROPERTY_TYPE']='N'; }*/ }else{ $arFields['SMART_FILTER']="N"; } //echol($prop["VALUE_TYPE"]); if ($prop['VALUE_TYPE'] == 'Число') { $arFields2=$arFields; $arFields2['CODE'].='_n'; $arFields2['XML_ID'].='-n'; $arFields2['DISPLAY_TYPE']='A'; $arFields2['PROPERTY_TYPE']='N'; } if($prop["VALUE_TYPE"]=="Файл"){ $arFields["PROPERTY_TYPE"]="F"; $arFields["PROPERTY_TYPE"] = 'F'; $arFields["FILE_TYPE"] = ''; $arFields["FILTRABLE"] = 'N'; } // Проверим наличие свойства в инфоблоке свойств if(in_array($id, $ibkeys)){ $cnt3++; $outIblock["ID"] = $arIBList[$id]["ID"]; $arOut["IBLOCK"]["TO_UPDATE"][]=$outIblock; }else{ $cnt4++; $arOut["IBLOCK"]["TO_ADD"][]=$outIblock; } // Проверяем наличие свойства в инфоблоке товаров if(in_array($id, $arKeys)){ $arFields["ID"] = $arList[$id]["ID"]; $arOut["PROPERTIES"]["TO_UPDATE"][]=$arFields; $cnt++; }else{ $arOut["PROPERTIES"]["TO_ADD"][]=$arFields; $cnt2++; } if(in_array($id."-n", $arKeys)&& !empty($arFields2)){ $arFields2["ID"] = $arList[$id."-n"]["ID"]; $arOut["PROPERTIES"]["TO_UPDATE"][]=$arFields2; $cnt5++; }elseif(!empty($arFields2)){ $arOut["PROPERTIES"]["TO_ADD"][]=$arFields2; $cnt6++; } } $arOut["GROUPS"] = $Groups; echol("===$cnt==$cnt2=---$cnt3--$cnt4---$cnt5....$cnt6.."); //echol($arOut); return $arOut; } function parseGroupInfo($prop, $out) { global $PROPS_GROUPER_IBLOCK_ID; $id = $prop["GROUP_XML_ID"]; if(!empty($prop["GROUP_NAME"])) $out["NAME"] = $prop["GROUP_NAME"]; if(!empty($prop["GROUP_XML_ID"])) $out["XML_ID"] = $prop["GROUP_XML_ID"]; if(!empty($prop["GROUP_SORT"])) $out["SORT"] = $prop["GROUP_SORT"]; if(!empty($prop["GROUP_ACTIVE"])&& !empty($prop["GROUP_NAME"])) $out["ACTIVE"] = $prop["GROUP_ACTIVE"]; $out["IBLOCK_ID"] = $PROPS_GROUPER_IBLOCK_ID; $out["PROPERTY_VALUES"]["PROPS"][]=$prop["XML_ID"]; //if(!empty($prop["GROUP_NAME"])) $out[$id]["NAME"] = $prop["GROUP_NAME"]; // $out[$prop["GROUP_XML_ID"]] = [ // "XML_ID" => $prop["GROUP_XML_ID"], // "NAME" => $prop["GROUP_NAME"], // "SORT" => $prop["GROUP_SORT"], // "UF_CAT_CODE" => $prop["GROUP_CODE"], // "ACTIVE" => $prop["GROUP_ACTIVE"] // ]; return $out; } /*////////////////////////// $times=array( 'start'=>date('Y-m-d H:i:s'), 'stop'=>''); $errors=array(); $counts=array( 'Added'=>0, 'Added_n'=>0, 'Updated'=>0, 'Updated_n'=>0, 'Deleted'=>0, 'Error'=>0, 'Error_n'=>0 ); $data=CParser::GetDataFromTable($parser_id."_".$_REQUEST['get'],array(),array()); //CParser::AddDataTable('items_har',array('XML_ID','CODE')); $arParams=array(); while ($arParam=$data->GetNext()) { foreach ($arParam as $k => $v) { if(isJSON($arParam['~'.$k])){ $arParam[$k]=json_decode($arParam['~'.$k],true); } } $arParams[]=$arParam; } $filter_arr=array('103a479e-6104-11e5-b5fc-ac162d7b6f40'); CModule::IncludeModule('iblock'); $arFilter = Array("IBLOCK_ID"=>$arConfig['CATALOG_PROPS_ID']); $arSelect = Array("ID", "NAME", "CODE", "XML_ID"); $res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect); while($arFields = $res->Fetch()) { $made_els[$arFields['XML_ID']] = $arFields['ID']; $made_els_left[$arFields['XML_ID']] = $arFields['ID']; $made_els_codes[$arFields['CODE']] = $arFields['ID']; } $prop_list = []; $properties = CIBlockProperty::GetList(Array("sort"=>"asc", "name"=>"asc"), Array("IBLOCK_ID"=>$arConfig['CATALOG_IBLOCK_ID'])); while ($prop_fields = $properties->GetNext()) { if ($prop_fields["SORT"] < 100) { continue; } $prop_list[$prop_fields['CODE']] = $prop_fields; } $SORT=100; foreach ($arParams as $key => $param) { $param['КодНаСайте'] = preg_replace('/[\.\s\t]/ui', '_', $param['КодНаСайте']); if ($param['КодНаСайте'] == '') { if($param['ХарактеристикиФильтров']==1||in_array($param['Идентификатор'],$filter_arr)){ $param['КодНаСайте'] = 'filter_'.$param['Код']; }else{ $param['КодНаСайте'] = 'prop_'.$param['Код']; } } $param['КодНаСайте'] = preg_replace('/[\s\t\.]+/ui', '', $param['КодНаСайте']); $arFields = Array( "NAME" => $param['~Наименование'], "ACTIVE" => $param['ПометкаУдаления'] == 0 ? "Y" : "N", "SORT" => $SORT, "CODE" => $param['КодНаСайте'], "XML_ID" => $param['Идентификатор'], "HINT" => $param['edinicaIzmereniya']['Наименование'], "COL_COUNT" => "50", "FILTRABLE" => "Y", "PROPERTY_TYPE" => "S", "DISPLAY_TYPE"=>"F", "USER_TYPE" => "", "IBLOCK_ID" => $arConfig['CATALOG_IBLOCK_ID'], ); $arFields2=false; $arLoadProductArray = Array( "NAME" => $param['~Наименование'], "ACTIVE" => $param['ПометкаУдаления'] == 0 ? "Y" : "N", "SORT" => $param['НомерТитула'], "CODE" => $param['КодНаСайте'], "XML_ID" => $param['Идентификатор'], "IBLOCK_ID" => $arConfig['CATALOG_PROPS_ID'], ); if ($param['ТипЗначения'] == 'Изображения') { $arFields["PROPERTY_TYPE"] = 'F'; $arFields["FILE_TYPE"] = 'jpg, gif, bmp, png, jpeg'; $arFields["FILTRABLE"] = 'N'; } elseif ($param['ТипЗначения'] == 'Файл') { $arFields["PROPERTY_TYPE"] = 'F'; $arFields["FILE_TYPE"] = ''; $arFields["FILTRABLE"] = 'N'; } elseif ($param['КодНаСайте'] == 'seo_title' || $param['КодНаСайте'] == 'seo_key' || $param['КодНаСайте'] == 'seo_descr') { $arFields["ROW_COUNT"] = '3'; }else{ } if($param['ХарактеристикиФильтров']==1||in_array($param['Идентификатор'],$filter_arr)){ $arFields['SMART_FILTER']="Y"; if ($param['ТипЗначения'] == 'Число') { $arFields2=$arFields; $arFields2['CODE'].='_n'; $arFields2['XML_ID'].='-n'; $arFields2['DISPLAY_TYPE']='A'; $arFields2['PROPERTY_TYPE']='N'; } /*if ($param['Диапазон'] == 1) { $arFields['DISPLAY_TYPE']='A'; $arFields['PROPERTY_TYPE']='N'; }*//* }else{ $arFields['SMART_FILTER']="N"; } if (substr($arFields["CODE"], 0, 2) == '3d') { $arFields["CODE"] = 'prop_'.$arFields["CODE"]; $arFields["FILE_TYPE"] = ''; } $elp = new CIBlockProperty; $el = new CIBlockElement; if (!isset($prop_list[$arFields["CODE"]])) { if($PRODUCT_ID = $elp->Add($arFields)) { $counts['Added']++; } else { $counts['Error']++; $errors[]="Error prop add: ".$elp->LAST_ERROR; } } else { if($elp->Update($prop_list[$arFields["CODE"]]['ID'], $arFields)){ $counts['Updated']++; }else{ $counts['Error']++; $errors[]="Error prop update: ".$elp->LAST_ERROR; } } if(is_array($arFields2)){ $elp = new CIBlockProperty; if (!isset($prop_list[$arFields2["CODE"]])) { if($PRODUCT_ID = $elp->Add($arFields2)) { $counts['Added_n']++; } else { $counts['Error_n']++; $errors[]="Error prop add: ".$elp->LAST_ERROR; } } else { if($elp->Update($prop_list[$arFields2["CODE"]]['ID'], $arFields2)){ $counts['Updated_n']++; }else{ $counts['Error_n']++; $errors[]="Error prop update: ".$elp->LAST_ERROR; } } } if (!isset($made_els[$param['Идентификатор']])) { if($PRODUCT_ID = $el->Add($arLoadProductArray, false, false, false)) { $made_els[$arLoadProductArray['CODE']] = $PRODUCT_ID; $made_els_codes[$param['Идентификатор']] = $PRODUCT_ID; } else { $counts['Error']++; $errors[]=$el->LAST_ERROR; } }else{ if($el->Update($made_els_left[$param['Идентификатор']], $arLoadProductArray)){ } else { $counts['Error']++; $errors[]=$el->LAST_ERROR; } unset($made_els_left[$param['Идентификатор']]); } if($param['Титул']==1){ CIBlockElement::SetPropertyValuesEx($made_els[$param['Идентификатор']],$arConfig['CATALOG_PROPS_ID'],array('TILE'=>100)); }else{ CIBlockElement::SetPropertyValuesEx($made_els[$param['Идентификатор']],$arConfig['CATALOG_PROPS_ID'],array('TILE'=>false)); } unset($prop_list[$arFields["CODE"]]); if(is_array($arFields2)){ unset($prop_list[$arFields2["CODE"]]); } $SORT += 1; } foreach($made_els_left as $key=>$left_good_id){ CIBlockElement::Delete($left_good_id); } //p($prop_list); foreach ($prop_list as $k => $v) { CIBlockProperty::Delete($v['ID']); $counts['Deleted']++; } $times['stop']=date('Y-m-d H:i:s'); p($counts); p($errors); p($times); CParser::AddLog($params_parser_id,'PropertiesImport',array('MESSAGE'=>'Импорт свойств','DATA'=>json_encode(array('times'=>$times,'counts'=>$counts,'errors'=>$errors)))); if($counts['Added']>0||$counts['Deleted']>0||$counts['Added_n']>0){ $times=array( 'start'=>date('Y-m-d H:i:s'), 'stop'=>''); $errors=array(); $counts=array(); $index = \Bitrix\Iblock\PropertyIndex\Manager::createIndexer($arConfig['CATALOG_IBLOCK_ID']); $index->startIndex(); $index->continueIndex(0); // создание без ограничения по времени $index->endIndex(); $times['stop']=date('Y-m-d H:i:s'); CParser::AddLog($params_parser_id,'IndexRecreateImport',array('MESSAGE'=>'Пересоздание фасетного индекса','DATA'=>json_encode(array('times'=>$times,'counts'=>$counts,'errors'=>$errors)))); } break;*/ function MakeLoadReady($arIn){ global $el; global $GLOBALTEST; global $SILENTPROPS; global $IBLOCK; foreach($arIn as $k => $arLoad){ if(!empty($arLoad["DETAIL_TEXT"])) $arLoad["DETAIL_TEXT_TYPE"] = "html"; //$res = UpdateProduct($ELID, $arLoad, true); if(!empty($arLoad["NAME"])){ if(!empty($arLoad["ID"])) { $ELID = $arLoad["ID"]; unset($arLoad["ID"]); echo "\nto update $ELID"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } if($GLOBALTEST != true){ $res = UpdateProduct($ELID, $arLoad, true); checkCatalogable($ELID); } } elseif($GLOBALTEST == true){ echo "\nTo add element"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } } else { if( $ELID = $el->Add($arLoad, false, true, true) ){ checkCatalogable($ELID); echo "\nAdded $ELID"; if($SILENTPROPS != true) { echo " with \n "; echol($arLoad); } } else echo "Error: ".$el->LAST_ERROR; } } } //CIBlockSection::ReSort($IBLOCK); } function MakeLoadReadyProps($arIn){ global $ibp; global $GLOBALTEST; global $SILENTPROPS; global $IBLOCK; foreach($arIn as $code => $prop){ if(!empty($prop["ID"])){ // Обновляем существующее свойство $PropID = $id = $prop["ID"]; unset($prop["ID"]); //echol($arUp); $res = $ibp->Update($id, $prop); }elseif(!empty($prop)){ $PropID = $ibp->Add($prop); } echol(" done with $PropID = ".$prop["NAME"]); } } function setStoreProduct($id, $store, $amount, $arStore) { global $SILENTPROPS; $arFields = Array( "PRODUCT_ID" => $id, "STORE_ID" => $store, "AMOUNT" => $amount ); if(!empty($arStore[$id])) { $loadid = $arStore[$id]; $ID = CCatalogStoreProduct::Update($loadid, $arFields); if($SILENTPROPS != "true") echol("upd $loadid "); } else { $ID = CCatalogStoreProduct::Add($arFields); if($SILENTPROPS != "true") echol("added $ID "); } return $ID; } function getElementStores($id,$store_id=""){ $arFilter = array('PRODUCT_ID' =>$id); if(!empty($store_id)) $arFilter["STORE_ID"] = $store_id; $rsStore = CCatalogStoreProduct::GetList(array(), $arFilter, false, false, array()); while ($arStore = $rsStore->Fetch()){ $out[]=$arStore; } return $out; } ?>