diff --git a/CHANGELOG.md b/CHANGELOG.md index c0320a4e..bbe4e718 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2015-05-18 v.1.1.2 +* Добавлена возможность изменять файлы основных классов(ICMLLoader и ICrmOrderActions) и экспорт каталога без потери обновлений +* Исправлены мелкие ошибки ## 2015-03-19 v.1.1.1 * Исправлена ошибка, связанная с версионностью PHP в History. * Добавлена выгрузка закупочной цены вместе с заказом diff --git a/intaro.intarocrm/classes/general/ICMLLoader.php b/intaro.intarocrm/classes/general/ICMLLoader.php index 24eba372..4116d52a 100644 --- a/intaro.intarocrm/classes/general/ICMLLoader.php +++ b/intaro.intarocrm/classes/general/ICMLLoader.php @@ -1,542 +1,546 @@ 1, // 1 mm = 1 mm - 'cm' => 10, // 1 cm = 10 mm - 'm' => 1000, - 'mg' => 0.001, // 0.001 g = 1 mg - 'g' => 1, - 'kg' => 1000, - ); - - protected $measurementLink = array ( - 'mm' => 'mm', - 'cm' => 'mm', - 'm' => 'mm', - 'mg' => 'g', - 'g' => 'g', - 'kg' => 'g', - ); - - public function Load() - { - global $USER; - if(!isset($_SESSION["SESS_AUTH"]["USER_ID"]) || !$_SESSION["SESS_AUTH"]["USER_ID"]) - $USER = new CUser; - - $this->isLogged = true; - - $defaultSite = CSite::GetList($by="def", $order="desc", Array())->Fetch(); - $this->encodingDefault = $defaultSite["CHARSET"]; - - $this->PrepareSettings(); - - $this->fp = $this->PrepareFile($this->filename. '.tmp'); - - if ($this->isLogged) { - $this->fpLog = $this->PrepareFile($this->logFile); - $this->WriteLog("Start Loading"); - } - - $this->PreWriteCatalog(); - - $categories = $this->GetCategories(); - - $this->WriteCategories($categories); - - $this->PreWriteOffers(); - $this->BuildOffers($categories); - $this->PostWriteOffers(); - - $this->PostWriteCatalog(); - - if ($this->isLogged) { - $this->WriteLog("Loading was ended successfully (peek memory usage: " . memory_get_peak_usage() . ")"); - } - - $this->CloseFile($this->fp); - $this->CloseFile($this->fpLog); - - unlink($_SERVER["DOCUMENT_ROOT"] . $this->filename); - rename($_SERVER["DOCUMENT_ROOT"] . $this->filename. '.tmp', $_SERVER["DOCUMENT_ROOT"] . $this->filename); - - return true; - - } - - protected function PrepareSettings() - { - foreach ($this->propertiesSKU as $iblock => $arr) { - foreach ($arr as $id => $sku) { - $this->propertiesSKU[$iblock][$id] = strtoupper($sku); - } - } - foreach ($this->propertiesProduct as $iblock => $arr) { - foreach ($arr as $id => $prod) { - $this->propertiesProduct[$iblock][$id] = strtoupper($prod); - } - } - } - - protected function PrepareValue($text) - { - $newText = $this->application->ConvertCharset($text, $this->encodingDefault, $this->encoding); - $newText = strip_tags($newText); - $newText = str_replace("&", "&", $newText); - return $newText; - } - - protected function PrepareFile($filename) - { - $fullFilename = $_SERVER["DOCUMENT_ROOT"] . $filename; - CheckDirPath($fullFilename); - - if ($fp = @fopen($fullFilename, "w")) - return $fp; - else - return false; - } - - protected function PreWriteCatalog() - { - @fwrite($this->fp, "PrepareValue(Date("Y-m-d H:i:s")) . "\">\n - \n - " . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."\n - " . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."\n" - ); - - } - - protected function WriteCategories($categories) - { - $stringCategories = ""; - @fwrite($this->fp, "\n"); - foreach ($categories as $category) { - $stringCategories .= $this->BuildCategory($category); - } - @fwrite($this->fp, $stringCategories); - @fwrite($this->fp, "\n"); - } - protected function PreWriteOffers() - { - @fwrite($this->fp, "\n"); - } - - protected function PostWriteOffers() - { - @fwrite($this->fp, "\n"); - } - - protected function WriteOffers($offers) - { - @fwrite($this->fp, $offers); - } - - protected function WriteLog($text) - { - if ($this->isLogged) - @fwrite($this->fpLog, Date("Y:m:d H:i:s") . ": " . $text . "\n"); - } - - protected function PostWriteCatalog() - { - @fwrite($this->fp, "\n - \n"); - } - - protected function CloseFile($fp) - { - @fclose($fp); - } - - - protected function GetCategories() - { - $categories = array(); - foreach ($this->iblocks as $id) - { - $filter = array("IBLOCK_ID" => $id); - - $dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter); - $hasCategories = false; - while ($arRes = $dbRes->Fetch()) { - $categories[$arRes['ID']] = $arRes; - $hasCategories = true; - } - if (!$hasCategories) { - $iblock = CIBlock::GetByID($id)->Fetch(); - - $arRes = Array(); - $arRes['ID'] = $this->mainSection + $id; - $arRes['IBLOCK_SECTION_ID'] = 0; - $arRes['NAME'] = sprintf(GetMessage('ROOT_CATEGORY_FOR_CATALOG'), $iblock['NAME']); - $categories[$arRes['ID']] = $arRes; - } - } - return $categories; - - } - - protected function BuildCategory($arCategory) - { - return " - PrepareValue($arCategory["ID"]) . "\"" - . ( intval($arCategory["IBLOCK_SECTION_ID"] ) > 0 ? - " parentId=\"" . $this->PrepareValue($arCategory["IBLOCK_SECTION_ID"]) . "\"" - :"") - . ">" - . $this->PrepareValue($arCategory["NAME"]) - . "\n"; - - } - - protected function BuildOffers(&$allCategories) - { - - $basePriceId = COption::GetOptionString( - $this->MODULE_ID, - $this->CRM_CATALOG_BASE_PRICE . (is_null($this->profileID) === false ? '_' . $this->profileID : ''), - 1 + protected $measurement = array ( + 'mm' => 1, // 1 mm = 1 mm + 'cm' => 10, // 1 cm = 10 mm + 'm' => 1000, + 'mg' => 0.001, // 0.001 g = 1 mg + 'g' => 1, + 'kg' => 1000, ); - foreach ($this->iblocks as $key => $id) - { - // Get Info by infoblocks - $iblock['IBLOCK_DB'] = CIBlock::GetByID($id)->Fetch(); - $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id); + protected $measurementLink = array ( + 'mm' => 'mm', + 'cm' => 'mm', + 'm' => 'mm', + 'mg' => 'g', + 'g' => 'g', + 'kg' => 'g', + ); - $arSelect = Array ( - "ID", - "LID", - "IBLOCK_ID", - "IBLOCK_SECTION_ID", - "ACTIVE", - "ACTIVE_FROM", - "ACTIVE_TO", - "NAME", - "DETAIL_PICTURE", - "DETAIL_TEXT", - "DETAIL_PICTURE", - "LANG_DIR", - "DETAIL_PAGE_URL", - "CATALOG_GROUP_" . $basePriceId - ); - // Set selected properties - foreach ($this->propertiesProduct[$id] as $key => $propProduct) { - if ($this->propertiesProduct[$id][$key] != "") { - $arSelect[] = "PROPERTY_" . $propProduct; - $arSelect[] = "PROPERTY_" . $propProduct . ".NAME"; - } + public function Load() + { + global $USER; + if(!isset($_SESSION["SESS_AUTH"]["USER_ID"]) || !$_SESSION["SESS_AUTH"]["USER_ID"]) + $USER = new CUser; + + $this->isLogged = true; + + $defaultSite = CSite::GetList($by="def", $order="desc", Array())->Fetch(); + $this->encodingDefault = $defaultSite["CHARSET"]; + + $this->PrepareSettings(); + + $this->fp = $this->PrepareFile($this->filename. '.tmp'); + + if ($this->isLogged) { + $this->fpLog = $this->PrepareFile($this->logFile); + $this->WriteLog("Start Loading"); + } + + $this->PreWriteCatalog(); + + $categories = $this->GetCategories(); + + $this->WriteCategories($categories); + + $this->PreWriteOffers(); + $this->BuildOffers($categories); + $this->PostWriteOffers(); + + $this->PostWriteCatalog(); + + if ($this->isLogged) { + $this->WriteLog("Loading was ended successfully (peek memory usage: " . memory_get_peak_usage() . ")"); + } + + $this->CloseFile($this->fp); + $this->CloseFile($this->fpLog); + + unlink($_SERVER["DOCUMENT_ROOT"] . $this->filename); + rename($_SERVER["DOCUMENT_ROOT"] . $this->filename. '.tmp', $_SERVER["DOCUMENT_ROOT"] . $this->filename); + + return true; + + } + + protected function PrepareSettings() + { + foreach ($this->propertiesSKU as $iblock => $arr) { + foreach ($arr as $id => $sku) { + $this->propertiesSKU[$iblock][$id] = strtoupper($sku); + } + } + foreach ($this->propertiesProduct as $iblock => $arr) { + foreach ($arr as $id => $prod) { + $this->propertiesProduct[$iblock][$id] = strtoupper($prod); + } + } + } + + protected function PrepareValue($text) + { + $newText = $this->application->ConvertCharset($text, $this->encodingDefault, $this->encoding); + $newText = strip_tags($newText); + $newText = str_replace("&", "&", $newText); + return $newText; + } + + protected function PrepareFile($filename) + { + $fullFilename = $_SERVER["DOCUMENT_ROOT"] . $filename; + CheckDirPath($fullFilename); + + if ($fp = @fopen($fullFilename, "w")) + return $fp; + else + return false; + } + + protected function PreWriteCatalog() + { + @fwrite($this->fp, "PrepareValue(Date("Y-m-d H:i:s")) . "\">\n + \n + " . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."\n + " . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."\n" + ); + + } + + protected function WriteCategories($categories) + { + $stringCategories = ""; + @fwrite($this->fp, "\n"); + foreach ($categories as $category) { + $stringCategories .= $this->BuildCategory($category); + } + @fwrite($this->fp, $stringCategories); + @fwrite($this->fp, "\n"); + } + protected function PreWriteOffers() + { + @fwrite($this->fp, "\n"); + } + + protected function PostWriteOffers() + { + @fwrite($this->fp, "\n"); + } + + protected function WriteOffers($offers) + { + @fwrite($this->fp, $offers); + } + + protected function WriteLog($text) + { + if ($this->isLogged) + @fwrite($this->fpLog, Date("Y:m:d H:i:s") . ": " . $text . "\n"); + } + + protected function PostWriteCatalog() + { + @fwrite($this->fp, "\n + \n"); + } + + protected function CloseFile($fp) + { + @fclose($fp); + } + + + protected function GetCategories() + { + $categories = array(); + foreach ($this->iblocks as $id) + { + $filter = array("IBLOCK_ID" => $id); + + $dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter); + $hasCategories = false; + while ($arRes = $dbRes->Fetch()) { + $categories[$arRes['ID']] = $arRes; + $hasCategories = true; } + if (!$hasCategories) { + $iblock = CIBlock::GetByID($id)->Fetch(); - $arSelectOffer = Array ( - 'ID', - 'ACTIVE', - "NAME", - "DETAIL_TEXT", - "DETAIL_PAGE_URL", - "DETAIL_PICTURE", - 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'], - "CATALOG_GROUP_" . $basePriceId - ); - // Set selected properties - foreach ($this->propertiesSKU[$id] as $key => $propSKU) { - if ($this->propertiesSKU[$id][$key] != "") { - $arSelectOffer[] = "PROPERTY_" . $propSKU; - $arSelectOffer[] = "PROPERTY_" . $propSKU . ".NAME"; - } + $arRes = Array(); + $arRes['ID'] = $this->mainSection + $id; + $arRes['IBLOCK_SECTION_ID'] = 0; + $arRes['NAME'] = sprintf(GetMessage('ROOT_CATEGORY_FOR_CATALOG'), $iblock['NAME']); + $categories[$arRes['ID']] = $arRes; } + } + return $categories; - // Set filter - $filter = array( - "IBLOCK_ID" => $id, - "INCLUDE_SUBSECTIONS" => "Y", - ); - $order = array("id"); - $arNavStatParams = Array( - "iNumPage" => 1, - "nPageSize" => $this->pageSize, - ); + } - // Cycle page to page - do { - // Get products on this page - $dbResProducts = CIBlockElement::GetList($order, $filter, false, $arNavStatParams, $arSelect); + protected function BuildCategory($arCategory) + { + return " + PrepareValue($arCategory["ID"]) . "\"" + . ( intval($arCategory["IBLOCK_SECTION_ID"] ) > 0 ? + " parentId=\"" . $this->PrepareValue($arCategory["IBLOCK_SECTION_ID"]) . "\"" + :"") + . ">" + . $this->PrepareValue($arCategory["NAME"]) + . "\n"; - $pictures = array(); - $products = array(); - while ($product = $dbResProducts->GetNext()) { + } - // Compile products to array - $products[$product['ID']] = $product; - $products[$product['ID']]['offers'] = array(); + protected function BuildOffers(&$allCategories) + { - $detailPicture = intval($product["DETAIL_PICTURE"]); - $previewPicture = intval($product["PREVIEW_PICTURE"]); + $basePriceId = COption::GetOptionString( + $this->MODULE_ID, + $this->CRM_CATALOG_BASE_PRICE . (is_null($this->profileID) === false ? '_' . $this->profileID : ''), + 1 + ); - if ($detailPicture > 0 || $previewPicture > 0) - { - $picture = $detailPicture; - if ($picture <= 0) { - $picture = $previewPicture; + foreach ($this->iblocks as $key => $id) + { + // Get Info by infoblocks + $iblock['IBLOCK_DB'] = CIBlock::GetByID($id)->Fetch(); + $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id); + + $arSelect = Array ( + "ID", + "LID", + "IBLOCK_ID", + "IBLOCK_SECTION_ID", + "ACTIVE", + "ACTIVE_FROM", + "ACTIVE_TO", + "NAME", + "DETAIL_PICTURE", + "DETAIL_TEXT", + "DETAIL_PICTURE", + "LANG_DIR", + "DETAIL_PAGE_URL", + "CATALOG_GROUP_" . $basePriceId + ); + // Set selected properties + foreach ($this->propertiesProduct[$id] as $key => $propProduct) { + if ($this->propertiesProduct[$id][$key] != "") { + $arSelect[] = "PROPERTY_" . $propProduct; + $arSelect[] = "PROPERTY_" . $propProduct . ".NAME"; + } + } + + $arSelectOffer = Array ( + 'ID', + 'ACTIVE', + "NAME", + "DETAIL_TEXT", + "DETAIL_PAGE_URL", + "DETAIL_PICTURE", + 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'], + "CATALOG_GROUP_" . $basePriceId + ); + // Set selected properties + foreach ($this->propertiesSKU[$id] as $key => $propSKU) { + if ($this->propertiesSKU[$id][$key] != "") { + $arSelectOffer[] = "PROPERTY_" . $propSKU; + $arSelectOffer[] = "PROPERTY_" . $propSKU . ".NAME"; + } + } + + // Set filter + $filter = array( + "IBLOCK_ID" => $id, + "INCLUDE_SUBSECTIONS" => "Y", + ); + $order = array("id"); + $arNavStatParams = Array( + "iNumPage" => 1, + "nPageSize" => $this->pageSize, + ); + + // Cycle page to page + do { + // Get products on this page + $dbResProducts = CIBlockElement::GetList($order, $filter, false, $arNavStatParams, $arSelect); + + $pictures = array(); + $products = array(); + while ($product = $dbResProducts->GetNext()) { + + // Compile products to array + $products[$product['ID']] = $product; + $products[$product['ID']]['offers'] = array(); + + $detailPicture = intval($product["DETAIL_PICTURE"]); + $previewPicture = intval($product["PREVIEW_PICTURE"]); + + if ($detailPicture > 0 || $previewPicture > 0) + { + $picture = $detailPicture; + if ($picture <= 0) { + $picture = $previewPicture; + } + + // Link pictureID and productID + $pictures[$picture] = $product['ID']; } - - // Link pictureID and productID - $pictures[$picture] = $product['ID']; } - } - unset($product); - unset($detailPicture, $previewPicture, $picture); + unset($product); + unset($detailPicture, $previewPicture, $picture); - $pictureIDs = array_keys($pictures); + $pictureIDs = array_keys($pictures); - // Get pathes of pictures - $dbFiles = CFile::GetList(Array(), Array("@ID" => implode(',', $pictureIDs))); - while($file = $dbFiles->GetNext()) { + // Get pathes of pictures + $dbFiles = CFile::GetList(Array(), Array("@ID" => implode(',', $pictureIDs))); + while($file = $dbFiles->GetNext()) { - // Link picture to product - $products[$pictures[$file['ID']]]['PICTURE'] = ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . - $this->serverName . - '/upload/' . $file['SUBDIR'] . - '/' . $file['FILE_NAME'] ; - } - unset($pictures); - - if (!empty($iblockOffer['IBLOCK_ID'])) { - $arFilterOffer = array( - 'IBLOCK_ID' => $iblockOffer['IBLOCK_ID'], - 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] => array_keys($products), - ); - - // Get all offers for products on this page - $dbResOffers = CIBlockElement::GetList( - array(), - $arFilterOffer, - false, - array('nTopCount' => $this->pageSize * $this->offerPageSize), - $arSelectOffer - ); - - while ($offer = $dbResOffers->GetNext()) { - // Link offers to products - $products[$offer['PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] . '_VALUE']]['offers'][$offer['ID']] = $offer; + // Link picture to product + $products[$pictures[$file['ID']]]['PICTURE'] = ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . + $this->serverName . + '/upload/' . $file['SUBDIR'] . + '/' . $file['FILE_NAME'] ; } - unset($offer, $dbResOffers); - } + unset($pictures); - $stringOffers = ""; - foreach ($products as $product) { + if (!empty($iblockOffer['IBLOCK_ID'])) { + $arFilterOffer = array( + 'IBLOCK_ID' => $iblockOffer['IBLOCK_ID'], + 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] => array_keys($products), + ); - // Get properties of product - $resPropertiesProduct = Array(); - foreach ($this->propertiesProduct[$id] as $key => $propProduct) { - $resPropertiesProduct[$key] = ""; + // Get all offers for products on this page + $dbResOffers = CIBlockElement::GetList( + array(), + $arFilterOffer, + false, + array('nTopCount' => $this->pageSize * $this->offerPageSize), + $arSelectOffer + ); - if ($propProduct != "") { + while ($offer = $dbResOffers->GetNext()) { + // Link offers to products + $products[$offer['PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] . '_VALUE']]['offers'][$offer['ID']] = $offer; + } + unset($offer, $dbResOffers); + } - if (isset($product["PROPERTY_" . $propProduct . "_NAME"])) - $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_NAME"]; - elseif (isset($product["PROPERTY_" . $propProduct . "_VALUE"])) - $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_VALUE"]; - elseif (isset($product[$propProduct])) - $resPropertiesProduct[$key] = $product[$propProduct]; + $stringOffers = ""; + foreach ($products as $product) { - if (array_key_exists($key, $this->propertiesUnitProduct[$id])) { - $resPropertiesProduct[$key] *= $this->measurement[$this->propertiesUnitProduct[$id][$key]]; - $resPropertiesProduct[$key . "_UNIT"] = $this->measurementLink[$this->propertiesUnitProduct[$id][$key]]; + // Get properties of product + $resPropertiesProduct = Array(); + foreach ($this->propertiesProduct[$id] as $key => $propProduct) { + $resPropertiesProduct[$key] = ""; + + if ($propProduct != "") { + + if (isset($product["PROPERTY_" . $propProduct . "_NAME"])) + $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_NAME"]; + elseif (isset($product["PROPERTY_" . $propProduct . "_VALUE"])) + $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_VALUE"]; + elseif (isset($product[$propProduct])) + $resPropertiesProduct[$key] = $product[$propProduct]; + + if (array_key_exists($key, $this->propertiesUnitProduct[$id])) { + $resPropertiesProduct[$key] *= $this->measurement[$this->propertiesUnitProduct[$id][$key]]; + $resPropertiesProduct[$key . "_UNIT"] = $this->measurementLink[$this->propertiesUnitProduct[$id][$key]]; + } } } - } - // Get categories of product - $categories = Array(); - $dbResCategories = CIBlockElement::GetElementGroups($product['ID'], true); - while ($arResCategory = $dbResCategories->Fetch()) { - $categories[$arResCategory["ID"]] = array( - 'ID' => $arResCategory["ID"], - 'NAME' => $arResCategory["NAME"], - ); - } - if (count($categories) == 0) { + // Get categories of product + $categories = Array(); + $dbResCategories = CIBlockElement::GetElementGroups($product['ID'], true); + while ($arResCategory = $dbResCategories->Fetch()) { + $categories[$arResCategory["ID"]] = array( + 'ID' => $arResCategory["ID"], + 'NAME' => $arResCategory["NAME"], + ); + } + if (count($categories) == 0) { - $catId = $this->mainSection + $id; - $categories[$catId] = $allCategories[$catId]; - } + $catId = $this->mainSection + $id; + $categories[$catId] = $allCategories[$catId]; + } - $existOffer = false; - if (!empty($iblockOffer['IBLOCK_ID'])) { + $existOffer = false; + if (!empty($iblockOffer['IBLOCK_ID'])) { - foreach ($product['offers'] as $offer) { + foreach ($product['offers'] as $offer) { - $offer['PRODUCT_ID'] = $product["ID"]; - $offer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"]; - $offer['PICTURE'] = $product["PICTURE"]; - $offer['PRODUCT_NAME'] = $product["NAME"]; - $offer['PRODUCT_ACTIVE'] = $product["ACTIVE"]; - $offer['PRICE'] = $offer['CATALOG_PRICE_' . $basePriceId]; - $offer['PURCHASE_PRICE'] = $offer['CATALOG_PURCHASING_PRICE']; - $offer['QUANTITY'] = $offer["CATALOG_QUANTITY"]; + $offer['PRODUCT_ID'] = $product["ID"]; + $offer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"]; + $offer['PICTURE'] = $product["PICTURE"]; + $offer['PRODUCT_NAME'] = $product["NAME"]; + $offer['PRODUCT_ACTIVE'] = $product["ACTIVE"]; + $offer['PRICE'] = $offer['CATALOG_PRICE_' . $basePriceId]; + $offer['PURCHASE_PRICE'] = $offer['CATALOG_PURCHASING_PRICE']; + $offer['QUANTITY'] = $offer["CATALOG_QUANTITY"]; - // Get properties of product + // Get properties of product - foreach ($this->propertiesSKU[$id] as $key => $propSKU) { + foreach ($this->propertiesSKU[$id] as $key => $propSKU) { - if ($propSKU != "") { + if ($propSKU != "") { - if (isset ($offer["PROPERTY_" . $propSKU . "_NAME"])) - $offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_NAME"]; - elseif (isset($offer["PROPERTY_" . $propSKU . "_VALUE"])) - $offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_VALUE"]; - elseif (isset($offer[$propSKU])) - $offer['_PROP_' . $key] = $offer[$propSKU]; + if (isset ($offer["PROPERTY_" . $propSKU . "_NAME"])) + $offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_NAME"]; + elseif (isset($offer["PROPERTY_" . $propSKU . "_VALUE"])) + $offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_VALUE"]; + elseif (isset($offer[$propSKU])) + $offer['_PROP_' . $key] = $offer[$propSKU]; - if (array_key_exists($key, $this->propertiesUnitSKU[$id])) { - $offer['_PROP_' . $key] *= $this->measurement[$this->propertiesUnitSKU[$id][$key]]; - $offer['_PROP_' . $key . "_UNIT"] = $this->measurementLink[$this->propertiesUnitSKU[$id][$key]]; + if (array_key_exists($key, $this->propertiesUnitSKU[$id])) { + $offer['_PROP_' . $key] *= $this->measurement[$this->propertiesUnitSKU[$id][$key]]; + $offer['_PROP_' . $key . "_UNIT"] = $this->measurementLink[$this->propertiesUnitSKU[$id][$key]]; + } } + } + foreach ($resPropertiesProduct as $key => $propProduct) { + if ($this->propertiesProduct[$id][$key] != "" && !isset($offer[$key])) + $offer['_PROP_' . $key] = $propProduct; + } + + $stringOffers .= $this->BuildOffer($offer, $categories, $iblock, $allCategories); + $existOffer = true; } + } + if (!$existOffer) { + + $product['PRODUCT_ID'] = $product["ID"]; + $product['PRODUCT_NAME'] = $product["NAME"]; + $product['PRODUCT_ACTIVE'] = $product["ACTIVE"]; + $product['PRICE'] = $product['CATALOG_PRICE_' . $basePriceId]; + $product['PURCHASE_PRICE'] = $product['CATALOG_PURCHASING_PRICE']; + $product['QUANTITY'] = $product["CATALOG_QUANTITY"]; foreach ($resPropertiesProduct as $key => $propProduct) { - if ($this->propertiesProduct[$id][$key] != "" && !isset($offer[$key])) - $offer['_PROP_' . $key] = $propProduct; + if ($this->propertiesProduct[$id][$key] != "" || $this->propertiesProduct[$id][str_replace("_UNIT", "", $key)] != "") { + $product['_PROP_' . $key] = $propProduct; + } } - $stringOffers .= $this->BuildOffer($offer, $categories, $iblock, $allCategories); - $existOffer = true; - } - } - if (!$existOffer) { - - $product['PRODUCT_ID'] = $product["ID"]; - $product['PRODUCT_NAME'] = $product["NAME"]; - $product['PRODUCT_ACTIVE'] = $product["ACTIVE"]; - $product['PRICE'] = $product['CATALOG_PRICE_' . $basePriceId]; - $product['PURCHASE_PRICE'] = $product['CATALOG_PURCHASING_PRICE']; - $product['QUANTITY'] = $product["CATALOG_QUANTITY"]; - - foreach ($resPropertiesProduct as $key => $propProduct) { - if ($this->propertiesProduct[$id][$key] != "" || $this->propertiesProduct[$id][str_replace("_UNIT", "", $key)] != "") { - $product['_PROP_' . $key] = $propProduct; - } + $stringOffers .= $this->BuildOffer($product, $categories, $iblock, $allCategories); } - $stringOffers .= $this->BuildOffer($product, $categories, $iblock, $allCategories); - } + } + unset($products); + if ($this->isLogged) + $this->WriteLog(($this->pageSize * $arNavStatParams['iNumPage']) . " product(s) has been loaded from " . $id . " IB (memory usage: " . memory_get_usage() . ")"); + if ($stringOffers != "") { + $this->WriteOffers($stringOffers); + $stringOffers = ""; + } + + $arNavStatParams['iNumPage'] = $dbResProducts->NavPageNomer + 1; } - unset($products); + while ($dbResProducts->NavPageNomer < $dbResProducts->NavPageCount); + } + } - if ($this->isLogged) - $this->WriteLog(($this->pageSize * $arNavStatParams['iNumPage']) . " product(s) has been loaded from " . $id . " IB (memory usage: " . memory_get_usage() . ")"); - if ($stringOffers != "") { - $this->WriteOffers($stringOffers); - $stringOffers = ""; + + protected function BuildOffer($arOffer, $categories, $iblock, &$allCategories) + { + $offer = ""; + $offer .= "PrepareValue($arOffer["ID"]) . "\" ". + "productId=\"" . $this->PrepareValue($arOffer["PRODUCT_ID"]) . "\" ". + "quantity=\"" . $this->PrepareValue(DoubleVal($arOffer['QUANTITY'])) . "\">\n"; + + if ($arOffer['PRODUCT_ACTIVE'] == "N") + $offer .= "" . $this->PrepareValue($arOffer['PRODUCT_ACTIVE']) . "\n"; + + $keys = array_keys($categories); + if (strpos($arOffer['DETAIL_PAGE_URL'], "#SECTION_PATH#") !== false) { + if (count($categories) != 0) { + + $category = $allCategories[$keys[0]]; + $path = $category['CODE']; + + if(intval($category["IBLOCK_SECTION_ID"] ) != 0) { + while (true) { + $category = $allCategories[$category['IBLOCK_SECTION_ID']]; + $path = $category['CODE'] . '/' . $path; + if(intval($category["IBLOCK_SECTION_ID"] ) == 0) + break; + } } - $arNavStatParams['iNumPage'] = $dbResProducts->NavPageNomer + 1; } - while ($dbResProducts->NavPageNomer < $dbResProducts->NavPageCount); - } - } + $arOffer['DETAIL_PAGE_URL'] = str_replace("#SECTION_PATH#", $path, $arOffer['DETAIL_PAGE_URL']); + } + $offer .= "" . $this->PrepareValue($arOffer["PICTURE"]) . "\n"; + $offer .= "" . ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . $this->serverName . $this->PrepareValue($arOffer['DETAIL_PAGE_URL']) . "\n"; - protected function BuildOffer($arOffer, $categories, $iblock, &$allCategories) - { - $offer = ""; - $offer .= "PrepareValue($arOffer["ID"]) . "\" ". - "productId=\"" . $this->PrepareValue($arOffer["PRODUCT_ID"]) . "\" ". - "quantity=\"" . $this->PrepareValue(DoubleVal($arOffer['QUANTITY'])) . "\">\n"; + $offer .= "" . $this->PrepareValue($arOffer['PRICE']) . "\n"; + if ($arOffer['PURCHASE_PRICE'] && $this->loadPurchasePrice) { + $offer .= "" . $this->PrepareValue($arOffer['PURCHASE_PRICE']) . "\n"; + } + foreach ($categories as $category) + $offer .= "" . $category['ID'] . "\n"; - if ($arOffer['PRODUCT_ACTIVE'] == "N") - $offer .= "" . $this->PrepareValue($arOffer['PRODUCT_ACTIVE']) . "\n"; + $offer .= "" . $this->PrepareValue($arOffer["NAME"]) . "\n"; - $keys = array_keys($categories); - if (strpos($arOffer['DETAIL_PAGE_URL'], "#SECTION_PATH#") !== false) { - if (count($categories) != 0) { + $offer .= "" . $this->PrepareValue($arOffer["EXTERNAL_ID"]) . "\n"; + $offer .= "" . $this->PrepareValue($arOffer["PRODUCT_NAME"]) . "\n"; - $category = $allCategories[$keys[0]]; - $path = $category['CODE']; - - if(intval($category["IBLOCK_SECTION_ID"] ) != 0) { - while (true) { - $category = $allCategories[$category['IBLOCK_SECTION_ID']]; - $path = $category['CODE'] . '/' . $path; - if(intval($category["IBLOCK_SECTION_ID"] ) == 0) - break; - } + foreach ($this->propertiesProduct[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { + if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) { + if ($key === "manufacturer") + $offer .= "" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; + else + $offer .= '" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; } - } - $arOffer['DETAIL_PAGE_URL'] = str_replace("#SECTION_PATH#", $path, $arOffer['DETAIL_PAGE_URL']); - } - - $offer .= "" . $this->PrepareValue($arOffer["PICTURE"]) . "\n"; - $offer .= "" . ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . $this->serverName . $this->PrepareValue($arOffer['DETAIL_PAGE_URL']) . "\n"; - - $offer .= "" . $this->PrepareValue($arOffer['PRICE']) . "\n"; - if ($arOffer['PURCHASE_PRICE'] && $this->loadPurchasePrice) { - $offer .= "" . $this->PrepareValue($arOffer['PURCHASE_PRICE']) . "\n"; - } - foreach ($categories as $category) - $offer .= "" . $category['ID'] . "\n"; - - $offer .= "" . $this->PrepareValue($arOffer["NAME"]) . "\n"; - - $offer .= "" . $this->PrepareValue($arOffer["EXTERNAL_ID"]) . "\n"; - $offer .= "" . $this->PrepareValue($arOffer["PRODUCT_NAME"]) . "\n"; - - foreach ($this->propertiesProduct[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { - if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) { - if ($key === "manufacturer") - $offer .= "" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; - else - $offer .= '" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; + foreach ($this->propertiesSKU[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { + if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) { + if ($key === "manufacturer") + $offer .= "" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; + else + $offer .= '" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; + } } - } - foreach ($this->propertiesSKU[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { - if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) { - if ($key === "manufacturer") - $offer .= "" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; - else - $offer .= '" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "\n"; - } - } - $offer.= "\n"; - return $offer; + $offer.= "\n"; + return $offer; + } } } diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php index 3caba6ed..51ae8e1b 100644 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ b/intaro.intarocrm/classes/general/ICrmOrderActions.php @@ -1,1058 +1,1063 @@ 0) { - $arFilter['ID'] = $failedIds; - } elseif ($orderList !== false && count($orderList) > 0) { - $arFilter['ID'] = $orderList; - } else { - $arFilter['>ID'] = $lastUpOrderId; - $arCount['nTopCount'] = $pSize; - } - - if ( (isset($arFilter['ID']) && count($arFilter['ID']) > 0) || isset($arFilter['>ID']) ) { - $dbOrder = CSaleOrder::GetList(array("ID" => "ASC"), $arFilter, false, $arCount); - if ($dbOrder->SelectedRowsCount() <= 0) { - return false; + if (!CModule::IncludeModule("iblock")) { + self::eventLog('ICrmOrderActions::uploadOrders', 'iblock', 'module not found'); + return true; } - } else { - return false; - } - - $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); - $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0); - - $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); - $optionsOrderTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0)); - $optionsDelivTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0)); - $optionsPayTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0)); - $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses - $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); - $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); - $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0)); - $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0)); - $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0)); - - $api = new RetailCrm\RestApi($api_host, $api_key); - - $arParams = array( - 'optionsOrderTypes' => $optionsOrderTypes, - 'optionsDelivTypes' => $optionsDelivTypes, - 'optionsPayTypes' => $optionsPayTypes, - 'optionsPayStatuses' => $optionsPayStatuses, - 'optionsPayment' => $optionsPayment, - 'optionsOrderProps' => $optionsOrderProps, - 'optionsLegalDetails' => $optionsLegalDetails, - 'optionsContragentType' => $optionsContragentType, - 'optionsSitesList' => $optionsSitesList , - 'optionsCustomFields' => $optionsCustomFields, - ); - - $recOrders = array(); - while ($arOrder = $dbOrder->GetNext()) { - $result = self::orderCreate($arOrder, $api, $arParams); - if (!$result['order'] || !$result['customer']){ - continue; + if (!CModule::IncludeModule("sale")) { + self::eventLog('ICrmOrderActions::uploadOrders', 'sale', 'module not found'); + return true; + } + if (!CModule::IncludeModule("catalog")) { + self::eventLog('ICrmOrderActions::uploadOrders', 'catalog', 'module not found'); + return true; } - $resOrders[$arOrder['LID']][] = $result['order']; - $resCustomers[$arOrder['LID']][] = $result['customer']; + $resOrders = array(); + $resCustomers = array(); - $recOrders[] = $arOrder['ID']; - } - if(count($resOrders) > 0){ - foreach($resCustomers as $key => $customerLoad){ - $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; - if (self::apiMethod($api, 'customerUpload', __METHOD__, $customerLoad, $site) === false) { - return false; - } - if (count($optionsSitesList) > 1) { - time_nanosleep(0, 250000000); - } - } - foreach($resOrders as $key => $orderLoad){ - $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; - if (self::apiMethod($api, 'orderUpload', __METHOD__, $orderLoad, $site) === false) { - return false; - } - if (count($optionsSitesList) > 1) { - time_nanosleep(0, 250000000); - } - } + $lastUpOrderId = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, 0); + $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); + + $arFilter = array(); + $arCount = false; if ($failed == true && $failedIds !== false && count($failedIds) > 0) { - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, serialize(array_diff($failedIds, $recOrders))); - } elseif ($lastUpOrderId < max($recOrders) && $orderList === false) { - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, max($recOrders)); + $arFilter['ID'] = $failedIds; + } elseif ($orderList !== false && count($orderList) > 0) { + $arFilter['ID'] = $orderList; + } else { + $arFilter['>ID'] = $lastUpOrderId; + $arCount['nTopCount'] = $pSize; } - } - return true; - } - - /** - * - * Creates order or returns array of order and customer for mass upload - * - * @param array $arFields - * @param $api - * @param $arParams - * @param $send - * @return boolean - * @return array - array('order' = $order, 'customer' => $customer) - */ - public static function orderCreate($arFields, $api, $arParams, $send = false, $site = null) { - if(!$api || empty($arParams)) { // add cond to check $arParams - return false; - } - if (empty($arFields)) { - self::eventLog('ICrmOrderActions::orderCreate', 'empty($arFields)', 'incorrect order'); - return false; - } - - if (isset($arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['city']) == false) { - $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'], 'CODE' => 'LOCATION')); - $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['city'] = $rsOrderProps->SelectedRowsCount() < 1 ? 'CITY' : 'LOCATION'; - } - - $normalizer = new RestNormalizer(); - $normalizer->setValidation(__DIR__ . '/config/retailcrm.json'); - - $customer = array(); - - if ($arFields['CANCELED'] == 'Y') { - $arFields['STATUS_ID'] = $arFields['CANCELED'].$arFields['CANCELED']; - } - - $order = array( - 'number' => $arFields['ACCOUNT_NUMBER'], - 'externalId' => $arFields['ID'], - 'createdAt' => new \DateTime($arFields['DATE_INSERT']), - 'customerId' => $arFields['USER_ID'], - 'discount' => $arFields['DISCOUNT_VALUE'], - 'markDateTime' => $arFields['DATE_MARKED'], - 'paymentType' => isset($arParams['optionsPayTypes'][$arFields['PAY_SYSTEM_ID']]) ? - $arParams['optionsPayTypes'][$arFields['PAY_SYSTEM_ID']] : '', - 'paymentStatus' => isset($arParams['optionsPayment'][$arFields['PAYED']]) ? - $arParams['optionsPayment'][$arFields['PAYED']] : '', - 'orderType' => isset($arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']]) ? - $arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']] : '', - 'contragentType' => isset($arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']]) ? - $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']] : '', - 'status' => isset($arParams['optionsPayStatuses'][$arFields['STATUS_ID']]) ? - $arParams['optionsPayStatuses'][$arFields['STATUS_ID']] : '', - 'statusComment' => $arFields['REASON_CANCELED'], - 'customerComment' => $arFields['USER_DESCRIPTION'], - 'managerComment' => $arFields['COMMENTS'], - 'delivery' => array( - 'cost' => $arFields['PRICE_DELIVERY'] - ), - ); - - $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); - while ($ar = $rsOrderProps->Fetch()) { - if ($search = array_search($ar['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) { - $order[$search] = $ar['VALUE']; - $customer[$search] = $ar['VALUE']; - } elseif ($search = array_search($ar['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) { - $order['customFields'][$search] = $ar['VALUE']; - } elseif ($search = array_search($ar['CODE'], $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']])) { - if (in_array($search, array('fio', 'phone', 'email'))) { - if ($search == 'fio') { - $order = array_merge($order, self::explodeFIO($ar['VALUE'])); - } else { - $order[$search] = $ar['VALUE']; - } - } else { - $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']); - if ($prop['TYPE'] == 'LOCATION') { - $ar['VALUE'] = CSaleLocation::GetByID( - method_exists('CSaleLocation', 'getLocationIDbyCODE') ? - CSaleLocation::getLocationIDbyCODE($ar['VALUE']) : $ar['VALUE'] - ); - $ar['VALUE'] = $ar['VALUE']['CITY_NAME_LANG']; - } - - $order['delivery']['address'][$search] = $ar['VALUE']; + if ( (isset($arFilter['ID']) && count($arFilter['ID']) > 0) || isset($arFilter['>ID']) ) { + $dbOrder = CSaleOrder::GetList(array("ID" => "ASC"), $arFilter, false, $arCount); + if ($dbOrder->SelectedRowsCount() <= 0) { + return false; } - } - } - if (strpos($arFields['DELIVERY_ID'], ":") !== false){ - $arFields["DELIVERY_ID"] = explode(":", $arFields["DELIVERY_ID"], 2); - if ($arDeliveryType = CSaleDeliveryHandler::GetBySID(reset($arFields["DELIVERY_ID"]))->GetNext()) { - if (array_key_exists(end($arFields["DELIVERY_ID"]), $arDeliveryType['PROFILES'])) { - $arFields["DELIVERY_SERVICE"] = array( - 'code' => implode('-', $arFields["DELIVERY_ID"]), - 'name' => $arDeliveryType['PROFILES'][end($arFields["DELIVERY_ID"])]['TITLE'] - ); - } - } - $arFields["DELIVERY_ID"] = reset($arFields["DELIVERY_ID"]); - } - - if (array_key_exists($arFields['DELIVERY_ID'], $arParams['optionsDelivTypes'])) { - $order['delivery']['code'] = $arParams['optionsDelivTypes'][$arFields["DELIVERY_ID"]]; - if (isset($arFields["DELIVERY_SERVICE"])) { - $order['delivery']['service'] = $arFields["DELIVERY_SERVICE"]; - } - } - - $rsOrderBasket = CSaleBasket::GetList(array('ID' => 'ASC'), array('ORDER_ID' => $arFields['ID'])); - while ($p = $rsOrderBasket->Fetch()) { - $item = array( - 'quantity' => $p['QUANTITY'], - 'productId' => $p['PRODUCT_ID'], - 'xmlId' => $p['PRODUCT_XML_ID'], - 'productName' => $p['NAME'], - 'comment' => $p['NOTES'], - 'createdAt' => new \DateTime($p['DATE_INSERT']) - ); - - $pp = CCatalogProduct::GetByID($p['PRODUCT_ID']); - if (is_null($pp['PURCHASING_PRICE']) == false) { - $item['purchasePrice'] = $pp['PURCHASING_PRICE']; - } - - $propCancel = CSaleBasket::GetPropsList(array(), array('BASKET_ID' => $p['ID'], 'CODE' => self::CANCEL_PROPERTY_CODE))->Fetch(); - if (!$propCancel || ($propCancel && !(int)$propCancel['VALUE'])) { - $item['discount'] = (double) $p['DISCOUNT_PRICE']; - $item['initialPrice'] = (double) $p['PRICE'] + (double) $p['DISCOUNT_PRICE']; - } - - $order['items'][] = $item; - } - - $arUser = CUser::GetByID($arFields['USER_ID'])->Fetch(); - - $customer = array( - 'externalId' => $arFields['USER_ID'], - 'lastName' => $arUser['LAST_NAME'], - 'firstName' => $arUser['NAME'], - 'patronymic' => $arUser['SECOND_NAME'], - 'phones' => array( - array('number' => $arUser['PERSONAL_PHONE']), - array('number' => $arUser['WORK_PHONE']) - ), - 'createdAt' => new \DateTime($arUser['DATE_REGISTER']), - 'contragentType' => $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']] - ); - - if(function_exists('intarocrm_get_order_type')) { - $orderType = intarocrm_get_order_type($arFields); - if ($orderType) { - $order['orderType'] = $orderType; - } - } - if (function_exists('intarocrm_before_order_send')) { - $newResOrder = intarocrm_before_order_send($resOrder); - if (is_array($newResOrder) && !empty($newResOrder)) { - $resOrder = $newResOrder; - } - } - - $customer = $normalizer->normalize($customer, 'customers'); - $order = $normalizer->normalize($order, 'orders'); - - if (isset($arParams['optionsSitesList']) && is_array($arParams['optionsSitesList']) && - array_key_exists($arFields['LID'], $arParams['optionsSitesList'])) { - $site = $arParams['optionsSitesList'][$arFields['LID']]; - } - - if($send) { - if (!self::apiMethod($api, 'customerEdit', __METHOD__, $customer, $site)) { - return false; - } - if ($orderEdit = self::apiMethod($api, 'orderEdit', __METHOD__, $order, $site)) { - return $orderEdit; } else { return false; } - } - return array( - 'order' => $order, - 'customer' => $customer - ); - } + $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); + $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0); - /** - * - * History update, cron usage only - * @global CUser $USER - * @return boolean - */ - public static function orderHistory() { - global $USER; - if (is_object($USER) == false) { - $USER = new RetailUser; - } + $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); + $optionsOrderTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0)); + $optionsDelivTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0)); + $optionsPayTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0)); + $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses + $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); + $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); + $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0)); + $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0)); + $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0)); - if (!CModule::IncludeModule("iblock")) { - self::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found'); - return false; - } - if (!CModule::IncludeModule("sale")) { - self::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found'); - return false; - } - if (!CModule::IncludeModule("catalog")) { - self::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found'); - return false; - } + $api = new RetailCrm\RestApi($api_host, $api_key); - $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); - $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0); - - $optionsOrderTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0))); - $optionsDelivTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0))); - $optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0))); - $optionsPayStatuses = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0))); // --statuses - $optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0))); - $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); - $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0)); - $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0)); - $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); - $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0)); - - foreach ($optionsOrderProps as $code => $value) { - if (isset($optionsLegalDetails[$code])) { - $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsLegalDetails[$code]); - } - if (isset($optionsCustomFields[$code])) { - $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsCustomFields[$code]); - } - $optionsOrderProps[$code]['location'] = 'LOCATION'; - if (array_search('CITY', $optionsOrderProps[$code]) == false) { - $optionsOrderProps[$code]['city'] = 'CITY'; - } - if (array_search('ZIP', $optionsOrderProps[$code]) == false) { - $optionsOrderProps[$code]['index'] = 'ZIP'; - } - } - - $api = new RetailCrm\RestApi($api_host, $api_key); - - $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null); - - if (is_null($dateStart)) { - $dateStart = new \DateTime(); - $dateStart = $dateStart->format('Y-m-d H:i:s'); - } - - try { - $orderHistory = $api->orderHistory($dateStart); - } catch (\RetailCrm\Exception\CurlException $e) { - self::eventLog( - 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::orderHistory::CurlException', - $e->getCode() . ': ' . $e->getMessage() + $arParams = array( + 'optionsOrderTypes' => $optionsOrderTypes, + 'optionsDelivTypes' => $optionsDelivTypes, + 'optionsPayTypes' => $optionsPayTypes, + 'optionsPayStatuses' => $optionsPayStatuses, + 'optionsPayment' => $optionsPayment, + 'optionsOrderProps' => $optionsOrderProps, + 'optionsLegalDetails' => $optionsLegalDetails, + 'optionsContragentType' => $optionsContragentType, + 'optionsSitesList' => $optionsSitesList , + 'optionsCustomFields' => $optionsCustomFields, ); - return false; - } - - $orderHistory = isset($orderHistory['orders']) ? $orderHistory['orders'] : array(); - - $dateFinish = $api->getGeneratedAt(); - if (is_null($dateFinish) || $dateFinish == false) { - $dateFinish = new \DateTime(); - } - - $defaultOrderType = 1; - $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y")); - if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { - $defaultOrderType = $arOrderTypesList['ID']; - } - - $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true; - - foreach ($orderHistory as $order) { - if (function_exists('intarocrm_order_pre_persist')) { - $order = intarocrm_order_pre_persist($order); - } - - if (!isset($order['externalId'])) { - - // custom orderType function - if (function_exists('intarocrm_set_order_type')) { - $orderType = intarocrm_set_order_type($order); - if ($orderType) { - $optionsOrderTypes[$order['orderType']] = $orderType; - } else { - $optionsOrderTypes[$order['orderType']] = $defaultOrderType; - } - } - - // we dont need new orders without any customers (can check only for externalId) - if (!isset($order['customer']['externalId'])) { - if (!isset($order['customer']['id'])) { - continue; - } - - $registerNewUser = true; - - if (!isset($order['customer']['email'])) { - $login = $order['customer']['email'] = uniqid('user_' . time()) . '@crm.com'; - } else { - $dbUser = CUser::GetList(($by = 'ID'), ($sort = 'ASC'), array('=EMAIL' => $order['email'])); - switch ($dbUser->SelectedRowsCount()) { - case 0: - $login = $order['customer']['email']; - break; - case 1: - $arUser = $dbUser->Fetch(); - $registeredUserID = $arUser['ID']; - $registerNewUser = false; - break; - default: - $login = uniqid('user_' . time()) . '@crm.com'; - break; - } - } - - if ($registerNewUser === true) { - $userPassword = uniqid(); - - $newUser = new CUser; - $arFields = array( - "NAME" => self::fromJSON($order['customer']['firstName']), - "LAST_NAME" => self::fromJSON($order['customer']['lastName']), - "EMAIL" => $order['customer']['email'], - "LOGIN" => $login, - "LID" => "ru", - "ACTIVE" => "Y", - "PASSWORD" => $userPassword, - "CONFIRM_PASSWORD" => $userPassword - ); - $registeredUserID = $newUser->Add($arFields); - if ($registeredUserID === false) { - self::eventLog('ICrmOrderActions::orderHistory', 'CUser::Register', 'Error register user'); - continue; - } - - try { - $api->customerFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))); - } catch (\RetailCrm\Exception\CurlException $e) { - self::eventLog( - 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - - continue; - } - } - - $order['customer']['externalId'] = $registeredUserID; - } - - // new order - $newOrderFields = array( - 'LID' => CSite::GetDefSite(), - 'PERSON_TYPE_ID' => isset($optionsOrderTypes[$order['orderType']]) ? $optionsOrderTypes[$order['orderType']] : $defaultOrderType, - 'PAYED' => 'N', - 'CANCELED' => 'N', - 'STATUS_ID' => 'N', - 'PRICE' => 0, - 'CURRENCY' => 'RUB', - 'USER_ID' => $order['customer']['externalId'], - 'PAY_SYSTEM_ID' => 0, - 'PRICE_DELIVERY' => 0, - 'DELIVERY_ID' => 0, - 'DISCOUNT_VALUE' => 0, - 'USER_DESCRIPTION' => '' - ); - - if(count($optionsSitesList) > 1 && $lid = array_search($order['site'], $optionsSitesList)){ - $newOrderFields['LID'] = $lid; - } - - $externalId = CSaleOrder::Add($newOrderFields); - - if (!isset($order['externalId'])) { - try { - $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $externalId))); - } catch (\RetailCrm\Exception\CurlException $e) { - self::eventLog( - 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::orderFixExternalIds::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - - continue; - } - } - $order['externalId'] = $externalId; - } - - if (isset($order['externalId']) && $order['externalId']) { - - // custom orderType function - if (function_exists('intarocrm_set_order_type')) { - $orderType = intarocrm_set_order_type($order); - if ($orderType) { - $optionsOrderTypes[$order['orderType']] = $orderType; - } else { - $optionsOrderTypes[$order['orderType']] = $defaultOrderType; - } - } - - $arFields = CSaleOrder::GetById($order['externalId']); - - // incorrect order - if ($arFields === false || empty($arFields)) { + $recOrders = array(); + while ($arOrder = $dbOrder->GetNext()) { + $result = self::orderCreate($arOrder, $api, $arParams); + if (!$result['order'] || !$result['customer']){ continue; } - $LID = $arFields['LID']; - $userId = $arFields['USER_ID']; + $resOrders[$arOrder['LID']][] = $result['order']; + $resCustomers[$arOrder['LID']][] = $result['customer']; - if(isset($order['customer']['externalId']) && !is_null($order['customer']['externalId'])) { - $userId = $order['customer']['externalId']; + $recOrders[] = $arOrder['ID']; + } + if(count($resOrders) > 0){ + foreach($resCustomers as $key => $customerLoad){ + $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; + if (self::apiMethod($api, 'customerUpload', __METHOD__, $customerLoad, $site) === false) { + return false; + } + if (count($optionsSitesList) > 1) { + time_nanosleep(0, 250000000); + } } - - $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); - $arUpdateProps = array(); - while ($ar = $rsOrderProps->Fetch()) { - $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']); - $arUpdateProps[ $ar['CODE'] ] = array('ID' => $ar['ID'], 'TYPE' => $prop['TYPE'], 'VALUE' => $ar['VALUE']); + foreach($resOrders as $key => $orderLoad){ + $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; + if (self::apiMethod($api, 'orderUpload', __METHOD__, $orderLoad, $site) === false) { + return false; + } + if (count($optionsSitesList) > 1) { + time_nanosleep(0, 250000000); + } } - - $order['fio'] = trim( - implode( - ' ', - array( - isset($order['lastName']) ? $order['lastName'] : '', - isset($order['firstName']) ? $order['firstName'] : '', - isset($order['patronymic']) ? $order['patronymic'] : '', - ) - ) - ); - - if (isset($order['delivery']['address']['city'])) { - $order['location'] = $order['delivery']['address']['city']; + if ($failed == true && $failedIds !== false && count($failedIds) > 0) { + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, serialize(array_diff($failedIds, $recOrders))); + } elseif ($lastUpOrderId < max($recOrders) && $orderList === false) { + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_LAST_ID, max($recOrders)); } + } - if (isset($order['orderType']) && isset($optionsOrderTypes[ $order['orderType'] ])) { - if (isset($optionsOrderProps[$arFields['PERSON_TYPE_ID']])) { - foreach ($optionsOrderProps[$arFields['PERSON_TYPE_ID']] as $code => $value) { - if (in_array($code, array_keys($order)) === false && isset($optionsOrderProps[$optionsOrderTypes[$order['orderType']]][$code])) { - $order[ $code ] = $arUpdateProps[$optionsOrderProps[$arFields['PERSON_TYPE_ID']][$code]]['VALUE']; - } + return true; + } + + /** + * + * Creates order or returns array of order and customer for mass upload + * + * @param array $arFields + * @param $api + * @param $arParams + * @param $send + * @return boolean + * @return array - array('order' = $order, 'customer' => $customer) + */ + public static function orderCreate($arFields, $api, $arParams, $send = false, $site = null) { + if(!$api || empty($arParams)) { // add cond to check $arParams + return false; + } + if (empty($arFields)) { + self::eventLog('ICrmOrderActions::orderCreate', 'empty($arFields)', 'incorrect order'); + return false; + } + + if (isset($arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['city']) == false) { + $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'], 'CODE' => 'LOCATION')); + $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']]['city'] = $rsOrderProps->SelectedRowsCount() < 1 ? 'CITY' : 'LOCATION'; + } + + $normalizer = new RestNormalizer(); + $normalizer->setValidation(__DIR__ . '/config/retailcrm.json'); + + $customer = array(); + + if ($arFields['CANCELED'] == 'Y') { + $arFields['STATUS_ID'] = $arFields['CANCELED'].$arFields['CANCELED']; + } + + $order = array( + 'number' => $arFields['ACCOUNT_NUMBER'], + 'externalId' => $arFields['ID'], + 'createdAt' => new \DateTime($arFields['DATE_INSERT']), + 'customerId' => $arFields['USER_ID'], + 'discount' => $arFields['DISCOUNT_VALUE'], + 'markDateTime' => $arFields['DATE_MARKED'], + 'paymentType' => isset($arParams['optionsPayTypes'][$arFields['PAY_SYSTEM_ID']]) ? + $arParams['optionsPayTypes'][$arFields['PAY_SYSTEM_ID']] : '', + 'paymentStatus' => isset($arParams['optionsPayment'][$arFields['PAYED']]) ? + $arParams['optionsPayment'][$arFields['PAYED']] : '', + 'orderType' => isset($arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']]) ? + $arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']] : '', + 'contragentType' => isset($arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']]) ? + $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']] : '', + 'status' => isset($arParams['optionsPayStatuses'][$arFields['STATUS_ID']]) ? + $arParams['optionsPayStatuses'][$arFields['STATUS_ID']] : '', + 'statusComment' => $arFields['REASON_CANCELED'], + 'customerComment' => $arFields['USER_DESCRIPTION'], + 'managerComment' => $arFields['COMMENTS'], + 'delivery' => array( + 'cost' => $arFields['PRICE_DELIVERY'] + ), + ); + + $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); + while ($ar = $rsOrderProps->Fetch()) { + if ($search = array_search($ar['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) { + $order[$search] = $ar['VALUE']; + $customer[$search] = $ar['VALUE']; + } elseif ($search = array_search($ar['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) { + $order['customFields'][$search] = $ar['VALUE']; + } elseif ($search = array_search($ar['CODE'], $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']])) { + if (in_array($search, array('fio', 'phone', 'email'))) { + if ($search == 'fio') { + $order = array_merge($order, self::explodeFIO($ar['VALUE'])); + } else { + $order[$search] = $ar['VALUE']; } - } - - //update ordertype - CSaleOrder::Update($order['externalId'], array('PERSON_TYPE_ID' => $optionsOrderTypes[ $order['orderType'] ])); - - $arProp = CSaleOrderProps::GetList(array(), array('PERSON_TYPE_ID' => $optionsOrderTypes[ $order['orderType'] ])); - $typeParam = array(); - while ($ar = $arProp->Fetch()) { - $typeParam[ $ar['CODE'] ] = $ar['CODE']; - } - foreach (array_diff_key($arUpdateProps, $typeParam) as $code => $param) { - if (isset($arUpdateProps[$code])) { - CSaleOrderPropsValue::Delete($param['ID']); + } else { + $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']); + if ($prop['TYPE'] == 'LOCATION') { + $ar['VALUE'] = CSaleLocation::GetByID( + method_exists('CSaleLocation', 'getLocationIDbyCODE') ? + CSaleLocation::getLocationIDbyCODE($ar['VALUE']) : $ar['VALUE'] + ); + $ar['VALUE'] = $ar['VALUE']['CITY_NAME_LANG']; } + + $order['delivery']['address'][$search] = $ar['VALUE']; } - $arFields['PERSON_TYPE_ID'] = $optionsOrderTypes[ $order['orderType'] ]; } - - array_walk_recursive( - self::clearArr($order), - 'self::recursiveUpdate', - array( - 'update' => $arUpdateProps, - 'type' => $arFields['PERSON_TYPE_ID'], - 'options' => $optionsOrderProps, - 'orderId' => $order['externalId'] - ) - ); - - foreach($order['items'] as $item) { - if(isset($item['deleted']) && $item['deleted']) { - if ($p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['id']))->Fetch()) { - CSaleBasket::Delete($p['ID']); - } - continue; - } - - if (isset($item['offer']) === false && isset($item['offer']['externalId']) === false) { - continue; - } - - $p = CSaleBasket::GetList(array(),array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch(); - - if ($p == false) { - $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); - $iblock = CIBlock::GetByID($p['IBLOCK_ID'])->Fetch(); - $p['CATALOG_XML_ID'] = $iblock['XML_ID']; - $p['PRODUCT_XML_ID'] = $p['XML_ID']; - unset($p['XML_ID']); - } elseif ($propResult = CSaleBasket::GetPropsList(array(''),array('BASKET_ID' => $p['ID']))) { - while ($r = $propResult->Fetch()) { - $p['PROPS'][] = $r; - } - } - - $arProduct = array(); - - if (isset($item['created']) && $item['created'] == true) { - $productPrice = GetCatalogProductPrice($item['offer']['externalId'], 1); - $arProduct = array( - 'FUSER_ID' => $userId, - 'ORDER_ID' => $order['externalId'], - 'QUANTITY' => $item['quantity'], - 'CURRENCY' => $productPrice['CURRENCY'], - 'LID' => $LID, - 'PRODUCT_ID' => $item['offer']['externalId'], - 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'], - 'WEIGHT' => $p['WEIGHT'], - 'DELAY' => $p['DELAY'], - 'CAN_BUY' => $p['CAN_BUY'], - 'MODULE' => $p['MODULE'], - 'NOTES' => $item['comment'] ?: $p['NOTES'], - 'PRODUCT_PROVIDER_CLASS' => $p['PRODUCT_PROVIDER_CLASS'], - 'DETAIL_PAGE_URL' => $p['DETAIL_PAGE_URL'], - 'CATALOG_XML_ID' => $p['CATALOG_XML_ID'], - 'PRODUCT_XML_ID' => $p['PRODUCT_XML_ID'], - 'CUSTOM_PRICE' => 'Y' + } + if (strpos($arFields['DELIVERY_ID'], ":") !== false){ + $arFields["DELIVERY_ID"] = explode(":", $arFields["DELIVERY_ID"], 2); + if ($arDeliveryType = CSaleDeliveryHandler::GetBySID(reset($arFields["DELIVERY_ID"]))->GetNext()) { + if (array_key_exists(end($arFields["DELIVERY_ID"]), $arDeliveryType['PROFILES'])) { + $arFields["DELIVERY_SERVICE"] = array( + 'code' => implode('-', $arFields["DELIVERY_ID"]), + 'name' => $arDeliveryType['PROFILES'][end($arFields["DELIVERY_ID"])]['TITLE'] ); } + } + $arFields["DELIVERY_ID"] = reset($arFields["DELIVERY_ID"]); + } - if (isset($item['isCanceled']) == false) { - if (isset($item['initialPrice']) && $item['initialPrice']) { - $arProduct['PRICE'] = (double) $item['initialPrice']; + if (array_key_exists($arFields['DELIVERY_ID'], $arParams['optionsDelivTypes'])) { + $order['delivery']['code'] = $arParams['optionsDelivTypes'][$arFields["DELIVERY_ID"]]; + if (isset($arFields["DELIVERY_SERVICE"])) { + $order['delivery']['service'] = $arFields["DELIVERY_SERVICE"]; + } + } + + $rsOrderBasket = CSaleBasket::GetList(array('ID' => 'ASC'), array('ORDER_ID' => $arFields['ID'])); + while ($p = $rsOrderBasket->Fetch()) { + $item = array( + 'quantity' => $p['QUANTITY'], + 'productId' => $p['PRODUCT_ID'], + 'xmlId' => $p['PRODUCT_XML_ID'], + 'productName' => $p['NAME'], + 'comment' => $p['NOTES'], + 'createdAt' => new \DateTime($p['DATE_INSERT']) + ); + + $pp = CCatalogProduct::GetByID($p['PRODUCT_ID']); + if (is_null($pp['PURCHASING_PRICE']) == false) { + $item['purchasePrice'] = $pp['PURCHASING_PRICE']; + } + + $propCancel = CSaleBasket::GetPropsList(array(), array('BASKET_ID' => $p['ID'], 'CODE' => self::CANCEL_PROPERTY_CODE))->Fetch(); + if (!$propCancel || ($propCancel && !(int)$propCancel['VALUE'])) { + $item['discount'] = (double) $p['DISCOUNT_PRICE']; + $item['initialPrice'] = (double) $p['PRICE'] + (double) $p['DISCOUNT_PRICE']; + } + + $order['items'][] = $item; + } + + $arUser = CUser::GetByID($arFields['USER_ID'])->Fetch(); + + $customer = array( + 'externalId' => $arFields['USER_ID'], + 'lastName' => $arUser['LAST_NAME'], + 'firstName' => $arUser['NAME'], + 'patronymic' => $arUser['SECOND_NAME'], + 'phones' => array( + array('number' => $arUser['PERSONAL_PHONE']), + array('number' => $arUser['WORK_PHONE']) + ), + 'createdAt' => new \DateTime($arUser['DATE_REGISTER']), + 'contragentType' => $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']] + ); + + if(function_exists('intarocrm_get_order_type')) { + $orderType = intarocrm_get_order_type($arFields); + if ($orderType) { + $order['orderType'] = $orderType; + } + } + if (function_exists('intarocrm_before_order_send')) { + $newResOrder = intarocrm_before_order_send($order); + if (is_array($newResOrder) && !empty($newResOrder)) { + $order = $newResOrder; + } + } + + $customer = $normalizer->normalize($customer, 'customers'); + $order = $normalizer->normalize($order, 'orders'); + + if (isset($arParams['optionsSitesList']) && is_array($arParams['optionsSitesList']) && + array_key_exists($arFields['LID'], $arParams['optionsSitesList'])) { + $site = $arParams['optionsSitesList'][$arFields['LID']]; + } + + if($send) { + if (!self::apiMethod($api, 'customerEdit', __METHOD__, $customer, $site)) { + return false; + } + if ($orderEdit = self::apiMethod($api, 'orderEdit', __METHOD__, $order, $site)) { + return $orderEdit; + } else { + return false; + } + } + + return array( + 'order' => $order, + 'customer' => $customer + ); + } + + /** + * + * History update, cron usage only + * @global CUser $USER + * @return boolean + */ + public static function orderHistory() { + global $USER; + if (is_object($USER) == false) { + $USER = new RetailUser; + } + + if (!CModule::IncludeModule("iblock")) { + self::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found'); + return false; + } + if (!CModule::IncludeModule("sale")) { + self::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found'); + return false; + } + if (!CModule::IncludeModule("catalog")) { + self::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found'); + return false; + } + + $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); + $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0); + + $optionsOrderTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0))); + $optionsDelivTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0))); + $optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0))); + $optionsPayStatuses = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0))); // --statuses + $optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0))); + $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); + $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0)); + $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0)); + $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); + $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0)); + + foreach ($optionsOrderProps as $code => $value) { + if (isset($optionsLegalDetails[$code])) { + $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsLegalDetails[$code]); + } + if (isset($optionsCustomFields[$code])) { + $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsCustomFields[$code]); + } + $optionsOrderProps[$code]['location'] = 'LOCATION'; + if (array_search('CITY', $optionsOrderProps[$code]) == false) { + $optionsOrderProps[$code]['city'] = 'CITY'; + } + if (array_search('ZIP', $optionsOrderProps[$code]) == false) { + $optionsOrderProps[$code]['index'] = 'ZIP'; + } + } + + $api = new RetailCrm\RestApi($api_host, $api_key); + + $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null); + + if (is_null($dateStart)) { + $dateStart = new \DateTime(); + $dateStart = $dateStart->format('Y-m-d H:i:s'); + } + + try { + $orderHistory = $api->orderHistory($dateStart); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::orderHistory::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } + + $orderHistory = isset($orderHistory['orders']) ? $orderHistory['orders'] : array(); + + $dateFinish = $api->getGeneratedAt(); + if (is_null($dateFinish) || $dateFinish == false) { + $dateFinish = new \DateTime(); + } + + $defaultOrderType = 1; + $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y")); + if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { + $defaultOrderType = $arOrderTypesList['ID']; + } + + $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true; + + foreach ($orderHistory as $order) { + if (function_exists('intarocrm_order_pre_persist')) { + $order = intarocrm_order_pre_persist($order); + } + + if (!isset($order['externalId'])) { + + // custom orderType function + if (function_exists('intarocrm_set_order_type')) { + $orderType = intarocrm_set_order_type($order); + if ($orderType) { + $optionsOrderTypes[$order['orderType']] = $orderType; + } else { + $optionsOrderTypes[$order['orderType']] = $defaultOrderType; } - if (isset($item['discount'])) { - $arProduct['DISCOUNT_PRICE'] = $item['discount']; + } + + // we dont need new orders without any customers (can check only for externalId) + if (!isset($order['customer']['externalId'])) { + if (!isset($order['customer']['id'])) { + continue; } - if (isset($item['discountPercent'])) { - $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; - $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2); - $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice; + + $registerNewUser = true; + + if (!isset($order['customer']['email'])) { + $login = $order['customer']['email'] = uniqid('user_' . time()) . '@crm.com'; + } else { + $dbUser = CUser::GetList(($by = 'ID'), ($sort = 'ASC'), array('=EMAIL' => $order['email'])); + switch ($dbUser->SelectedRowsCount()) { + case 0: + $login = $order['customer']['email']; + break; + case 1: + $arUser = $dbUser->Fetch(); + $registeredUserID = $arUser['ID']; + $registerNewUser = false; + break; + default: + $login = uniqid('user_' . time()) . '@crm.com'; + break; + } } - if(isset($item['discount']) || isset($item['discountPercent'])) { - $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE']; + + if ($registerNewUser === true) { + $userPassword = uniqid(); + + $newUser = new CUser; + $arFields = array( + "NAME" => self::fromJSON($order['customer']['firstName']), + "LAST_NAME" => self::fromJSON($order['customer']['lastName']), + "EMAIL" => $order['customer']['email'], + "LOGIN" => $login, + "LID" => "ru", + "ACTIVE" => "Y", + "PASSWORD" => $userPassword, + "CONFIRM_PASSWORD" => $userPassword + ); + $registeredUserID = $newUser->Add($arFields); + if ($registeredUserID === false) { + self::eventLog('ICrmOrderActions::orderHistory', 'CUser::Register', 'Error register user'); + continue; + } + + try { + $api->customerFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } + } + + $order['customer']['externalId'] = $registeredUserID; + } + + // new order + $newOrderFields = array( + 'LID' => CSite::GetDefSite(), + 'PERSON_TYPE_ID' => isset($optionsOrderTypes[$order['orderType']]) ? $optionsOrderTypes[$order['orderType']] : $defaultOrderType, + 'PAYED' => 'N', + 'CANCELED' => 'N', + 'STATUS_ID' => 'N', + 'PRICE' => 0, + 'CURRENCY' => CCurrency::GetBaseCurrency(), + 'USER_ID' => $order['customer']['externalId'], + 'PAY_SYSTEM_ID' => 0, + 'PRICE_DELIVERY' => 0, + 'DELIVERY_ID' => 0, + 'DISCOUNT_VALUE' => 0, + 'USER_DESCRIPTION' => '' + ); + + if(count($optionsSitesList) > 1 && $lid = array_search($order['site'], $optionsSitesList)){ + $newOrderFields['LID'] = $lid; + } + + $externalId = CSaleOrder::Add($newOrderFields); + + if (!isset($order['externalId'])) { + try { + $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $externalId))); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::orderFixExternalIds::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } + } + $order['externalId'] = $externalId; + } + + if (isset($order['externalId']) && $order['externalId']) { + + // custom orderType function + if (function_exists('intarocrm_set_order_type')) { + $orderType = intarocrm_set_order_type($order); + if ($orderType) { + $optionsOrderTypes[$order['orderType']] = $orderType; + } else { + $optionsOrderTypes[$order['orderType']] = $defaultOrderType; + } + } + + $arFields = CSaleOrder::GetById($order['externalId']); + + // incorrect order + if ($arFields === false || empty($arFields)) { + continue; + } + + $LID = $arFields['LID']; + $userId = $arFields['USER_ID']; + + if(isset($order['customer']['externalId']) && !is_null($order['customer']['externalId'])) { + $userId = $order['customer']['externalId']; + } + + $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID'])); + $arUpdateProps = array(); + while ($ar = $rsOrderProps->Fetch()) { + $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']); + $arUpdateProps[ $ar['CODE'] ] = array('ID' => $ar['ID'], 'TYPE' => $prop['TYPE'], 'VALUE' => $ar['VALUE']); + } + + $order['fio'] = trim( + implode( + ' ', + array( + isset($order['lastName']) ? $order['lastName'] : '', + isset($order['firstName']) ? $order['firstName'] : '', + isset($order['patronymic']) ? $order['patronymic'] : '', + ) + ) + ); + + if (isset($order['delivery']['address']['city'])) { + $order['location'] = $order['delivery']['address']['city']; + } + + if (isset($order['orderType']) && isset($optionsOrderTypes[ $order['orderType'] ])) { + if (isset($optionsOrderProps[$arFields['PERSON_TYPE_ID']])) { + foreach ($optionsOrderProps[$arFields['PERSON_TYPE_ID']] as $code => $value) { + if (in_array($code, array_keys($order)) === false && isset($optionsOrderProps[$optionsOrderTypes[$order['orderType']]][$code])) { + $order[ $code ] = $arUpdateProps[$optionsOrderProps[$arFields['PERSON_TYPE_ID']][$code]]['VALUE']; + } + } + } + + //update ordertype + CSaleOrder::Update($order['externalId'], array('PERSON_TYPE_ID' => $optionsOrderTypes[ $order['orderType'] ])); + + $arProp = CSaleOrderProps::GetList(array(), array('PERSON_TYPE_ID' => $optionsOrderTypes[ $order['orderType'] ])); + $typeParam = array(); + while ($ar = $arProp->Fetch()) { + $typeParam[ $ar['CODE'] ] = $ar['CODE']; + } + foreach (array_diff_key($arUpdateProps, $typeParam) as $code => $param) { + if (isset($arUpdateProps[$code])) { + CSaleOrderPropsValue::Delete($param['ID']); + } + } + $arFields['PERSON_TYPE_ID'] = $optionsOrderTypes[ $order['orderType'] ]; + } + + array_walk_recursive( + self::clearArr($order), + 'self::recursiveUpdate', + array( + 'update' => $arUpdateProps, + 'type' => $arFields['PERSON_TYPE_ID'], + 'options' => $optionsOrderProps, + 'orderId' => $order['externalId'] + ) + ); + + foreach($order['items'] as $item) { + if(isset($item['deleted']) && $item['deleted']) { + if ($p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['id']))->Fetch()) { + CSaleBasket::Delete($p['ID']); + } + continue; + } + + if (isset($item['offer']) === false && isset($item['offer']['externalId']) === false) { + continue; + } + + $p = CSaleBasket::GetList(array(),array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch(); + + if ($p == false) { + $p = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); + $iblock = CIBlock::GetByID($p['IBLOCK_ID'])->Fetch(); + $p['CATALOG_XML_ID'] = $iblock['XML_ID']; + $p['PRODUCT_XML_ID'] = $p['XML_ID']; + unset($p['XML_ID']); + } elseif ($propResult = CSaleBasket::GetPropsList(array(''),array('BASKET_ID' => $p['ID']))) { + while ($r = $propResult->Fetch()) { + $p['PROPS'][] = $r; + } + } + + $arProduct = array(); + + if (isset($item['created']) && $item['created'] == true) { + $productPrice = GetCatalogProductPrice($item['offer']['externalId'], 1); + $arProduct = array( + 'FUSER_ID' => $userId, + 'ORDER_ID' => $order['externalId'], + 'QUANTITY' => $item['quantity'], + 'CURRENCY' => $productPrice['CURRENCY'], + 'LID' => $LID, + 'PRODUCT_ID' => $item['offer']['externalId'], + 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'], + 'WEIGHT' => $p['WEIGHT'], + 'DELAY' => $p['DELAY'], + 'CAN_BUY' => $p['CAN_BUY'], + 'MODULE' => $p['MODULE'], + 'NOTES' => $item['comment'] ?: $p['NOTES'], + 'PRODUCT_PROVIDER_CLASS' => $p['PRODUCT_PROVIDER_CLASS'], + 'DETAIL_PAGE_URL' => $p['DETAIL_PAGE_URL'], + 'CATALOG_XML_ID' => $p['CATALOG_XML_ID'], + 'PRODUCT_XML_ID' => $p['PRODUCT_XML_ID'], + 'CUSTOM_PRICE' => 'Y' + ); + } + + if (isset($item['isCanceled']) == false) { + if (isset($item['initialPrice']) && $item['initialPrice']) { + $arProduct['PRICE'] = (double) $item['initialPrice']; + } + if (isset($item['discount'])) { + $arProduct['DISCOUNT_PRICE'] = $item['discount']; + } + if (isset($item['discountPercent'])) { + $arProduct['DISCOUNT_VALUE'] = $item['discountPercent']; + $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2); + $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice; + } + if(isset($item['discount']) || isset($item['discountPercent'])) { + $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE']; + } + if (isset($item['offer']['name']) && $item['offer']['name']) { + $arProduct['NAME'] = self::fromJSON($item['offer']['name']); + } + $arProduct = self::updateCancelProp($arProduct, 0); + } elseif (isset($item['isCanceled'])) { + $arProduct['PRICE'] = 0; + $arProduct = self::updateCancelProp($arProduct, 1); + } + + if (isset($item['created']) && $item['created'] == true) { + CSaleBasket::Add($arProduct); + continue; + } + + if (count($p['PROPS']) > 0) { + $arProduct['PROPS'] = $p['PROPS']; + } + if (isset($item['quantity']) && $item['quantity']) { + $arProduct['QUANTITY'] = $item['quantity']; } if (isset($item['offer']['name']) && $item['offer']['name']) { $arProduct['NAME'] = self::fromJSON($item['offer']['name']); } - $arProduct = self::updateCancelProp($arProduct, 0); - } elseif (isset($item['isCanceled'])) { - $arProduct['PRICE'] = 0; - $arProduct = self::updateCancelProp($arProduct, 1); + + CSaleBasket::Update($p['ID'], $arProduct); + CSaleBasket::DeleteAll($userId); } - if (isset($item['created']) && $item['created'] == true) { - CSaleBasket::Add($arProduct); - continue; + if (isset($order['delivery']) === false || isset($order['delivery']['cost']) === false) { + $order['delivery']['cost'] = $arFields['PRICE_DELIVERY']; } - if (count($p['PROPS']) > 0) { - $arProduct['PROPS'] = $p['PROPS']; - } - if (isset($item['quantity']) && $item['quantity']) { - $arProduct['QUANTITY'] = $item['quantity']; - } - if (isset($item['offer']['name']) && $item['offer']['name']) { - $arProduct['NAME'] = self::fromJSON($item['offer']['name']); + if (isset($order['summ']) === false || $order['summ'] <= 0) { + $order['summ'] = $arFields['PRICE'] - $arFields['PRICE_DELIVERY']; } - CSaleBasket::Update($p['ID'], $arProduct); - CSaleBasket::DeleteAll($userId); - } + $wasCanaceled = $arFields['CANCELED'] == 'Y' ? true : false; - if (isset($order['delivery']) === false || isset($order['delivery']['cost']) === false) { - $order['delivery']['cost'] = $arFields['PRICE_DELIVERY']; - } - - if (isset($order['summ']) === false || $order['summ'] <= 0) { - $order['summ'] = $arFields['PRICE'] - $arFields['PRICE_DELIVERY']; - } - - $wasCanaceled = $arFields['CANCELED'] == 'Y' ? true : false; - - if (isset($optionsDelivTypes[$order['delivery']['code']])) { - $resultDeliveryTypeId = $optionsDelivTypes[$order['delivery']['code']]; - } else { - $resultDeliveryTypeId = isset($order['delivery']['service']) && isset($order['delivery']['service']['code']) ? - reset(explode(":", $arFields['DELIVERY_ID'], 1)) : - $arFields['DELIVERY_ID']; - } - - if(isset($order['delivery']['service']) && isset($order['delivery']['service']['code'])) { - $deliveryHandler = reset(CSaleDeliveryHandler::GetBySID($resultDeliveryTypeId)->arResult); - if (count($deliveryHandler) > 0 && array_key_exists($order['delivery']['service']['code'], $deliveryHandler['PROFILES'])) { - $resultDeliveryTypeId = $resultDeliveryTypeId . ':' . $order['delivery']['service']['code']; + if (isset($optionsDelivTypes[$order['delivery']['code']])) { + $resultDeliveryTypeId = $optionsDelivTypes[$order['delivery']['code']]; + } else { + $resultDeliveryTypeId = isset($order['delivery']['service']) && isset($order['delivery']['service']['code']) ? + reset(explode(":", $arFields['DELIVERY_ID'], 1)) : + $arFields['DELIVERY_ID']; } - } - // orderUpdate - $arFields = self::clearArr(array( - 'PRICE_DELIVERY' => $order['delivery']['cost'], - 'PRICE' => $order['summ'] + (double) $order['delivery']['cost'], - 'DATE_MARKED' => $order['markDatetime'], - 'USER_ID' => $userId, - 'PAY_SYSTEM_ID' => $optionsPayTypes[$order['paymentType']], - 'DELIVERY_ID' => $resultDeliveryTypeId, - 'STATUS_ID' => $optionsPayStatuses[$order['status']], - 'REASON_CANCELED' => self::fromJSON($order['statusComment']), - 'USER_DESCRIPTION' => self::fromJSON($order['customerComment']), - 'COMMENTS' => self::fromJSON($order['managerComment']) - )); - - if (isset($order['discount'])) { - $arFields['DISCOUNT_VALUE'] = $order['discount']; - $arFields['PRICE'] -= $order['discount']; - } - - if(!empty($arFields)) { - CSaleOrder::Update($order['externalId'], $arFields); - } - - if(isset($order['status']) && $order['status']) { - if(isset($optionsPayStatuses[$order['status']]) && $optionsPayStatuses[$order['status']]) { - // set STATUS_ID - CSaleOrder::StatusOrder($order['externalId'], $optionsPayStatuses[$order['status']]); - - if($wasCanaceled && $optionsPayStatuses[ $order['status'] ] != 'YY') { - CSaleOrder::CancelOrder($order['externalId'], "N", $order['statusComment']); - } elseif ($optionsPayStatuses[ $order['status'] ] == 'YY') { - CSaleOrder::CancelOrder($order['externalId'], "Y", $order['statusComment']); + if(isset($order['delivery']['service']) && isset($order['delivery']['service']['code'])) { + $deliveryHandler = reset(CSaleDeliveryHandler::GetBySID($resultDeliveryTypeId)->arResult); + if (count($deliveryHandler) > 0 && array_key_exists($order['delivery']['service']['code'], $deliveryHandler['PROFILES'])) { + $resultDeliveryTypeId = $resultDeliveryTypeId . ':' . $order['delivery']['service']['code']; } } - } - // set PAYED - if(isset($order['paymentStatus']) && $order['paymentStatus'] && $optionsPayment[$order['paymentStatus']]) { - CSaleOrder::PayOrder($order['externalId'], $optionsPayment[$order['paymentStatus']]); - } + // orderUpdate + $arFields = self::clearArr(array( + 'PRICE_DELIVERY' => $order['delivery']['cost'], + 'PRICE' => $order['summ'] + (double) $order['delivery']['cost'], + 'DATE_MARKED' => $order['markDatetime'], + 'USER_ID' => $userId, + 'PAY_SYSTEM_ID' => $optionsPayTypes[$order['paymentType']], + 'DELIVERY_ID' => $resultDeliveryTypeId, + 'STATUS_ID' => $optionsPayStatuses[$order['status']], + 'REASON_CANCELED' => self::fromJSON($order['statusComment']), + 'USER_DESCRIPTION' => self::fromJSON($order['customerComment']), + 'COMMENTS' => self::fromJSON($order['managerComment']) + )); - if(function_exists('intarocrm_order_post_persist')) { - intarocrm_order_post_persist($order); + if (isset($order['discount'])) { + $arFields['DISCOUNT_VALUE'] = $order['discount']; + $arFields['PRICE'] -= $order['discount']; + } + + if(!empty($arFields)) { + CSaleOrder::Update($order['externalId'], $arFields); + } + + if(isset($order['status']) && $order['status']) { + if(isset($optionsPayStatuses[$order['status']]) && $optionsPayStatuses[$order['status']]) { + // set STATUS_ID + CSaleOrder::StatusOrder($order['externalId'], $optionsPayStatuses[$order['status']]); + + if($wasCanaceled && $optionsPayStatuses[ $order['status'] ] != 'YY') { + CSaleOrder::CancelOrder($order['externalId'], "N", $order['statusComment']); + } elseif ($optionsPayStatuses[ $order['status'] ] == 'YY') { + CSaleOrder::CancelOrder($order['externalId'], "Y", $order['statusComment']); + } + } + } + + // set PAYED + if(isset($order['paymentStatus']) && $order['paymentStatus'] && $optionsPayment[$order['paymentStatus']]) { + CSaleOrder::PayOrder($order['externalId'], $optionsPayment[$order['paymentStatus']]); + } + + if(function_exists('intarocrm_order_post_persist')) { + intarocrm_order_post_persist($order); + } + } + } + + if (count($orderHistory) > 0) { + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateFinish->format('Y-m-d H:i:s')); + } + + $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false; + + return true; + } + + protected static function recursiveUpdate($value, $code, $param) + { + $value = self::fromJSON($value); + if (in_array($code, array('customer', 'items')) === false && isset($param['options'][$param['type']][$code])) { + self::updateProps($value, $code, $param); + } + } + + protected static function updateProps($value, $code, $param) + { + if ($value == '' || !CModule::IncludeModule('sale')) { + return false; + } + $add = false; + if (isset($param['update'][ $param['options'][$param['type']][$code] ]) == false) { + if ($arProp = CSaleOrderProps::GetList(array(), array('CODE' => $param['options'][$param['type']][$code]))->Fetch()) { + $param['update'][ $param['options'][$param['type']][$code] ] = array( + 'NAME' => $arProp['NAME'], + 'CODE' => $arProp['CODE'], + 'ORDER_PROPS_ID' => $arProp['ID'], + 'TYPE' => $arProp['TYPE'], + 'ORDER_ID' => $param['orderId'], + 'VALUE' => '' + ); + $add = true; + } else { + return false; + } + } + + if ($param['update'][ $param['options'][$param['type']][$code] ]['TYPE'] == 'LOCATION') { + $value = self::getLocation($value); + if ($value == false) { + return false; + } + } + + if ($param['update'][ $param['options'][$param['type']][$code] ]['VALUE'] != $value) { + if ($add === true) { + $param['update'][ $param['options'][$param['type']][$code] ]['VALUE'] = $value; + CSaleOrderPropsValue::Add($param['update'][ $param['options'][$param['type']][$code] ]); + } else { + CSaleOrderPropsValue::Update($param['update'][ $param['options'][$param['type']][$code] ]['ID'], array('VALUE' => $value)); } } } - if (count($orderHistory) > 0) { - COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateFinish->format('Y-m-d H:i:s')); - } - - $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false; - - return true; - } - - protected static function recursiveUpdate($value, $code, $param) - { - $value = self::fromJSON($value); - if (in_array($code, array('customer', 'items')) === false && isset($param['options'][$param['type']][$code])) { - self::updateProps($value, $code, $param); - } - } - - protected static function updateProps($value, $code, $param) - { - if ($value == '' || !CModule::IncludeModule('sale')) { - return false; - } - $add = false; - if (isset($param['update'][ $param['options'][$param['type']][$code] ]) == false) { - if ($arProp = CSaleOrderProps::GetList(array(), array('CODE' => $param['options'][$param['type']][$code]))->Fetch()) { - $param['update'][ $param['options'][$param['type']][$code] ] = array( - 'NAME' => $arProp['NAME'], - 'CODE' => $arProp['CODE'], - 'ORDER_PROPS_ID' => $arProp['ID'], - 'TYPE' => $arProp['TYPE'], - 'ORDER_ID' => $param['orderId'], - 'VALUE' => '' + protected static function updateCancelProp($arProduct, $value) { + if (isset($arProduct['PROPS'])) { + foreach($arProduct['PROPS'] as $key => $item) { + if ($item['CODE'] == self::CANCEL_PROPERTY_CODE) { + $arProduct['PROPS'][$key]['VALUE'] = $value; + break; + } + } + $arProduct['PROPS'][] = array( + 'NAME' => GetMessage('PRODUCT_CANCEL'), + 'CODE' => self::CANCEL_PROPERTY_CODE, + 'VALUE' => $value, + 'SORT' => 10, ); - $add = true; + } + + return $arProduct; + } + + public static function getLocation($value) { + if (is_string($value) === false) { + return false; + } elseif ($location = CSaleLocation::GetList(array(), array("LID" => LANGUAGE_ID, "CITY_NAME" => $value))->Fetch()) { + return method_exists('CSaleLocation', 'getLocationCODEbyID') ? + CSaleLocation::getLocationCODEbyID($location['ID']) : $location['ID']; } else { return false; } } - if ($param['update'][ $param['options'][$param['type']][$code] ]['TYPE'] == 'LOCATION') { - $value = self::getLocation($value); - if ($value == false) { - return false; - } + /** + * + * w+ event in bitrix log + */ + + public static function eventLog($auditType, $itemId, $description) { + + CEventLog::Add(array( + "SEVERITY" => "SECURITY", + "AUDIT_TYPE_ID" => $auditType, + "MODULE_ID" => self::$MODULE_ID, + "ITEM_ID" => $itemId, + "DESCRIPTION" => $description, + )); } - if ($param['update'][ $param['options'][$param['type']][$code] ]['VALUE'] != $value) { - if ($add === true) { - $param['update'][ $param['options'][$param['type']][$code] ]['VALUE'] = $value; - CSaleOrderPropsValue::Add($param['update'][ $param['options'][$param['type']][$code] ]); - } else { - CSaleOrderPropsValue::Update($param['update'][ $param['options'][$param['type']][$code] ]['ID'], array('VALUE' => $value)); - } - } - } + /** + * + * Agent function + * + * @return self name + */ - protected static function updateCancelProp($arProduct, $value) { - if (isset($arProduct['PROPS'])) { - foreach($arProduct['PROPS'] as $key => $item) { - if ($item['CODE'] == self::CANCEL_PROPERTY_CODE) { - $arProduct['PROPS'][$key]['VALUE'] = $value; + public static function uploadOrdersAgent() { + self::uploadOrders(); + $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); + if (is_array($failedIds) && !empty($failedIds)) { + self::uploadOrders(50, true); + } + + return 'ICrmOrderActions::uploadOrdersAgent();'; + } + + /** + * + * Agent function + * + * @return self name + */ + + public static function orderAgent() { + if(COption::GetOptionString('main', 'agents_use_crontab', 'N') != 'N') { + define('NO_AGENT_CHECK', true); + } + + self::uploadOrdersAgent(); + self::orderHistory(); + + return 'ICrmOrderActions::orderAgent();'; + } + + /** + * removes all empty fields from arrays + * working with nested arrs + * + * @param array $arr + * @return array + */ + public static function clearArr($arr) { + if (is_array($arr) === false) { + return $arr; + } + + $result = array(); + foreach ($arr as $index => $node ) { + $result[ $index ] = is_array($node) === true ? self::clearArr($node) : trim($node); + if ($result[ $index ] == '' || $result[ $index ] === null || count($result[ $index ]) < 1) { + unset($result[ $index ]); + } + } + + return $result; + } + + /** + * + * @global $APPLICATION + * @param $str in SITE_CHARSET + * @return $str in utf-8 + */ + public static function toJSON($str) { + global $APPLICATION; + + return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8'); + } + + /** + * + * @global $APPLICATION + * @param $str in utf-8 + * @return $str in SITE_CHARSET + */ + public static function fromJSON($str) { + global $APPLICATION; + + return $APPLICATION->ConvertCharset($str, 'utf-8', SITE_CHARSET); + } + + public static function explodeFIO($fio) { + $newFio = empty($fio) ? false : explode(" ", $fio, 3); + $result = array(); + switch (count($newFio)) { + default: + case 0: + $result['firstName'] = $fio; break; - } - } - $arProduct['PROPS'][] = array( - 'NAME' => GetMessage('PRODUCT_CANCEL'), - 'CODE' => self::CANCEL_PROPERTY_CODE, - 'VALUE' => $value, - 'SORT' => 10, - ); - } - - return $arProduct; - } - - public static function getLocation($value) { - if (is_string($value) === false) { - return false; - } elseif ($location = CSaleLocation::GetList(array(), array("LID" => LANGUAGE_ID, "CITY_NAME" => $value))->Fetch()) { - return method_exists('CSaleLocation', 'getLocationCODEbyID') ? - CSaleLocation::getLocationCODEbyID($location['ID']) : $location['ID']; - } else { - return false; - } - } - - /** - * - * w+ event in bitrix log - */ - - public static function eventLog($auditType, $itemId, $description) { - - CEventLog::Add(array( - "SEVERITY" => "SECURITY", - "AUDIT_TYPE_ID" => $auditType, - "MODULE_ID" => self::$MODULE_ID, - "ITEM_ID" => $itemId, - "DESCRIPTION" => $description, - )); - } - - /** - * - * Agent function - * - * @return self name - */ - - public static function uploadOrdersAgent() { - self::uploadOrders(); - $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); - if (is_array($failedIds) && !empty($failedIds)) { - self::uploadOrders(50, true); - } - - return 'ICrmOrderActions::uploadOrdersAgent();'; - } - - /** - * - * Agent function - * - * @return self name - */ - - public static function orderAgent() { - if(COption::GetOptionString('main', 'agents_use_crontab', 'N') != 'N') { - define('NO_AGENT_CHECK', true); - } - - self::uploadOrdersAgent(); - self::orderHistory(); - - return 'ICrmOrderActions::orderAgent();'; - } - - /** - * removes all empty fields from arrays - * working with nested arrs - * - * @param array $arr - * @return array - */ - public static function clearArr($arr) { - if (is_array($arr) === false) { - return $arr; - } - - $result = array(); - foreach ($arr as $index => $node ) { - $result[ $index ] = is_array($node) === true ? self::clearArr($node) : trim($node); - if ($result[ $index ] == '' || $result[ $index ] === null || count($result[ $index ]) < 1) { - unset($result[ $index ]); - } - } - - return $result; - } - - /** - * - * @global $APPLICATION - * @param $str in SITE_CHARSET - * @return $str in utf-8 - */ - public static function toJSON($str) { - global $APPLICATION; - - return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8'); - } - - /** - * - * @global $APPLICATION - * @param $str in utf-8 - * @return $str in SITE_CHARSET - */ - public static function fromJSON($str) { - global $APPLICATION; - - return $APPLICATION->ConvertCharset($str, 'utf-8', SITE_CHARSET); - } - - public static function explodeFIO($fio) { - $newFio = empty($fio) ? false : explode(" ", $fio, 3); - $result = array(); - switch (count($newFio)) { - default: - case 0: - $result['firstName'] = $fio; - break; - case 1: - $result['firstName'] = $newFio[0]; - break; - case 2: - $result = array( - 'lastName' => $newFio[0], - 'firstName' => $newFio[1] - ); - break; - case 3: - $result = array( - 'lastName' => $newFio[0], - 'firstName' => $newFio[1], - 'patronymic' => $newFio[2] - ); - break; - } - - return $result; - } - - public static function apiMethod($api, $methodApi, $method, $params, $site = null) { - switch($methodApi){ - case 'ordersGet': - case 'orderEdit': - case 'customerGet': - case 'customerEdit': - try { - $result = $api->$methodApi($params, 'externalId', $site); - } catch (\RetailCrm\Exception\CurlException $e) { - self::eventLog( - __CLASS__.'::'.$method, 'RetailCrm\RestApi::'.$methodApi.'::CurlException', - $e->getCode() . ': ' . $e->getMessage() + case 1: + $result['firstName'] = $newFio[0]; + break; + case 2: + $result = array( + 'lastName' => $newFio[0], + 'firstName' => $newFio[1] ); - - return false; - } - return $result; - - default: - try { - $result = $api->$methodApi($params, $site); - } catch (\RetailCrm\Exception\CurlException $e) { - self::eventLog( - __CLASS__.'::'.$method, 'RetailCrm\RestApi::'.$methodApi.'::CurlException', - $e->getCode() . ': ' . $e->getMessage() + break; + case 3: + $result = array( + 'lastName' => $newFio[0], + 'firstName' => $newFio[1], + 'patronymic' => $newFio[2] ); + break; + } - return false; - } - return $result; - } - } -} + return $result; + } -class RetailUser extends CUser -{ - public function GetID() - { - $rsUser = CUser::GetList(($by='ID'), ($order='DESC'), array('LOGIN' => 'retailcrm%')); - if ($arUser = $rsUser->Fetch()) { - return $arUser['ID']; - } else { - $retailUser = new CUser; - $userPassword = uniqid(); - $arFields = array( - "NAME" => 'retailcrm', - "LAST_NAME" => 'retailcrm', - "EMAIL" => 'retailcrm@retailcrm.com', - "LOGIN" => 'retailcrm', - "LID" => "ru", - "ACTIVE" => "Y", - "GROUP_ID" => array(2), - "PASSWORD" => $userPassword, - "CONFIRM_PASSWORD" => $userPassword + public static function apiMethod($api, $methodApi, $method, $params, $site = null) { + switch($methodApi){ + case 'ordersGet': + case 'orderEdit': + case 'customerGet': + case 'customerEdit': + try { + $result = $api->$methodApi($params, 'externalId', $site); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + __CLASS__.'::'.$method, 'RetailCrm\RestApi::'.$methodApi.'::CurlException', + $e->getCode() . ': ' . $e->getMessage() ); - $id = $retailUser->Add($arFields); - if (!$id) { - return null; + + return false; + } + return $result; + + default: + try { + $result = $api->$methodApi($params, $site); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + __CLASS__.'::'.$method, 'RetailCrm\RestApi::'.$methodApi.'::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } + return $result; + } + } + } + + class RetailUser extends CUser + { + public function GetID() + { + $rsUser = CUser::GetList(($by='ID'), ($order='DESC'), array('LOGIN' => 'retailcrm%')); + if ($arUser = $rsUser->Fetch()) { + return $arUser['ID']; } else { - return $id; + $retailUser = new CUser; + $userPassword = uniqid(); + $arFields = array( + "NAME" => 'retailcrm', + "LAST_NAME" => 'retailcrm', + "EMAIL" => 'retailcrm@retailcrm.com', + "LOGIN" => 'retailcrm', + "LID" => "ru", + "ACTIVE" => "Y", + "GROUP_ID" => array(2), + "PASSWORD" => $userPassword, + "CONFIRM_PASSWORD" => $userPassword + ); + $id = $retailUser->Add($arFields); + if (!$id) { + return null; + } else { + return $id; + } } } } diff --git a/intaro.intarocrm/export/export_run.php b/intaro.intarocrm/export/export_run.php index 3174dcb5..d1f17c90 100644 --- a/intaro.intarocrm/export/export_run.php +++ b/intaro.intarocrm/export/export_run.php @@ -1,83 +1,87 @@ 'Y')); -while ($ar = $rsSites->Fetch()){ - if($ar['DEF'] == 'Y'){ - $SERVER_NAME = $ar['SERVER_NAME'];//разделить потом с учетом многосайтовости - } +if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_run.php")){ + require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_run.php"); } +else{ + ignore_user_abort(true); + set_time_limit(0); -$iblockProperties = Array( - "article" => "article", - "manufacturer" => "manufacturer", - "color" =>"color", - "weight" => "weight", - "size" => "size", - "length" => "length", - "width" => "width", - "height" => "height", - ); -$IBLOCK_PROPERTY_SKU = array(); -$IBLOCK_PROPERTY_UNIT_SKU = array(); -foreach ($iblockProperties as $prop) { + global $APPLICATION; + if (!CModule::IncludeModule("iblock")) + return; + if (!CModule::IncludeModule("catalog")) + return; + if (!CModule::IncludeModule("intaro.intarocrm")) + return; - $skuUnitProps = ('IBLOCK_PROPERTY_UNIT_SKU' . "_" . $prop); - $skuUnitProps = $$skuUnitProps; - if (is_array($skuUnitProps)) { - foreach ($skuUnitProps as $iblock => $val) { - $IBLOCK_PROPERTY_UNIT_SKU[$iblock][$prop] = $val; + $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); + while ($ar = $rsSites->Fetch()){ + if($ar['DEF'] == 'Y'){ + $SERVER_NAME = $ar['SERVER_NAME'];//разделить потом с учетом многосайтовости } } - $skuProps = ('IBLOCK_PROPERTY_SKU' . "_" . $prop); - $skuProps = $$skuProps; - if (is_array($skuProps)) { - foreach ($skuProps as $iblock => $val) { - $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; + $iblockProperties = Array( + "article" => "article", + "manufacturer" => "manufacturer", + "color" =>"color", + "weight" => "weight", + "size" => "size", + "length" => "length", + "width" => "width", + "height" => "height", + ); + $IBLOCK_PROPERTY_SKU = array(); + $IBLOCK_PROPERTY_UNIT_SKU = array(); + foreach ($iblockProperties as $prop) { + + $skuUnitProps = ('IBLOCK_PROPERTY_UNIT_SKU' . "_" . $prop); + $skuUnitProps = $$skuUnitProps; + if (is_array($skuUnitProps)) { + foreach ($skuUnitProps as $iblock => $val) { + $IBLOCK_PROPERTY_UNIT_SKU[$iblock][$prop] = $val; + } + } + + $skuProps = ('IBLOCK_PROPERTY_SKU' . "_" . $prop); + $skuProps = $$skuProps; + if (is_array($skuProps)) { + foreach ($skuProps as $iblock => $val) { + $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; + } } } -} -$IBLOCK_PROPERTY_PRODUCT = array(); -$IBLOCK_PROPERTY_UNIT_PRODUCT = array(); -foreach ($iblockProperties as $prop) { + $IBLOCK_PROPERTY_PRODUCT = array(); + $IBLOCK_PROPERTY_UNIT_PRODUCT = array(); + foreach ($iblockProperties as $prop) { - $productUnitProps = "IBLOCK_PROPERTY_UNIT_PRODUCT" . "_" . $prop; - $productUnitProps = $$productUnitProps; - if (is_array($productUnitProps)) { - foreach ($productUnitProps as $iblock => $val) { - $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock][$prop] = $val; + $productUnitProps = "IBLOCK_PROPERTY_UNIT_PRODUCT" . "_" . $prop; + $productUnitProps = $$productUnitProps; + if (is_array($productUnitProps)) { + foreach ($productUnitProps as $iblock => $val) { + $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock][$prop] = $val; + } + } + + $productProps = "IBLOCK_PROPERTY_PRODUCT" . "_" . $prop; + $productProps = $$productProps; + if (is_array($productProps)) { + foreach ($productProps as $iblock => $val) { + $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; + } } } - $productProps = "IBLOCK_PROPERTY_PRODUCT" . "_" . $prop; - $productProps = $$productProps; - if (is_array($productProps)) { - foreach ($productProps as $iblock => $val) { - $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; - } - } -} - -$loader = new ICMLLoader(); -$loader->profileID = $PROFILE_ID; -$loader->iblocks = $IBLOCK_EXPORT; -$loader->propertiesSKU = $IBLOCK_PROPERTY_SKU; -$loader->propertiesUnitSKU = $IBLOCK_PROPERTY_UNIT_SKU; -$loader->propertiesProduct = $IBLOCK_PROPERTY_PRODUCT; -$loader->propertiesUnitProduct = $IBLOCK_PROPERTY_UNIT_PRODUCT; -$loader->filename = $SETUP_FILE_NAME; -$loader->serverName = $SERVER_NAME; -$loader->application = $APPLICATION; -$loader->loadPurchasePrice = $LOAD_PURCHASE_PRICE == 'Y'; -$loader->Load(); \ No newline at end of file + $loader = new ICMLLoader(); + $loader->profileID = $PROFILE_ID; + $loader->iblocks = $IBLOCK_EXPORT; + $loader->propertiesSKU = $IBLOCK_PROPERTY_SKU; + $loader->propertiesUnitSKU = $IBLOCK_PROPERTY_UNIT_SKU; + $loader->propertiesProduct = $IBLOCK_PROPERTY_PRODUCT; + $loader->propertiesUnitProduct = $IBLOCK_PROPERTY_UNIT_PRODUCT; + $loader->filename = $SETUP_FILE_NAME; + $loader->serverName = $SERVER_NAME; + $loader->application = $APPLICATION; + $loader->loadPurchasePrice = $LOAD_PURCHASE_PRICE == 'Y'; + $loader->Load(); +} \ No newline at end of file diff --git a/intaro.intarocrm/export/export_setup.php b/intaro.intarocrm/export/export_setup.php index 797235f3..968b8ca1 100644 --- a/intaro.intarocrm/export/export_setup.php +++ b/intaro.intarocrm/export/export_setup.php @@ -1,455 +1,356 @@ "article", - "manufacturer" => "manufacturer", - "color" =>"color", - "size" => "size", - "weight" => "weight", - "length" => "length", - "width" => "width", - "height" => "height", - ); - -if(!check_bitrix_sessid()) return; - -__IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/lang/", "/icml_export_setup.php")); - -$MODULE_ID = 'intaro.intarocrm'; -$CRM_CATALOG_BASE_PRICE = 'catalog_base_price'; -$basePriceId = COption::GetOptionString($MODULE_ID, $CRM_CATALOG_BASE_PRICE . '_' . $_REQUEST['PROFILE_ID'], 1); - -$arResult['PRICE_TYPES'] = array(); -$dbPriceType = CCatalogGroup::GetList( - array("SORT" => "ASC"), array(), array(), array(), array("ID", "NAME", "BASE") -); - -while ($arPriceType = $dbPriceType->Fetch()) { - $arResult['PRICE_TYPES'][$arPriceType['ID']] = $arPriceType; +if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_setup.php")){ + require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_setup.php"); } +else{ + $iblockProperties = Array( + "article" => "article", + "manufacturer" => "manufacturer", + "color" =>"color", + "size" => "size", + "weight" => "weight", + "length" => "length", + "width" => "width", + "height" => "height", + ); -if (($ACTION == 'EXPORT' || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && $STEP == 1) -{ + if(!check_bitrix_sessid()) return; - if (isset($arOldSetupVars['SETUP_FILE_NAME'])) - $SETUP_FILE_NAME = $arOldSetupVars['SETUP_FILE_NAME']; - if (isset($arOldSetupVars['LOAD_PURCHASE_PRICE'])) - $LOAD_PURCHASE_PRICE = $arOldSetupVars['LOAD_PURCHASE_PRICE']; - if (isset($arOldSetupVars['SETUP_PROFILE_NAME'])) - $SETUP_PROFILE_NAME = $arOldSetupVars['SETUP_PROFILE_NAME']; - if (isset($arOldSetupVars['IBLOCK_EXPORT'])) - $IBLOCK_EXPORT = $arOldSetupVars['IBLOCK_EXPORT']; + __IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/lang/", "/icml_export_setup.php")); - $IBLOCK_PROPERTY_SKU = array(); - $IBLOCK_PROPERTY_UNIT_SKU = array(); - foreach ($iblockProperties as $prop) { - foreach ($arOldSetupVars['IBLOCK_PROPERTY_SKU'. '_' . $prop] as $iblock => $val) { - $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; - } - foreach ($arOldSetupVars['IBLOCK_PROPERTY_UNIT_SKU'. '_' . $prop] as $iblock => $val) { - $IBLOCK_PROPERTY_UNIT_SKU[$iblock][$prop] = $val; - } - } + $MODULE_ID = 'intaro.intarocrm'; + $CRM_CATALOG_BASE_PRICE = 'catalog_base_price'; + $basePriceId = COption::GetOptionString($MODULE_ID, $CRM_CATALOG_BASE_PRICE . '_' . $_REQUEST['PROFILE_ID'], 1); + $arResult['PRICE_TYPES'] = array(); + $dbPriceType = CCatalogGroup::GetList( + array("SORT" => "ASC"), array(), array(), array(), array("ID", "NAME", "BASE") + ); - $IBLOCK_PROPERTY_PRODUCT = array(); - $IBLOCK_PROPERTY_UNIT_PRODUCT = array(); - foreach ($iblockProperties as $prop) { - foreach ($arOldSetupVars['IBLOCK_PROPERTY_PRODUCT'. '_' . $prop] as $iblock => $val) { - $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; - } - foreach ($arOldSetupVars['IBLOCK_PROPERTY_UNIT_PRODUCT'. '_' . $prop] as $iblock => $val) { - $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock][$prop] = $val; - } - } -} - - - -if ($STEP>1) -{ - - if (strlen($SETUP_FILE_NAME)<=0) - { - $arSetupErrors[] = GetMessage("CET_ERROR_NO_FILENAME"); - } - elseif ($APPLICATION->GetFileAccessPermission($SETUP_FILE_NAME) < "W") - { - $arSetupErrors[] = str_replace("#FILE#", $SETUP_FILE_NAME, GetMessage('CET_YAND_RUN_ERR_SETUP_FILE_ACCESS_DENIED')); + while ($arPriceType = $dbPriceType->Fetch()) { + $arResult['PRICE_TYPES'][$arPriceType['ID']] = $arPriceType; } - if (($ACTION=="EXPORT_SETUP" || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && strlen($SETUP_PROFILE_NAME)<=0) + if (($ACTION == 'EXPORT' || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && $STEP == 1) { - $arSetupErrors[] = GetMessage("CET_ERROR_NO_PROFILE_NAME"); + + if (isset($arOldSetupVars['SETUP_FILE_NAME'])) + $SETUP_FILE_NAME = $arOldSetupVars['SETUP_FILE_NAME']; + if (isset($arOldSetupVars['LOAD_PURCHASE_PRICE'])) + $LOAD_PURCHASE_PRICE = $arOldSetupVars['LOAD_PURCHASE_PRICE']; + if (isset($arOldSetupVars['SETUP_PROFILE_NAME'])) + $SETUP_PROFILE_NAME = $arOldSetupVars['SETUP_PROFILE_NAME']; + if (isset($arOldSetupVars['IBLOCK_EXPORT'])) + $IBLOCK_EXPORT = $arOldSetupVars['IBLOCK_EXPORT']; + + $IBLOCK_PROPERTY_SKU = array(); + $IBLOCK_PROPERTY_UNIT_SKU = array(); + foreach ($iblockProperties as $prop) { + foreach ($arOldSetupVars['IBLOCK_PROPERTY_SKU'. '_' . $prop] as $iblock => $val) { + $IBLOCK_PROPERTY_SKU[$iblock][$prop] = $val; + } + foreach ($arOldSetupVars['IBLOCK_PROPERTY_UNIT_SKU'. '_' . $prop] as $iblock => $val) { + $IBLOCK_PROPERTY_UNIT_SKU[$iblock][$prop] = $val; + } + } + + + $IBLOCK_PROPERTY_PRODUCT = array(); + $IBLOCK_PROPERTY_UNIT_PRODUCT = array(); + foreach ($iblockProperties as $prop) { + foreach ($arOldSetupVars['IBLOCK_PROPERTY_PRODUCT'. '_' . $prop] as $iblock => $val) { + $IBLOCK_PROPERTY_PRODUCT[$iblock][$prop] = $val; + } + foreach ($arOldSetupVars['IBLOCK_PROPERTY_UNIT_PRODUCT'. '_' . $prop] as $iblock => $val) { + $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock][$prop] = $val; + } + } + } + + + + if ($STEP>1) + { + + if (strlen($SETUP_FILE_NAME)<=0) + { + $arSetupErrors[] = GetMessage("CET_ERROR_NO_FILENAME"); + } + elseif ($APPLICATION->GetFileAccessPermission($SETUP_FILE_NAME) < "W") + { + $arSetupErrors[] = str_replace("#FILE#", $SETUP_FILE_NAME, GetMessage('CET_YAND_RUN_ERR_SETUP_FILE_ACCESS_DENIED')); + } + + if (($ACTION=="EXPORT_SETUP" || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && strlen($SETUP_PROFILE_NAME)<=0) + { + $arSetupErrors[] = GetMessage("CET_ERROR_NO_PROFILE_NAME"); + } + + if (!empty($arSetupErrors)) + { + $STEP = 1; + } } if (!empty($arSetupErrors)) + echo ShowError(implode('
', $arSetupErrors)); + + + if ($STEP==1) { - $STEP = 1; - } -} -if (!empty($arSetupErrors)) - echo ShowError(implode('
', $arSetupErrors)); - - -if ($STEP==1) -{ - - -?> - - - -
- - -

-

- GetMessage("PROPERTY_ARTICLE_HEADER_NAME"), - "manufacturer" => GetMessage("PROPERTY_MANUFACTURER_HEADER_NAME"), - "color" => GetMessage("PROPERTY_COLOR_HEADER_NAME"), - "size" => GetMessage("PROPERTY_SIZE_HEADER_NAME"), - "weight" => GetMessage("PROPERTY_WEIGHT_HEADER_NAME"), - "length" => GetMessage("PROPERTY_LENGTH_HEADER_NAME"), - "width" => GetMessage("PROPERTY_WIDTH_HEADER_NAME"), - "height" => GetMessage("PROPERTY_HEIGHT_HEADER_NAME"), - ); - - $iblockFieldsName = Array( - - "weight" => Array("code" => "catalog_size" , "name" => GetMessage("SELECT_WEIGHT_PROPERTY_NAME"), 'unit' => 'mass'), - "length" => Array("code" => "catalog_length" , "name" => GetMessage("SELECT_LENGTH_PROPERTY_NAME"), 'unit' => 'length'), - "width" => Array("code" => "catalog_width" , "name" => GetMessage("SELECT_WIDTH_PROPERTY_NAME"), 'unit' => 'length'), - "height" => Array("code" => "catalog_height" , "name" => GetMessage("SELECT_HEIGHT_PROPERTY_NAME"), 'unit' => 'length'), - ); - - $iblockPropertiesHint = Array( - "article" => Array("ARTICLE", "ART", "ARTNUMBER", "ARTICUL", "ARTIKUL"), - "manufacturer" => Array("MANUFACTURER", "PROISVODITEL", "PROISVOD", "PROISV"), - "color" => Array("COLOR", "CVET"), - "size" => Array("SIZE", "RAZMER"), - "weight" => Array("WEIGHT", "VES", "VEC"), - "length" => Array("LENGTH", "DLINA"), - "width" => Array("WIDTH", "SHIRINA"), - "height" => Array("HEIGHT", "VISOTA"), - ); - - $units = Array( - 'length' => Array( - 'mm' => GetMessage("UNIT_MEASUREMENT_MM"), - 'cm' => GetMessage("UNIT_MEASUREMENT_CM"), - 'm' => GetMessage("UNIT_MEASUREMENT_M"), - ), - 'mass' => Array( - 'mg' => GetMessage("UNIT_MEASUREMENT_MG"), - 'g' => GetMessage("UNIT_MEASUREMENT_G"), - 'kg' => GetMessage("UNIT_MEASUREMENT_KG"), - ) - ); - - $hintUnit = Array( - 'length' => 'mm', - 'mass' => 'g' - ); - - $boolAll = false; - $intCountChecked = 0; - $intCountAvailIBlock = 0; - $arIBlockList = array(); - $db_res = CIBlock::GetList(Array("IBLOCK_TYPE"=>"ASC", "NAME"=>"ASC"),array('CHECK_PERMISSIONS' => 'Y','MIN_PERMISSION' => 'W')); - - while ($iblock = $db_res->Fetch()) - { - if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) - { - if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") - { - $propertiesSKU = null; - if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") - { - $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]); - - $db_properties = CIBlock::GetProperties($iblockOffer['IBLOCK_ID'], Array()); - while($prop = $db_properties->Fetch()) - $propertiesSKU[] = $prop; - - $oldPropertySKU = null; - if (isset($IBLOCK_PROPERTY_SKU[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertySKU[$key] = $IBLOCK_PROPERTY_SKU[$iblock['ID']][$key]; - } - } - - $oldPropertyUnitSKU = null; - if (isset($IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertyUnitSKU[$key] = $IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']][$key]; - } - } - } - - - $propertiesProduct = null; - $db_properties = CIBlock::GetProperties($iblock['ID'], Array()); - while($prop = $db_properties->Fetch()) - $propertiesProduct[] = $prop; - - $oldPropertyProduct = null; - if (isset($IBLOCK_PROPERTY_PRODUCT[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertyProduct[$key] = $IBLOCK_PROPERTY_PRODUCT[$iblock['ID']][$key]; - } - } - - $oldPropertyUnitProduct = null; - if (isset($IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']])) { - foreach ($iblockPropertiesName as $key => $prop) { - $oldPropertyUnitProduct[$key] = $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']][$key]; - } - } - - $arSiteList = array(); - $rsSites = CIBlock::GetSite($iblock["ID"]); - while ($arSite = $rsSites->Fetch()) - { - $arSiteList[] = $arSite["SITE_ID"]; - } - - if (count($IBLOCK_EXPORT) != 0) - $boolExport = (in_array($iblock['ID'], $IBLOCK_EXPORT)); - else - $boolExport = true; - - - $arIBlockList[] = array( - 'ID' => $iblock['ID'], - 'NAME' => $iblock['NAME'], - 'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'], - 'IBLOCK_EXPORT' => $boolExport, - 'PROPERTIES_SKU' => $propertiesSKU, - 'PROPERTIES_PRODUCT' => $propertiesProduct, - 'OLD_PROPERTY_SKU_SELECT' => $oldPropertySKU, - 'OLD_PROPERTY_UNIT_SKU_SELECT' => $oldPropertyUnitSKU, - 'OLD_PROPERTY_PRODUCT_SELECT' => $oldPropertyProduct, - 'OLD_PROPERTY_UNIT_PRODUCT_SELECT' => $oldPropertyUnitProduct, - 'SITE_LIST' => '('.implode(' ',$arSiteList).')', - ); - - if ($boolExport) - $intCountChecked++; - $intCountAvailIBlock++; - } - } - } - if (count($IBLOCK_EXPORT) != 0) { - if ($intCountChecked == $intCountAvailIBlock) - $boolAll = true; - } else { - $intCountChecked = $intCountAvailIBlock; - $boolAll = true; - } ?> - - > -
-
-
- - $arIBlock):?> + + + + + +

+

+ GetMessage("PROPERTY_ARTICLE_HEADER_NAME"), + "manufacturer" => GetMessage("PROPERTY_MANUFACTURER_HEADER_NAME"), + "color" => GetMessage("PROPERTY_COLOR_HEADER_NAME"), + "size" => GetMessage("PROPERTY_SIZE_HEADER_NAME"), + "weight" => GetMessage("PROPERTY_WEIGHT_HEADER_NAME"), + "length" => GetMessage("PROPERTY_LENGTH_HEADER_NAME"), + "width" => GetMessage("PROPERTY_WIDTH_HEADER_NAME"), + "height" => GetMessage("PROPERTY_HEIGHT_HEADER_NAME"), + ); + + $iblockFieldsName = Array( + + "weight" => Array("code" => "catalog_size" , "name" => GetMessage("SELECT_WEIGHT_PROPERTY_NAME"), 'unit' => 'mass'), + "length" => Array("code" => "catalog_length" , "name" => GetMessage("SELECT_LENGTH_PROPERTY_NAME"), 'unit' => 'length'), + "width" => Array("code" => "catalog_width" , "name" => GetMessage("SELECT_WIDTH_PROPERTY_NAME"), 'unit' => 'length'), + "height" => Array("code" => "catalog_height" , "name" => GetMessage("SELECT_HEIGHT_PROPERTY_NAME"), 'unit' => 'length'), + ); + + $iblockPropertiesHint = Array( + "article" => Array("ARTICLE", "ART", "ARTNUMBER", "ARTICUL", "ARTIKUL"), + "manufacturer" => Array("MANUFACTURER", "PROISVODITEL", "PROISVOD", "PROISV"), + "color" => Array("COLOR", "CVET"), + "size" => Array("SIZE", "RAZMER"), + "weight" => Array("WEIGHT", "VES", "VEC"), + "length" => Array("LENGTH", "DLINA"), + "width" => Array("WIDTH", "SHIRINA"), + "height" => Array("HEIGHT", "VISOTA"), + ); + + $units = Array( + 'length' => Array( + 'mm' => GetMessage("UNIT_MEASUREMENT_MM"), + 'cm' => GetMessage("UNIT_MEASUREMENT_CM"), + 'm' => GetMessage("UNIT_MEASUREMENT_M"), + ), + 'mass' => Array( + 'mg' => GetMessage("UNIT_MEASUREMENT_MG"), + 'g' => GetMessage("UNIT_MEASUREMENT_G"), + 'kg' => GetMessage("UNIT_MEASUREMENT_KG"), + ) + ); + + $hintUnit = Array( + 'length' => 'mm', + 'mass' => 'g' + ); + + $boolAll = false; + $intCountChecked = 0; + $intCountAvailIBlock = 0; + $arIBlockList = array(); + $db_res = CIBlock::GetList(Array("IBLOCK_TYPE"=>"ASC", "NAME"=>"ASC"),array('CHECK_PERMISSIONS' => 'Y','MIN_PERMISSION' => 'W')); + + while ($iblock = $db_res->Fetch()) + { + if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) + { + if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") + { + $propertiesSKU = null; + if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") + { + $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]); + + $db_properties = CIBlock::GetProperties($iblockOffer['IBLOCK_ID'], Array()); + while($prop = $db_properties->Fetch()) + $propertiesSKU[] = $prop; + + $oldPropertySKU = null; + if (isset($IBLOCK_PROPERTY_SKU[$iblock['ID']])) { + foreach ($iblockPropertiesName as $key => $prop) { + $oldPropertySKU[$key] = $IBLOCK_PROPERTY_SKU[$iblock['ID']][$key]; + } + } + + $oldPropertyUnitSKU = null; + if (isset($IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']])) { + foreach ($iblockPropertiesName as $key => $prop) { + $oldPropertyUnitSKU[$key] = $IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']][$key]; + } + } + } + + + $propertiesProduct = null; + $db_properties = CIBlock::GetProperties($iblock['ID'], Array()); + while($prop = $db_properties->Fetch()) + $propertiesProduct[] = $prop; + + $oldPropertyProduct = null; + if (isset($IBLOCK_PROPERTY_PRODUCT[$iblock['ID']])) { + foreach ($iblockPropertiesName as $key => $prop) { + $oldPropertyProduct[$key] = $IBLOCK_PROPERTY_PRODUCT[$iblock['ID']][$key]; + } + } + + $oldPropertyUnitProduct = null; + if (isset($IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']])) { + foreach ($iblockPropertiesName as $key => $prop) { + $oldPropertyUnitProduct[$key] = $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']][$key]; + } + } + + $arSiteList = array(); + $rsSites = CIBlock::GetSite($iblock["ID"]); + while ($arSite = $rsSites->Fetch()) + { + $arSiteList[] = $arSite["SITE_ID"]; + } + + if (count($IBLOCK_EXPORT) != 0) + $boolExport = (in_array($iblock['ID'], $IBLOCK_EXPORT)); + else + $boolExport = true; + + + $arIBlockList[] = array( + 'ID' => $iblock['ID'], + 'NAME' => $iblock['NAME'], + 'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'], + 'IBLOCK_EXPORT' => $boolExport, + 'PROPERTIES_SKU' => $propertiesSKU, + 'PROPERTIES_PRODUCT' => $propertiesProduct, + 'OLD_PROPERTY_SKU_SELECT' => $oldPropertySKU, + 'OLD_PROPERTY_UNIT_SKU_SELECT' => $oldPropertyUnitSKU, + 'OLD_PROPERTY_PRODUCT_SELECT' => $oldPropertyProduct, + 'OLD_PROPERTY_UNIT_PRODUCT_SELECT' => $oldPropertyUnitProduct, + 'SITE_LIST' => '('.implode(' ',$arSiteList).')', + ); + + if ($boolExport) + $intCountChecked++; + $intCountAvailIBlock++; + } + } + } + if (count($IBLOCK_EXPORT) != 0) { + if ($intCountChecked == $intCountAvailIBlock) + $boolAll = true; + } else { + $intCountChecked = $intCountAvailIBlock; + $boolAll = true; + } + + ?> + + + > +
+
+ + $arIBlock):?>
- - ]" - id="IBLOCK_EXPORT" - value="" - - onclick="checkOne(this,);" - > -
-
-
- > - - - - - +
+ + ]" + id="IBLOCK_EXPORT" + value="" + + onclick="checkOne(this,);" + > +
+
+
+
-
-
-
-
> + + - - - - - - $property): ?> - - - - - - - + + + + - - =') && array_key_exists($key, $iblockFieldsName)) :?> - "> - $field): ?> + $property): ?> - - + + + - - + + -
-
+
- +
- - - - - - -
+ + + + ?> + > + + + + =') && array_key_exists($key, $iblockFieldsName)){?> + + - - - + + + +
+
-
-
+ + =') && array_key_exists($key, $iblockFieldsName)) :?> + "> + $field): ?> + + + + + + + + "> + + + + + + =') && array_key_exists($key, $iblockFieldsName)) : ?> + + + + + + + + + + + + + + + +
+
+
+ + +
+ +
- - +

- -
+

+ +
+
-

+   + > -

- -
-
- -   - > - -
-
-
- -   - - -
-
-
- - -

-


- - - + + var table = BX(obj.id.replace('IBLOCK_EXPORT','IBLOCK_EXPORT_TABLE')); + if (obj.checked) + BX.removeClass(table,"iblock-export-table-display-none"); + var easing = new BX.easing({ + duration : 150, + start : {opacity : obj.checked ? 0 : 100 }, + finish : {opacity: obj.checked ? 100 : 0 }, + transition : BX.easing.transitions.linear, + step : function(state){ + table.style.opacity = state.opacity/100; + }, + complete : function() { + if (!obj.checked) + BX.addClass(table,"iblock-export-table-display-none"); + } + }); + easing.animate(); + var boolCheck = obj.checked; + var intCurrent = parseInt(BX('count_checked').value); + intCurrent += (boolCheck ? 1 : -1); + BX('icml_export_all').checked = (intCurrent < cnt ? false : true); + BX('count_checked').value = intCurrent; + }; + function propertyChange(obj) + { + if (BX(obj.id).value !== 'none') { + if (obj.id.indexOf("SKU") !== -1) + BX(obj.id.replace('SKU','PRODUCT')).value = 'none'; + else + BX(obj.id.replace('PRODUCT','SKU')).value = 'none'; + } + }; + - - + + + + + + "> + + + + "> + + +
- - "> - - - - "> - - - - - \ No newline at end of file