diff --git a/CHANGELOG.md b/CHANGELOG.md index 48f08e15..9443b6f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 2016-09-12 v.2.0.0 +* Добавлена возможность изменять файлы основных классов(ICMLLoader и ICrmOrderActions) и экспорт каталога без потери обновлений +* Исправлены мелкие ошибки + ## 2015-11-09 v.1.1.3 * Добавлено логгирование в файл для приходящей из црм и уходящей в црм информации * Изменен механизм добавления товара в заказ diff --git a/intaro.intarocrm/classes/general/ICMLLoader.php b/intaro.intarocrm/classes/general/ICMLLoader.php deleted file mode 100644 index 52b6aed6..00000000 --- a/intaro.intarocrm/classes/general/ICMLLoader.php +++ /dev/null @@ -1,561 +0,0 @@ - 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 - ); - - 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 - ); - $order = array("id"); - $arNavStatParams = Array( - "iNumPage" => 1, - "nPageSize" => $this->pageSize, - ); - - // Cycle page to page - do { - // Get products on this page - $elems = array(); - $dbResProductsIds = CIBlockElement::GetList($order, $filter, false, $arNavStatParams, array('ID')); - while($obIds = $dbResProductsIds->Fetch()) - { - $elems[] = $obIds['ID']; - } - $arfilter = array( - "IBLOCK_ID" => $id, - "ID" => $elems - ); - - $dbResProducts = CIBlockElement::GetList($order, $arfilter, false, false, $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']; - } - } - unset($product); - unset($detailPicture, $previewPicture, $picture); - - $pictureIDs = array_keys($pictures); - - // 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; - } - unset($offer, $dbResOffers); - } - - $stringOffers = ""; - foreach ($products as $product) { - - // 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) { - $catId = $this->mainSection + $id; - $categories[$catId] = $allCategories[$catId]; - } - - - $existOffer = false; - if (!empty($iblockOffer['IBLOCK_ID'])) { - - 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"]; - - // Get properties of product - foreach ($this->propertiesSKU[$id] as $key => $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 (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] != "" || $this->propertiesProduct[$id][str_replace("_UNIT", "", $key)] != "") { - $product['_PROP_' . $key] = $propProduct; - } - } - - $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'] = $dbResProductsIds->NavPageNomer + 1; - } - while ($dbResProductsIds->NavPageNomer < $dbResProductsIds->NavPageCount); - } - } - - - 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; - } - } - - } - $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"; - } - } - } - - $offer.= "\n"; - return $offer; - } - } -} diff --git a/intaro.intarocrm/classes/general/ICrmOrderActions.php b/intaro.intarocrm/classes/general/ICrmOrderActions.php deleted file mode 100644 index a99e3ef5..00000000 --- a/intaro.intarocrm/classes/general/ICrmOrderActions.php +++ /dev/null @@ -1,1223 +0,0 @@ - 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; - } - } 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; - } - - $resOrders[$arOrder['LID']][] = $result['order']; - $resCustomers[$arOrder['LID']][] = $result['customer']; - - $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); - } - } - 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)); - } - } - - 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($_SERVER["DOCUMENT_ROOT"].'/bitrix/modules/intaro.intarocrm/classes/general/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 (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($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']]; - } - - $log = new Logger(); - $log->write($customer, 'customer'); - $log->write($order, 'order'); - - 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(); - - $log = new Logger(); - $log->write($orderHistory, 'history'); - - $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']) || $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' => 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()) { - if(!CSaleBasket::Delete($p['ID'])){ - self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error element delete'); - } - } - else{ - $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['id']))->Fetch(); - if(!CSaleBasket::Delete($prp['BASKET_ID'])){ - self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error castom element delete'); - } - } - - continue; - } - - if (isset($item['offer']) === false && isset($item['offer']['externalId']) === false) { - continue; - } - - $res = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch(); - - if($res){ - $p = CSaleBasket::GetList(array(),array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch(); - - if ($p == false) { - $p = CIBlockElement::GetByID($item['offer']['externalId'])->GetNext(); - $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()) { - unset($r['ID']); - unset($r['BASKET_ID']); - $p['PROPS'][] = $r; - } - } - - $arProduct = array(); - - if (isset($item['created']) && $item['created'] == true) { - $productPrice = GetCatalogProductPrice($item['offer']['externalId'], COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0)); - $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) { - if(!Add2BasketByProductID($item['offer']['externalId'], $item['quantity'], $arProduct, $p['PROPS'])){ - self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error element add'); - } - - 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']); - } - - if(!CSaleBasket::Update($p['ID'], $arProduct)){ - self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Update', 'Error element update'); - } - CSaleBasket::DeleteAll($userId); - } - else{ - $arProduct = array(); - - if (isset($item['created']) && $item['created'] == true) { - $arProduct = array( - 'FUSER_ID' => $userId, - 'ORDER_ID' => $order['externalId'], - 'LID' => $LID, - 'NOTES' => $item['comment'], - ); - } - - 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['quantity']) && $item['quantity']) { - $arProduct['QUANTITY'] = $item['quantity']; - } - if (isset($item['offer']['name']) && $item['offer']['name']) { - $arProduct['NAME'] = self::fromJSON($item['offer']['name']); - } - - if (isset($item['created']) && $item['created'] == true) { - $iBlocks = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_IBLOCKS, 0)); - $iBlock = array_shift($iBlocks); - - $newSection = new CIBlockSection; - $newSectionFields = Array( - "ACTIVE" => 'N', - "IBLOCK_ID" => $iBlock, - "NAME" => 'RetailCRM', - "CODE" => 'RetailCRM', - ); - $resSection = $newSection->Add($newSectionFields); - if(!$resSection){ - self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Add', 'Error castom section add'); - - continue; - } - - $arLoadProductArray = Array( - "IBLOCK_SECTION_ID" => $resSection, - "IBLOCK_ID" => $iBlock, - "NAME" => $item['offer']['name'] ? $item['offer']['name'] : 'RetailCrmElement', - "CODE" => 'RetailCrmElement', - "ACTIVE" => 'Y' - ); - $el = new CIBlockElement; - $PRODUCT_ID = $el->Add($arLoadProductArray, false, false, true); - if(!$PRODUCT_ID){ - self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockElement::Add', 'Error castom element add'); - - continue; - } - - if(!CCatalogProduct::Add(array("ID" => $PRODUCT_ID))){ - self::eventLog('ICrmOrderActions::orderHistory', 'CCatalogProduct::Add', 'Error product add'); - - continue; - } - - $arFields = Array( - "PRODUCT_ID" => $PRODUCT_ID, - "CATALOG_GROUP_ID" => COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0), - "PRICE" => $item['initialPrice'] ? $item['initialPrice'] : 1, - "CURRENCY" => CCurrency::GetBaseCurrency(), - ); - if(!CPrice::Add($arFields)){ - self::eventLog('ICrmOrderActions::orderHistory', 'CPrice::Add', 'Error price add'); - - continue; - } - - $Params = array( - array( - 'NAME' => 'id', - 'CODE' => 'ID', - 'VALUE' => $item['offer']['externalId'] - ) - ); - if(!Add2BasketByProductID($PRODUCT_ID, $item['quantity'], $arProduct, $Params)){ - self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error add to basket'); - - continue; - } - - if(!CIBlockSection::Delete($resSection)){ - self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Delete', 'Error delete section'); - - continue; - } - - continue; - } - - $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['offer']['externalId']))->Fetch(); - CSaleBasket::Update($prp['BASKET_ID'], $arProduct); - } - } - - 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']; - } - } - - // 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 (! date_create_from_format('Y-m-d H:i:s', $arFields['DATE_MARKED'])) { - unset($arFields['DATE_MARKED']); - } - - if (isset($order['discount'])) { - $arFields['DISCOUNT_VALUE'] = $order['discount']; - $arFields['PRICE'] -= $order['discount']; - } - - if(!empty($arFields)) { - try { - CSaleOrder::Update($order['externalId'], $arFields); - } catch (Exception $e) { - self::eventLog( - 'ICrmOrderActions::orderHistory', 'CSaleOrder::Update', - $e->getCode() . ': ' . $e->getMessage() . ' (order external id: '.$order['externalId'].')' - ); - continue; - } - } - - 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)); - } - } - } - - 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, - ); - } - - 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() - ); - - 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 { - $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/classes/general/RestApi.php b/intaro.intarocrm/classes/general/RestApi.php deleted file mode 100644 index 15f9434d..00000000 --- a/intaro.intarocrm/classes/general/RestApi.php +++ /dev/null @@ -1,689 +0,0 @@ -url = $url; - $this->defaultParameters = array('apiKey' => $apiKey); - $this->siteCode = $site; - } - - /* Методы для работы с заказами */ - /** - * Получение заказа по id - * - * @param string $id - идентификатор заказа - * @param string $by - поиск заказа по id или externalId - * @param string $site - символьный код сайта - * @return ApiResponse - информация о заказе - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->makeRequest("/orders/$id", self::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Создание заказа - * - * @param array $order - информация о заказе - * @param string $site - символьный код сайта - * @return ApiResponse - */ - public function ordersCreate($order, $site = null) - { - if (!sizeof($order)) { - throw new \InvalidArgumentException('Parameter `order` must contains a data'); - } - - return $this->makeRequest("/orders/create", self::METHOD_POST, $this->fillSite($site, array( - 'order' => json_encode($order) - ))); - } - - /** - * Изменение заказа - * - * @param array $order - информация о заказе - * @param string $by - изменение заказа по id или externalId - * @param string $site - символьный код сайта - * @return ApiResponse - */ - public function orderEdit($order, $by = 'externalId', $site = null) - { - if (!sizeof($order)) { - throw new \InvalidArgumentException('Parameter `order` must contains a data'); - } - - $this->checkIdParameter($by); - - if (!isset($order[$by])) { - throw new \InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by)); - } - - return $this->makeRequest( - "/orders/" . $order[$by] . "/edit", - self::METHOD_POST, - $this->fillSite($site, array( - 'order' => json_encode($order), - 'by' => $by, - )) - ); - } - - /** - * Пакетная загрузка заказов - * - * @param array $orders - массив заказов - * @param string $site - символьный код сайта - * @return ApiResponse - */ - public function orderUpload($orders, $site = null) - { - if (!sizeof($orders)) { - throw new \InvalidArgumentException('Parameter `orders` must contains array of the orders'); - } - - return $this->makeRequest("/orders/upload", self::METHOD_POST, $this->fillSite($site, array( - 'orders' => json_encode($orders), - ))); - } - - /** - * Обновление externalId у заказов с переданными id - * - * @param array $order - массив, содержащий id и externalId заказа - * @return ApiResponse - */ - public function orderFixExternalIds($order) - { - if (!sizeof($order)) { - throw new \InvalidArgumentException('Method parameter must contains at least one IDs pair'); - } - - return $this->makeRequest("/orders/fix-external-ids", self::METHOD_POST, array( - 'orders' => json_encode($order), - )); - } - - /** - * Получение последних измененных заказов - * - * @param \DateTime|string|int $startDate - начальная дата и время выборки (Y-m-d H:i:s) - * @param \DateTime|string|int $endDate - конечная дата и время выборки (Y-m-d H:i:s) - * @param int $limit - ограничение на размер выборки - * @param int $offset - сдвиг - * @param bool $skipMyChanges - * @return ApiResponse - */ - public function orderHistory( - $startDate = null, - $endDate = null, - $limit = 100, - $offset = 0, - $skipMyChanges = true - ) { - $parameters = array(); - - if ($startDate) { - $parameters['startDate'] = $this->ensureDateTime($startDate); - } - if ($endDate) { - $parameters['endDate'] = $this->ensureDateTime($endDate); - } - if ($limit) { - $parameters['limit'] = (int) $limit; - } - if ($offset) { - $parameters['offset'] = (int) $offset; - } - if ($skipMyChanges) { - $parameters['skipMyChanges'] = (bool) $skipMyChanges; - } - - return $this->makeRequest('/orders/history', self::METHOD_GET, $parameters); - } - - /* Методы для работы с клиентами */ - /** - * Получение клиента по id - * - * @param string $id - идентификатор - * @param string $by - поиск заказа по id или externalId - * @param string $site - символьный код сайта - * @return array - информация о клиенте - */ - public function customerGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->makeRequest("/customers/$id", self::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Получение списка клиентов в соответсвии с запросом - * - * @param array $filter - фильтры - * @param int $page - страница - * @param int $limit - ограничение на размер выборки - * @return ApiResponse - */ - public function customersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - - if (null !== $page) { - $parameters['page'] = (int) $page; - } - - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->makeRequest('/customers', self::METHOD_GET, $parameters); - } - - /** - * Создание клиента - * - * @param array $customer - информация о клиенте - * @param string $site - символьный код сайта - * @return ApiResponse - */ - public function customersCreate(array $customer, $site = null) - { - if (!sizeof($customer)) { - throw new \InvalidArgumentException('Parameter `customer` must contains a data'); - } - - return $this->makeRequest("/customers/create", self::METHOD_POST, $this->fillSite($site, array( - 'customer' => json_encode($customer) - ))); - } - - /** - * Редактирование клиента - * - * @param array $customer - информация о клиенте - * @param string $by - изменение клиента по id или externalId - * @param string $site - символьный код сайта - * @return ApiResponse - */ - public function customerEdit($customer, $by = 'externalId', $site = null) - { - if (!sizeof($customer)) { - throw new \InvalidArgumentException('Parameter `customer` must contains a data'); - } - - $this->checkIdParameter($by); - - if (!isset($customer[$by])) { - throw new \InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by)); - } - - return $this->makeRequest( - "/customers/" . $customer[$by] . "/edit", - self::METHOD_POST, - $this->fillSite($site, array( - 'customer' => json_encode($customer), - 'by' => $by, - ) - )); - } - - /** - * Пакетная загрузка клиентов - * - * @param array $customers - массив клиентов - * @param string $site - символьный код сайта - * @return ApiResponse - */ - public function customerUpload($customers, $site = null) - { - if (!sizeof($customers)) { - throw new \InvalidArgumentException('Parameter `customers` must contains array of the customers'); - } - - return $this->makeRequest("/customers/upload", self::METHOD_POST, $this->fillSite($site, array( - 'customers' => json_encode($customers), - ))); - } - - /** - * Обновление externalId у клиентов с переданными id - * - * @param array $customers - массив, содержащий id и externalId заказа - * @return array - */ - public function customerFixExternalIds($customers) - { - if (!sizeof($customers)) { - throw new \InvalidArgumentException('Method parameter must contains at least one IDs pair'); - } - - return $this->makeRequest("/customers/fix-external-ids", self::METHOD_POST, array( - 'customers' => json_encode($customers), - )); - } - - /* Методы для работы со справочниками */ - - /** - * Получение списка типов доставки - * - * @return ApiResponse - */ - public function deliveryTypesList() - { - return $this->makeRequest('/reference/delivery-types', self::METHOD_GET); - } - - /** - * Редактирование типа доставки - * - * @param array $delivery - информация о типе доставки - * @return ApiResponse - */ - public function deliveryTypeEdit($delivery) - { - if (!isset($delivery['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/delivery-types/' . $delivery['code'] . '/edit', - self::METHOD_POST, - array( - 'deliveryType' => json_encode($delivery) - ) - ); - } - - /** - * Получение списка служб доставки - * - * @return ApiResponse - */ - public function deliveryServicesList() - { - return $this->makeRequest('/reference/delivery-services', self::METHOD_GET); - } - - /** - * Редактирование службы доставки - * - * @param array $delivery - информация о типе доставки - * @return ApiResponse - */ - public function deliveryServiceEdit($delivery) - { - if (!isset($delivery['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/delivery-services/' . $delivery['code'] . '/edit', - self::METHOD_POST, - array( - 'deliveryService' => json_encode($delivery) - ) - ); - } - - - /** - * Получение списка типов оплаты - * - * @return ApiResponse - */ - public function paymentTypesList() - { - return $this->makeRequest('/reference/payment-types', self::METHOD_GET); - } - - /** - * Редактирование типа оплаты - * - * @param array $paymentType - информация о типе оплаты - * @return ApiResponse - */ - public function paymentTypesEdit($paymentType) - { - if (!isset($paymentType['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/payment-types/' . $paymentType['code'] . '/edit', - self::METHOD_POST, - array( - 'paymentType' => json_encode($paymentType) - ) - ); - } - - - /** - * Получение списка статусов оплаты - * - * @return ApiResponse - */ - public function paymentStatusesList() - { - return $this->makeRequest('/reference/payment-statuses', self::METHOD_GET); - } - - /** - * Редактирование статуса оплаты - * - * @param array $paymentStatus - информация о статусе оплаты - * @return ApiResponse - */ - public function paymentStatusesEdit($paymentStatus) - { - if (!isset($paymentStatus['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/payment-statuses/' . $paymentStatus['code'] . '/edit', - self::METHOD_POST, - array( - 'paymentStatus' => json_encode($paymentStatus) - ) - ); - } - - - /** - * Получение списка типов заказа - * - * @return ApiResponse - */ - public function orderTypesList() - { - return $this->makeRequest('/reference/order-types', self::METHOD_GET); - } - - /** - * Редактирование типа заказа - * - * @param array $orderType - информация о типе заказа - * @return ApiResponse - */ - public function orderTypesEdit($orderType) - { - if (!isset($orderType['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/order-types/' . $orderType['code'] . '/edit', - self::METHOD_POST, - array( - 'orderType' => json_encode($orderType) - ) - ); - } - - - /** - * Получение списка способов оформления заказа - * - * @return ApiResponse - */ - public function orderMethodsList() - { - return $this->makeRequest('/reference/order-methods', self::METHOD_GET); - } - - /** - * Редактирование способа оформления заказа - * - * @param array $orderMethod - информация о способе оформления заказа - * @return ApiResponse - */ - public function orderMethodsEdit($orderMethod) - { - if (!isset($orderMethod['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/order-methods/' . $orderMethod['code'] . '/edit', - self::METHOD_POST, - array( - 'orderMethod' => json_encode($orderMethod) - ) - ); - } - - /** - * Получение списка статусов заказа - * - * @return ApiResponse - */ - public function orderStatusesList() - { - return $this->makeRequest('/reference/statuses', self::METHOD_GET); - } - - /** - * Получение списка сайтов - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->makeRequest('/reference/sites', self::METHOD_GET); - } - - /** - * Редактирование статуса заказа - * - * @param array $status - информация о статусе заказа - * @return ApiResponse - */ - public function orderStatusEdit($status) - { - if (!isset($status['code'])) { - throw new \InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->makeRequest( - '/reference/statuses/' . $status['code'] . '/edit', - self::METHOD_POST, - array( - 'status' => json_encode($status) - ) - ); - } - - - /** - * Получение списка групп статусов заказа - * - * @return ApiResponse - */ - public function orderStatusGroupsList() - { - return $this->makeRequest('/reference/status-groups', self::METHOD_GET); - } - - /** - * Обновление статистики - * - * @return ApiResponse - */ - public function statisticUpdate() - { - return $this->makeRequest('/statistic/update', self::METHOD_GET); - } - - /** - * @return \DateTime - */ - public function getGeneratedAt() - { - return $this->generatedAt; - } - - protected function ensureDateTime($value) - { - if ($value instanceof \DateTime) { - return $value->format('Y-m-d H:i:s'); - } elseif (is_int($value)) { - return date('Y-m-d H:i:s', $value); - } - - return $value; - } - - /** - * Check ID parameter - * - * @param string $by - * @return bool - */ - protected function checkIdParameter($by) - { - $allowedForBy = array('externalId', 'id'); - if (!in_array($by, $allowedForBy)) { - throw new \InvalidArgumentException(sprintf( - 'Value "%s" for parameter "by" is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - )); - } - return true; - } - - /** - * Fill params by site value - * - * @param string $site - * @param array $params - * @return array - */ - protected function fillSite($site, array $params) - { - if ($site) { - $params['site'] = $site; - } elseif ($this->siteCode) { - $params['site'] = $this->siteCode; - } - - return $params; - } - - /** - * Make HTTP request - * - * @param string $path - * @param string $method (default: 'GET') - * @param array $parameters (default: array()) - * @param int $timeout - * @return ApiResponse - */ - public function makeRequest($path, $method, $parameters = array(), $timeout = 30) - { - $allowedMethods = array(self::METHOD_GET, self::METHOD_POST); - if (!in_array($method, $allowedMethods)) { - throw new \InvalidArgumentException(sprintf( - 'Method "%s" is not valid. Allowed methods are %s', - $method, - implode(', ', $allowedMethods) - )); - } - - $parameters = array_merge($this->defaultParameters, $parameters); - - $path = $this->url . $path; - if (self::METHOD_GET === $method && sizeof($parameters)) { - $path .= '?' . http_build_query($parameters); - } - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $path); - curl_setopt($ch, CURLOPT_FAILONERROR, false); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable - curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout); // times out after 30s - // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects - - if (self::METHOD_POST === $method) { - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); - } - - $responseBody = curl_exec($ch); - $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - $errno = curl_errno($ch); - $error = curl_error($ch); - curl_close($ch); - - if ($errno) { - throw new CurlException($error, $errno); - } - - $result = json_decode($responseBody, true); - - if (isset($result['generatedAt'])) { - $this->generatedAt = new \DateTime($result['generatedAt']); - unset($result['generatedAt']); - } - - return new ApiResponse($statusCode, $responseBody); - } -} diff --git a/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php b/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php deleted file mode 100644 index fde12b02..00000000 --- a/intaro.intarocrm/classes/general/events/ICrmOrderEvent.php +++ /dev/null @@ -1,340 +0,0 @@ - $optionsOrderTypes, - 'optionsDelivTypes' => $optionsDelivTypes, - 'optionsPayTypes' => $optionsPayTypes, - 'optionsPayStatuses' => $optionsPayStatuses, - 'optionsPayment' => $optionsPayment, - 'optionsOrderProps' => $optionsOrderProps, - 'optionsLegalDetails' => $optionsLegalDetails, - 'optionsContragentType' => $optionsContragentType, - 'optionsSitesList' => $optionsSitesList, - 'optionsCustomFields' => $optionsCustomFields - )); - - $arOrder = CSaleOrder::GetById($ID); - - if (is_array($arFields) && !empty($arFields)) { - - $arFieldsNew = array( - 'USER_ID' => $arOrder['USER_ID'], - 'ID' => $ID, - 'PERSON_TYPE_ID' => $arOrder['PERSON_TYPE_ID'], - 'CANCELED' => $arOrder['CANCELED'], - 'STATUS_ID' => $arOrder['STATUS_ID'], - 'DATE_INSERT' => $arOrder['DATE_INSERT'], - 'LID' => $arOrder['LID'] - ); - - $arFieldsNew = array_merge($arFieldsNew, $arFields); - $arOrder = $arFieldsNew; - } - if(count($optionsSitesList)>1){ - $result = ICrmOrderActions::orderCreate($arOrder, $api, $arParams, true, $optionsSitesList[$arOrder['LID']]); - } - else{ - $result = ICrmOrderActions::orderCreate($arOrder, $api, $arParams, true); - } - - if(!$result) { - ICrmOrderActions::eventLog('ICrmOrderEvent::writeDataOnOrderCreate', 'ICrmOrderActions::orderCreate', 'error during creating order'); - return false; - } - - return true; - } - - /** - * - * @param type $ID -- orderId - * @param type $cancel -- Y / N - cancel order status - * @param type $reason -- cancel reason - * @return boolean - */ - function onSaleCancelOrder($ID, $cancel, $reason) { - if(isset($GLOBALS['INTARO_CRM_FROM_HISTORY']) && $GLOBALS['INTARO_CRM_FROM_HISTORY']) - return; - - if(!$ID || !$cancel) - return true; - - if (!CModule::IncludeModule('iblock')) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'iblock', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("sale")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'sale', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("catalog")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSaleCancelOrder', 'catalog', 'module not found'); - return true; - } - - $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); - - //saved cat params - $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses - - $api = new RetailCrm\RestApi($api_host, $api_key); - - $order = array(); - - if($cancel == 'Y') { - $order = array( - 'externalId' => (int) $ID, - 'status' => $optionsPayStatuses[$cancel.$cancel], - 'statusComment' => ICrmOrderActions::toJSON($reason) - ); - } else if($cancel == 'N') { - $arOrder = CSaleOrder::GetById((int) $ID); - - $order = array( - 'externalId' => (int) $ID, - 'status' => $optionsPayStatuses[$arOrder['STATUS_ID']], - 'managerComment' => $arOrder['COMMENTS'] - ); - } - - $log = new Logger(); - $log->write($order, 'order'); - - try { - $api->orderEdit($order); - } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'ICrmOrderEvent::onSaleCancelOrder', 'RetailCrm\RestApi::orderEdit::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - } - - return true; - } - - /** - * - * @param type $ID -- orderId - * @param type $payed -- Y / N - pay order status - * @return boolean - */ - function onSalePayOrder($ID, $payed) { - if(isset($GLOBALS['INTARO_CRM_FROM_HISTORY']) && $GLOBALS['INTARO_CRM_FROM_HISTORY']) - return; - - if(!$ID || !$payed || ($payed != 'Y')) - return true; - - if (!CModule::IncludeModule('iblock')) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'iblock', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("sale")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'sale', 'module not found'); - return true; - } - - if (!CModule::IncludeModule("catalog")) { - //handle err - ICrmOrderActions::eventLog('ICrmOrderEvent::onSalePayOrder', 'catalog', 'module not found'); - return true; - } - - $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); - - //saved cat params - $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); - - $api = new RetailCrm\RestApi($api_host, $api_key); - - $order = array( - 'externalId' => (int) $ID, - 'paymentStatus' => $optionsPayment[$payed] - ); - - $log = new Logger(); - $log->write($order, 'order'); - - try { - $api->orderEdit($order); - } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'ICrmOrderEvent::onSalePayOrder', 'RetailCrm\RestApi::orderEdit::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - } - - return true; - } - - /** - * - * @param type $ID -- orderId - * @param type $value -- ACCOUNT_NUMBER - * @return boolean - */ - function onBeforeOrderAccountNumberSet($ID, $value) { - if(isset($GLOBALS['ICRM_ACCOUNT_NUMBER']) && $GLOBALS['ICRM_ACCOUNT_NUMBER']) - return $GLOBALS['ICRM_ACCOUNT_NUMBER']; - - return false; - } -} \ No newline at end of file diff --git a/intaro.intarocrm/classes/general/history/.htaccess b/intaro.intarocrm/classes/general/history/.htaccess deleted file mode 100644 index 945908c9..00000000 --- a/intaro.intarocrm/classes/general/history/.htaccess +++ /dev/null @@ -1,2 +0,0 @@ -Satisfy Any -Allow from all \ No newline at end of file diff --git a/intaro.intarocrm/classes/general/history/history.php b/intaro.intarocrm/classes/general/history/history.php deleted file mode 100644 index 978e60ef..00000000 --- a/intaro.intarocrm/classes/general/history/history.php +++ /dev/null @@ -1,435 +0,0 @@ - 0){ - require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php'); - - if (!CModule::IncludeModule("iblock")) { - ICrmOrderActions::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found'); - return false; - } - if (!CModule::IncludeModule("sale")) { - ICrmOrderActions::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found'); - return false; - } - if (!CModule::IncludeModule("catalog")) { - ICrmOrderActions::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found'); - return false; - } - if (!CModule::IncludeModule("intaro.intarocrm")) { - ICrmOrderActions::eventLog('ICrmOrderActions::orderHistory', 'intaro.intarocrm', 'module not found'); - return false; - } - - global $USER; - if (is_object($USER) == false) { - $USER = new RetailUser; - } - - $api_host = COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_API_HOST_OPTION, 0); - $api_key = COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_API_KEY_OPTION, 0); - - $optionsOrderTypes = array_flip(unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_ORDER_TYPES_ARR, 0))); - $optionsDelivTypes = array_flip(unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_DELIVERY_TYPES_ARR, 0))); - $optionsPayTypes = array_flip(unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_PAYMENT_TYPES, 0))); - $optionsPayStatuses = array_flip(unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_PAYMENT_STATUSES, 0))); // --statuses - $optionsPayment = array_flip(unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_PAYMENT, 0))); - $optionsOrderProps = unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_ORDER_PROPS, 0)); - $optionsLegalDetails = unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_LEGAL_DETAILS, 0)); - $optionsContragentType = unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_CONTRAGENT_TYPE, 0)); - $optionsSitesList = unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$CRM_SITES_LIST, 0)); - $optionsCustomFields = unserialize(COption::GetOptionString(ICrmOrderActions::$MODULE_ID, ICrmOrderActions::$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); - - $order = $api->orderGet($idOrderCRM, $by = 'id'); - - $log = new Logger(); - $log->write($order, 'order'); - - $defaultOrderType = 1; - $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y")); - if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { - $defaultOrderType = $arOrderTypesList['ID']; - } - - $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true; - - 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'])) { - die(); - } - - $registerNewUser = true; - - if (!isset($order['customer']['email']) && $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" => ICrmOrderActions::fromJSON($order['customer']['firstName']), - "LAST_NAME" => ICrmOrderActions::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) { - ICrmOrderActions::eventLog('ICrmOrderActions::orderHistory', 'CUser::Register', 'Error register user'); - die(); - } - - try { - $api->customerFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))); - } catch (\IntaroCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - - die(); - } - } - - $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 (\IntaroCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'ICrmOrderActions::orderHistory', 'RetailCrm\RestApi::orderFixExternalIds::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - - die(); - } - } - $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)) { - die(); - } - - $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( - ICrmOrderActions::clearArr($order), - 'ICrmOrderActions::recursiveUpdate', - array( - 'update' => $arUpdateProps, - 'type' => $arFields['PERSON_TYPE_ID'], - 'options' => $optionsOrderProps, - 'orderId' => $order['externalId'] - ) - ); - - //выбираем товары по текущему заказу с сайта - $bItms = array(); - $p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'])); - while($bItm = $p->Fetch()){ - $bItms[$bItm['PRODUCT_ID']] = $bItm; - } - - //перебираем хистори - $CrmItms = array(); - foreach($order['items'] as $item) { - $CrmItms[] = $item['id']; - //если такой товар есть - if(in_array($item['offer']['externalId'], $bItms)){ - if ((int) $item['quantity'] != (int) $bItms[$item['offer']['externalId']]['QUANTITY']) { - $arProduct['QUANTITY'] = $item['quantity']; - $g = CSaleBasket::Update($bItms[$item['offer']['externalId']]['ID'], $arProduct); - //резерв - $ar_res = CCatalogProduct::GetByID($item['offer']['externalId']); - $arFields = array( - 'QUANTITY' => (int)$ar_res['QUANTITY'] + (int)$bItms[$item['offer']['externalId']]['QUANTITY'] - (int) $item['quantity'], - 'QUANTITY_RESERVED' => (int)$ar_res['QUANTITY_RESERVED'] - (int)$bItms[$item['offer']['externalId']]['QUANTITY'] + (int) $item['quantity'], - ); - $d = CCatalogProduct::Update($item['offer']['externalId'], $arFields); - } - }//если нет, добавляем - else{ - $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']; - $arProduct = array( - 'FUSER_ID' => $userId, - 'ORDER_ID' => $order['externalId'], - 'QUANTITY' => $item['quantity'], - 'CURRENCY' => CCurrency::GetBaseCurrency(), - '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['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'] = ICrmOrderActions::fromJSON($item['offer']['name']); - } - - $op = CSaleBasket::Add($arProduct); - //резерв - $ar_res = CCatalogProduct::GetByID($item['offer']['externalId']); - $arFields = array( - 'QUANTITY' => (int)$ar_res['QUANTITY'] - (int)$item['quantity'], - 'QUANTITY_RESERVED' => (int)$ar_res['QUANTITY_RESERVED'] + (int)$item['quantity'], - ); - $d = CCatalogProduct::Update($item['offer']['externalId'], $arFields); - } - } - //удаляем лишние товары - foreach($bItms as $bItm){ - if(!in_array($bItm['PRODUCT_ID'], $CrmItms)){ - CSaleBasket::Delete($bItm['ID']); - //удаляем товары из резерва - $ar_res = CCatalogProduct::GetByID($bItm['PRODUCT_ID']); - $arFields = array( - 'QUANTITY' => (int)$ar_res['QUANTITY'] + (int)$bItm['QUANTITY'], - 'QUANTITY_RESERVED' => (int)$ar_res['QUANTITY_RESERVED'] - (int)$bItm['QUANTITY'], - ); - $d = CCatalogProduct::Update($bItm['PRODUCT_ID'], $arFields); - } - } - - 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']; - } - } - - // orderUpdate - $arFields = ICrmOrderActions::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' => ICrmOrderActions::fromJSON($order['statusComment']), - 'USER_DESCRIPTION' => ICrmOrderActions::fromJSON($order['customerComment']), - 'COMMENTS' => ICrmOrderActions::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']); - } - } - } - - // 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); - } - } - $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false; -} -?> \ No newline at end of file diff --git a/intaro.intarocrm/description.ru b/intaro.intarocrm/description.ru deleted file mode 100644 index 3ba43226..00000000 --- a/intaro.intarocrm/description.ru +++ /dev/null @@ -1,4 +0,0 @@ -- Исправлена ошибка, связанная с версионностью PHP в History. -- Добавлена выгрузка закупочной цены вместе с заказом -- Добавлены индивидуальные настройки для профилей выгрузки -- Исправлены мелкие ошибки \ No newline at end of file diff --git a/intaro.intarocrm/include.php b/intaro.intarocrm/include.php deleted file mode 100644 index e1352414..00000000 --- a/intaro.intarocrm/include.php +++ /dev/null @@ -1,15 +0,0 @@ - 'classes/general/RestNormalizer.php', - 'Logger' => 'classes/general/Logger.php', - 'RetailCrm\RestApi' => 'classes/general/RestApi.php', - 'RetailCrm\Response\ApiResponse' => 'classes/general/Response/ApiResponse.php', - 'ICrmOrderActions' => 'classes/general/ICrmOrderActions.php', - 'ICMLLoader' => 'classes/general/ICMLLoader.php', - 'ICrmOrderEvent' => 'classes/general/events/ICrmOrderEvent.php', - 'RetailCrm\Exception\InvalidJsonException' => 'classes/general/Exception/InvalidJsonException.php', - 'RetailCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php', - ) -); \ No newline at end of file diff --git a/intaro.intarocrm/install/export/intarocrm_run.php b/intaro.intarocrm/install/export/intarocrm_run.php deleted file mode 100644 index 26b789f8..00000000 --- a/intaro.intarocrm/install/export/intarocrm_run.php +++ /dev/null @@ -1,3 +0,0 @@ -retailCRM -require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/export/export_run.php"); \ No newline at end of file diff --git a/intaro.intarocrm/install/export/intarocrm_setup.php b/intaro.intarocrm/install/export/intarocrm_setup.php deleted file mode 100644 index da2957c8..00000000 --- a/intaro.intarocrm/install/export/intarocrm_setup.php +++ /dev/null @@ -1,3 +0,0 @@ -retailCRM -require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/export/export_setup.php"); \ No newline at end of file diff --git a/intaro.intarocrm/install/version.php b/intaro.intarocrm/install/version.php deleted file mode 100644 index 3913b629..00000000 --- a/intaro.intarocrm/install/version.php +++ /dev/null @@ -1,6 +0,0 @@ - "1.1.1", - "VERSION_DATE" => "2015-03-19 14:56:00" -); - diff --git a/intaro.intarocrm/lang/ru/classes/general/ICrmOrderActions.php b/intaro.intarocrm/lang/ru/classes/general/ICrmOrderActions.php deleted file mode 100644 index 493ac10f..00000000 --- a/intaro.intarocrm/lang/ru/classes/general/ICrmOrderActions.php +++ /dev/null @@ -1,2 +0,0 @@ - + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ + +namespace RetailCrm; + +use RetailCrm\Http\Client; +use RetailCrm\Response\ApiResponse; + +/** + * PHP version 5.3 + * + * API client class + * + * @category RetailCrm + * @package RetailCrm + * @author RetailCrm + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ +class ApiClient +{ + + const VERSION = 'v4'; + + protected $client; + + /** + * Site code + */ + protected $siteCode; + + /** + * Client creating + * + * @param string $url api url + * @param string $apiKey api key + * @param string $site site code + * + * @throws \InvalidArgumentException + * + * @return mixed + */ + public function __construct($url, $apiKey, $site = null) + { + if ('/' !== $url[strlen($url) - 1]) { + $url .= '/'; + } + + $url = $url . 'api/' . self::VERSION; + + $this->client = new Client($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * Returns users list + * + * @param array $filter + * @param null $page + * @param null $limit + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/users', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Returns user data + * + * @param integer $id user ID + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersGet($id) + { + return $this->client->makeRequest("/users/$id", Client::METHOD_GET); + } + + /** + * Returns filtered orders list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Create a order + * + * @param array $order order data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersCreate(array $order, $site = null) + { + if (!count($order)) { + throw new \InvalidArgumentException( + 'Parameter `order` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/create', + Client::METHOD_POST, + $this->fillSite($site, array('order' => json_encode($order))) + ); + } + + /** + * Save order IDs' (id and externalId) association in the CRM + * + * @param array $ids order identificators + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/orders/fix-external-ids', + Client::METHOD_POST, + array('orders' => json_encode($ids) + ) + ); + } + + /** + * Returns statuses of the orders + * + * @param array $ids (default: array()) + * @param array $externalIds (default: array()) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersStatuses(array $ids = array(), array $externalIds = array()) + { + $parameters = array(); + + if (count($ids)) { + $parameters['ids'] = $ids; + } + if (count($externalIds)) { + $parameters['externalIds'] = $externalIds; + } + + return $this->client->makeRequest( + '/orders/statuses', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Upload array of the orders + * + * @param array $orders array of orders + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersUpload(array $orders, $site = null) + { + if (!count($orders)) { + throw new \InvalidArgumentException( + 'Parameter `orders` must contains array of the orders' + ); + } + + return $this->client->makeRequest( + '/orders/upload', + Client::METHOD_POST, + $this->fillSite($site, array('orders' => json_encode($orders))) + ); + } + + /** + * Get order by id or externalId + * + * @param string $id order identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/orders/$id", + Client::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a order + * + * @param array $order order data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersEdit(array $order, $by = 'externalId', $site = null) + { + if (!count($order)) { + throw new \InvalidArgumentException( + 'Parameter `order` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $order)) { + throw new \InvalidArgumentException( + sprintf('Order array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/orders/%s/edit', $order[$by]), + Client::METHOD_POST, + $this->fillSite( + $site, + array('order' => json_encode($order), 'by' => $by) + ) + ); + } + + /** + * Get orders history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function ordersHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/history', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Returns filtered customers list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/customers', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Create a customer + * + * @param array $customer customer data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersCreate(array $customer, $site = null) + { + if (! count($customer)) { + throw new \InvalidArgumentException( + 'Parameter `customer` must contains a data' + ); + } + + return $this->client->makeRequest( + '/customers/create', + Client::METHOD_POST, + $this->fillSite($site, array('customer' => json_encode($customer))) + ); + } + + /** + * Save customer IDs' (id and externalId) association in the CRM + * + * @param array $ids ids mapping + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/customers/fix-external-ids', + Client::METHOD_POST, + array('customers' => json_encode($ids)) + ); + } + + /** + * Upload array of the customers + * + * @param array $customers array of customers + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersUpload(array $customers, $site = null) + { + if (! count($customers)) { + throw new \InvalidArgumentException( + 'Parameter `customers` must contains array of the customers' + ); + } + + return $this->client->makeRequest( + '/customers/upload', + Client::METHOD_POST, + $this->fillSite($site, array('customers' => json_encode($customers))) + ); + } + + /** + * Get customer by id or externalId + * + * @param string $id customer identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/customers/$id", + Client::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a customer + * + * @param array $customer customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersEdit(array $customer, $by = 'externalId', $site = null) + { + if (!count($customer)) { + throw new \InvalidArgumentException( + 'Parameter `customer` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $customer)) { + throw new \InvalidArgumentException( + sprintf('Customer array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/customers/%s/edit', $customer[$by]), + Client::METHOD_POST, + $this->fillSite( + $site, + array('customer' => json_encode($customer), 'by' => $by) + ) + ); + } + + /** + * Get customers history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function customersHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/customers/history', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/packs', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Create orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksCreate(array $pack, $site = null) + { + if (!count($pack)) { + throw new \InvalidArgumentException( + 'Parameter `pack` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/packs/create', + Client::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + /** + * Get orders assembly history + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/packs/history', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksGet($id) + { + if (empty($id)) { + throw new \InvalidArgumentException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + "/orders/packs/$id", + Client::METHOD_GET + ); + } + + /** + * Delete orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksDelete($id) + { + if (empty($id)) { + throw new \InvalidArgumentException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/delete', $id), + Client::METHOD_POST + ); + } + + /** + * Edit orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksEdit(array $pack, $site = null) + { + if (!count($pack) || empty($pack['id'])) { + throw new \InvalidArgumentException( + 'Parameter `pack` must contains a data & pack `id` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/edit', $pack['id']), + Client::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + /** + * Get purchace prices & stock balance + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeInventories(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/inventories', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Get store settings + * + * @param string $code get settings code + * + * @return ApiResponse + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/store/setting/$code", + Client::METHOD_GET + ); + } + + /** + * Edit store configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new \InvalidArgumentException( + 'Parameter `configuration` must contains a data & configuration `code` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/store/setting/%s/edit', $configuration['code']), + Client::METHOD_POST, + $configuration + ); + } + + /** + * Upload store inventories + * + * @param array $offers offers data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeInventoriesUpload(array $offers, $site = null) + { + if (!count($offers)) { + throw new \InvalidArgumentException( + 'Parameter `offers` must contains array of the offers' + ); + } + + return $this->client->makeRequest( + '/store/inventories/upload', + Client::METHOD_POST, + $this->fillSite($site, array('offers' => json_encode($offers))) + ); + } + + /** + * Get products + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeProducts(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/products', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Get delivery settings + * + * @param string $code + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliverySettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/delivery/generic/setting/$code", + Client::METHOD_GET + ); + } + + /** + * Edit delivery configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliverySettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new \InvalidArgumentException( + 'Parameter `configuration` must contains a data & configuration `code` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), + Client::METHOD_POST, + array('configuration' => json_encode($configuration)) + ); + } + + /** + * Delivery tracking update + * + * @param string $code + * @param array $statusUpdate + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliveryTracking($code, array $statusUpdate) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + if (!count($statusUpdate)) { + throw new \InvalidArgumentException( + 'Parameter `statusUpdate` must contains a data' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/%s/tracking', $code), + Client::METHOD_POST, + $statusUpdate + ); + } + + /** + * Returns available county list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function countriesList() + { + return $this->client->makeRequest( + '/reference/countries', + Client::METHOD_GET + ); + } + + /** + * Returns deliveryServices list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryServicesList() + { + return $this->client->makeRequest( + '/reference/delivery-services', + Client::METHOD_GET + ); + } + + /** + * Edit deliveryService + * + * @param array $data delivery service data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryServicesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/delivery-services/%s/edit', $data['code']), + Client::METHOD_POST, + array('deliveryService' => json_encode($data)) + ); + } + + /** + * Returns deliveryTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesList() + { + return $this->client->makeRequest( + '/reference/delivery-types', + Client::METHOD_GET + ); + } + + /** + * Edit deliveryType + * + * @param array $data delivery type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/delivery-types/%s/edit', $data['code']), + Client::METHOD_POST, + array('deliveryType' => json_encode($data)) + ); + } + + /** + * Returns orderMethods list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsList() + { + return $this->client->makeRequest( + '/reference/order-methods', + Client::METHOD_GET + ); + } + + /** + * Edit orderMethod + * + * @param array $data order method data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/order-methods/%s/edit', $data['code']), + Client::METHOD_POST, + array('orderMethod' => json_encode($data)) + ); + } + + /** + * Returns orderTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesList() + { + return $this->client->makeRequest( + '/reference/order-types', + Client::METHOD_GET + ); + } + + /** + * Edit orderType + * + * @param array $data order type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/order-types/%s/edit', $data['code']), + Client::METHOD_POST, + array('orderType' => json_encode($data)) + ); + } + + /** + * Returns paymentStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesList() + { + return $this->client->makeRequest( + '/reference/payment-statuses', + Client::METHOD_GET + ); + } + + /** + * Edit paymentStatus + * + * @param array $data payment status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/payment-statuses/%s/edit', $data['code']), + Client::METHOD_POST, + array('paymentStatus' => json_encode($data)) + ); + } + + /** + * Returns paymentTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesList() + { + return $this->client->makeRequest( + '/reference/payment-types', + Client::METHOD_GET + ); + } + + /** + * Edit paymentType + * + * @param array $data payment type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/payment-types/%s/edit', $data['code']), + Client::METHOD_POST, + array('paymentType' => json_encode($data)) + ); + } + + /** + * Returns productStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesList() + { + return $this->client->makeRequest( + '/reference/product-statuses', + Client::METHOD_GET + ); + } + + /** + * Edit productStatus + * + * @param array $data product status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/product-statuses/%s/edit', $data['code']), + Client::METHOD_POST, + array('productStatus' => json_encode($data)) + ); + } + + /** + * Returns sites list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function sitesList() + { + return $this->client->makeRequest( + '/reference/sites', + Client::METHOD_GET + ); + } + + /** + * Edit site + * + * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function sitesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/sites/%s/edit', $data['code']), + Client::METHOD_POST, + array('site' => json_encode($data)) + ); + } + + /** + * Returns statusGroups list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusGroupsList() + { + return $this->client->makeRequest( + '/reference/status-groups', + Client::METHOD_GET + ); + } + + /** + * Returns statuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesList() + { + return $this->client->makeRequest( + '/reference/statuses', + Client::METHOD_GET + ); + } + + /** + * Edit order status + * + * @param array $data status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/statuses/%s/edit', $data['code']), + Client::METHOD_POST, + array('status' => json_encode($data)) + ); + } + + /** + * Returns stores list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesList() + { + return $this->client->makeRequest( + '/reference/stores', + Client::METHOD_GET + ); + } + + /** + * Edit store + * + * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + if (!array_key_exists('name', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "name" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/stores/%s/edit', $data['code']), + Client::METHOD_POST, + array('store' => json_encode($data)) + ); + } + + /** + * Get telephony settings + * + * @param string $code + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function telephonySettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/telephony/setting/$code", + Client::METHOD_GET + ); + } + + /** + * Edit telephony settings + * + * @param string $code symbolic code + * @param string $clientId client id + * @param boolean $active telephony activity + * @param mixed $name service name + * @param mixed $makeCallUrl service init url + * @param mixed $image service logo url(svg file) + * + * @param array $additionalCodes + * @param array $externalPhones + * @param bool $allowEdit + * @param bool $inputEventSupported + * @param bool $outputEventSupported + * @param bool $hangupEventSupported + * @param bool $changeUserStatusUrl + * + * @return ApiResponse + */ + public function telephonySettingsEdit( + $code, + $clientId, + $active = false, + $name = false, + $makeCallUrl = false, + $image = false, + $additionalCodes = array(), + $externalPhones = array(), + $allowEdit = false, + $inputEventSupported = false, + $outputEventSupported = false, + $hangupEventSupported = false, + $changeUserStatusUrl = false + ) + { + if (!isset($code)) { + throw new \InvalidArgumentException('Code must be set'); + } + + $parameters['code'] = $code; + + if (!isset($clientId)) { + throw new \InvalidArgumentException('client id must be set'); + } + + $parameters['clientId'] = $clientId; + + if (!isset($active)) { + $parameters['active'] = false; + } else { + $parameters['active'] = $active; + } + + if (!isset($name)) { + throw new \InvalidArgumentException('name must be set'); + } + + if (isset($name)) { + $parameters['name'] = $name; + } + + if (isset($makeCallUrl)) { + $parameters['makeCallUrl'] = $makeCallUrl; + } + + if (isset($image)) { + $parameters['image'] = $image; + } + + if (isset($additionalCodes)) { + $parameters['additionalCodes'] = $additionalCodes; + } + + if (isset($externalPhones)) { + $parameters['externalPhones'] = $externalPhones; + } + + if (isset($allowEdit)) { + $parameters['allowEdit'] = $allowEdit; + } + + if (isset($inputEventSupported)) { + $parameters['inputEventSupported'] = $inputEventSupported; + } + + if (isset($outputEventSupported)) { + $parameters['outputEventSupported'] = $outputEventSupported; + } + + if (isset($hangupEventSupported)) { + $parameters['hangupEventSupported'] = $hangupEventSupported; + } + + if (isset($changeUserStatusUrl)) { + $parameters['changeUserStatusUrl'] = $changeUserStatusUrl; + } + + return $this->client->makeRequest( + "/telephony/setting/$code/edit", + Client::METHOD_POST, + array('configuration' => json_encode($parameters)) + ); + } + + /** + * Call event + * + * @param string $phone phone number + * @param string $type call type + * @param array $codes + * @param string $hangupStatus + * @param string $externalPhone + * @param array $webAnalyticsData + * + * @return ApiResponse + * @internal param string $code additional phone code + * @internal param string $status call status + * + */ + public function telephonyCallEvent( + $phone, + $type, + $codes, + $hangupStatus, + $externalPhone = null, + $webAnalyticsData = array() + ) + { + if (!isset($phone)) { + throw new \InvalidArgumentException('Phone number must be set'); + } + + if (!isset($type)) { + throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); + } + + if (empty($codes)) { + throw new \InvalidArgumentException('Codes array must be set'); + } + + $parameters['phone'] = $phone; + $parameters['type'] = $type; + $parameters['codes'] = $codes; + $parameters['hangupStatus'] = $hangupStatus; + $parameters['callExternalId'] = $externalPhone; + $parameters['webAnalyticsData'] = $webAnalyticsData; + + + return $this->client->makeRequest( + '/telephony/call/event', + Client::METHOD_POST, + array('event' => json_encode($parameters)) + ); + } + + /** + * Upload calls + * + * @param array $calls calls data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallsUpload(array $calls) + { + if (!count($calls)) { + throw new \InvalidArgumentException( + 'Parameter `calls` must contains array of the calls' + ); + } + + return $this->client->makeRequest( + '/telephony/calls/upload', + Client::METHOD_POST, + array('calls' => json_encode($calls)) + ); + } + + /** + * Get call manager + * + * @param string $phone phone number + * @param bool $details detailed information + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallManager($phone, $details) + { + if (!isset($phone)) { + throw new \InvalidArgumentException('Phone number must be set'); + } + + $parameters['phone'] = $phone; + $parameters['details'] = isset($details) ? $details : 0; + + return $this->client->makeRequest( + '/telephony/manager', + Client::METHOD_GET, + $parameters + ); + } + + /** + * Update CRM basic statistic + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statisticUpdate() + { + return $this->client->makeRequest( + '/statistic/update', + Client::METHOD_GET + ); + } + + /** + * Return current site + * + * @return string + */ + public function getSite() + { + return $this->siteCode; + } + + /** + * Set site + * + * @param string $site site code + * + * @return void + */ + public function setSite($site) + { + $this->siteCode = $site; + } + + /** + * Check ID parameter + * + * @param string $by identify by + * + * @throws \InvalidArgumentException + * + * @return bool + */ + protected function checkIdParameter($by) + { + $allowedForBy = array( + 'externalId', + 'id' + ); + + if (!in_array($by, $allowedForBy, false)) { + throw new \InvalidArgumentException( + sprintf( + 'Value "%s" for "by" param is not valid. Allowed values are %s.', + $by, + implode(', ', $allowedForBy) + ) + ); + } + + return true; + } + + /** + * Fill params by site value + * + * @param string $site site code + * @param array $params input parameters + * + * @return array + */ + protected function fillSite($site, array $params) + { + if ($site) { + $params['site'] = $site; + } elseif ($this->siteCode) { + $params['site'] = $this->siteCode; + } + + return $params; + } +} diff --git a/intaro.intarocrm/classes/general/Exception/CurlException.php b/intaro.retailcrm/classes/general/Exception/CurlException.php similarity index 100% rename from intaro.intarocrm/classes/general/Exception/CurlException.php rename to intaro.retailcrm/classes/general/Exception/CurlException.php diff --git a/intaro.intarocrm/classes/general/Exception/InvalidJsonException.php b/intaro.retailcrm/classes/general/Exception/InvalidJsonException.php similarity index 100% rename from intaro.intarocrm/classes/general/Exception/InvalidJsonException.php rename to intaro.retailcrm/classes/general/Exception/InvalidJsonException.php diff --git a/intaro.retailcrm/classes/general/Http/Client.php b/intaro.retailcrm/classes/general/Http/Client.php new file mode 100644 index 00000000..4e16190f --- /dev/null +++ b/intaro.retailcrm/classes/general/Http/Client.php @@ -0,0 +1,160 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + */ + +namespace RetailCrm\Http; + +use RetailCrm\Exception\CurlException; +use RetailCrm\Exception\InvalidJsonException; +use RetailCrm\Response\ApiResponse; + +/** + * PHP version 5.3 + * + * HTTP client + * + * @category RetailCrm + * @package RetailCrm + * @author RetailCrm + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + */ +class Client +{ + const METHOD_GET = 'GET'; + const METHOD_POST = 'POST'; + + protected $url; + protected $defaultParameters; + protected $retry; + + /** + * Client constructor. + * + * @param string $url api url + * @param array $defaultParameters array of parameters + * + * @throws \InvalidArgumentException + */ + public function __construct($url, array $defaultParameters = array()) + { + if (false === stripos($url, 'https://')) { + throw new \InvalidArgumentException( + 'API schema requires HTTPS protocol' + ); + } + + $this->url = $url; + $this->defaultParameters = $defaultParameters; + $this->retry = 0; + $this->curlErrors = array( + CURLE_COULDNT_RESOLVE_PROXY, + CURLE_COULDNT_RESOLVE_HOST, + CURLE_COULDNT_CONNECT, + CURLE_OPERATION_TIMEOUTED, + CURLE_HTTP_POST_ERROR, + CURLE_SSL_CONNECT_ERROR, + CURLE_SEND_ERROR, + CURLE_RECV_ERROR + ); + } + + /** + * Make HTTP request + * + * @param string $path request url + * @param string $method (default: 'GET') + * @param array $parameters (default: array()) + * + * @SuppressWarnings(PHPMD.ExcessiveParameterList) + * + * @throws \InvalidArgumentException + * @throws CurlException + * @throws InvalidJsonException + * + * @return ApiResponse + */ + public function makeRequest( + $path, + $method, + array $parameters = array() + ) { + $allowedMethods = array(self::METHOD_GET, self::METHOD_POST); + + if (!in_array($method, $allowedMethods, false)) { + throw new \InvalidArgumentException( + sprintf( + 'Method "%s" is not valid. Allowed methods are %s', + $method, + implode(', ', $allowedMethods) + ) + ); + } + + $parameters = array_merge($this->defaultParameters, $parameters); + + $url = $this->url . $path; + + if (self::METHOD_GET === $method && count($parameters)) { + $url .= '?' . http_build_query($parameters, '', '&'); + } + + $curlHandler = curl_init(); + curl_setopt($curlHandler, CURLOPT_URL, $url); + curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($curlHandler, CURLOPT_FAILONERROR, false); + curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30); + curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30); + + if (self::METHOD_POST === $method) { + curl_setopt($curlHandler, CURLOPT_POST, true); + curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters); + } + + $responseBody = curl_exec($curlHandler); + $statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); + $errno = curl_errno($curlHandler); + $error = curl_error($curlHandler); + + curl_close($curlHandler); + + if ($errno + && in_array($errno, $this->curlErrors, false) + && $this->retry < 3 + ) { + $errno = null; + $error = null; + ++$this->retry; + $this->makeRequest($path, $method, $parameters); + } + + if ($errno) { + throw new CurlException($error, $errno); + } + + return new ApiResponse($statusCode, $responseBody); + } + + /** + * Retry connect + * + * @return int + */ + public function getRetry() + { + return $this->retry; + } +} diff --git a/intaro.intarocrm/classes/general/Logger.php b/intaro.retailcrm/classes/general/Logger.php similarity index 70% rename from intaro.intarocrm/classes/general/Logger.php rename to intaro.retailcrm/classes/general/Logger.php index 422d3d35..e49cce6f 100644 --- a/intaro.intarocrm/classes/general/Logger.php +++ b/intaro.retailcrm/classes/general/Logger.php @@ -4,7 +4,7 @@ class Logger private $logPath; private $files; - public function __construct($logPath = '/bitrix/modules/intaro.intarocrm/classes/general/log', $files = 3) + public function __construct($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3) { $this->logPath = $logPath; $this->files = $files; @@ -12,13 +12,17 @@ class Logger public function write($dump, $file = 'info') { - $file = $_SERVER["DOCUMENT_ROOT"] . $this->logPath . '/' . $file . '.log'; - - // message prefix with current time + $rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y')); + $ar = $rsSites->Fetch(); + if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')) + { + mkdir($ar['ABS_DOC_ROOT'] . $this->logPath . '/'); + } + $file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log'; + $data['TIME'] = date('Y-m-d H:i:s'); $data['DATA'] = $dump; - //write log $f = fopen($file, "a+"); fwrite($f, print_r($data,true)); fclose($f); @@ -36,7 +40,8 @@ class Logger $path['dirname'], '/', $path['filename'], - date('YmdHis'), + '_', + date('Y-m-d_H:i:s'), '.', $path['extension'] )); @@ -44,7 +49,7 @@ class Logger copy($file, $rotate); $this->clean($file); - $files = glob($path['dirname'] . '/' . "*" . $path['filename'] . ".log"); + $files = glob($path['dirname'] . '/' . $path['filename'] . "*" . ".log"); if (0 === $this->files) { return; @@ -52,6 +57,7 @@ class Logger if (count($files) > $this->files) { natsort($files); + $files = array_reverse($files); foreach (array_slice($files, $this->files) as $log) { if (is_writable($log)) { unlink($log); diff --git a/intaro.retailcrm/classes/general/RCrmActions.php b/intaro.retailcrm/classes/general/RCrmActions.php new file mode 100644 index 00000000..879c8d15 --- /dev/null +++ b/intaro.retailcrm/classes/general/RCrmActions.php @@ -0,0 +1,259 @@ + 'Y')); + while ($ar = $rsSites->Fetch()){ + $arSites[] = $ar; + } + + return $arSites; + } + + public static function OrderTypesList($arSites){ + $orderTypesList = array(); + foreach($arSites as $site){ + $personTypes = \Bitrix\Sale\PersonType::load($site['LID']); + $bitrixOrderTypesList = array(); + foreach($personTypes as $personType){ + if(!array_key_exists($personType['ID'], $orderTypesList)){ + $bitrixOrderTypesList[$personType['ID']] = $personType; + } + asort($bitrixOrderTypesList); + } + $orderTypesList = $orderTypesList + $bitrixOrderTypesList; + } + + return $orderTypesList; + } + + public static function DeliveryList(){ + $bitrixDeliveryTypesList = array(); + $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); + $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); + foreach($arDeliveryServiceAll as $arDeliveryService){ + if($arDeliveryService['PARENT_ID'] == '0' && $arDeliveryService['ID'] != $noOrderId){ + $bitrixDeliveryTypesList[] = $arDeliveryService; + } + } + + return $bitrixDeliveryTypesList; + } + + public static function PaymentList(){ + $bitrixPaymentTypesList = array(); + $dbPaymentAll = \Bitrix\Sale\PaySystem\Manager::getList(array( + 'select' => array('ID', 'NAME'), + 'filter' => array('ACTIVE' => 'Y') + )); + while($payment = $dbPaymentAll->fetch()) + { + $bitrixPaymentTypesList[] = $payment; + } + + return $bitrixPaymentTypesList; + } + + public static function StatusesList(){ + $bitrixPaymentStatusesList = array(); + $arStatusesAll = \Bitrix\Sale\OrderStatus::getAllStatusesNames(); + foreach($arStatusesAll as $key => $arStatus){ + $bitrixPaymentStatusesList[$key] = array('ID' => $key, 'NAME' => $arStatus); + } + + return $bitrixPaymentStatusesList; + } + + public static function OrderPropsList(){ + $bitrixPropsList = array(); + $arPropsAll = \Bitrix\Sale\Internals\OrderPropsTable::getList(array( + 'select' => array('*') + )); + while ($prop = $arPropsAll->Fetch()){ + $bitrixPropsList[$prop['PERSON_TYPE_ID']][] = $prop; + } + + return $bitrixPropsList; + } + /** + * + * 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() { + RetailCrmOrder::uploadOrders(); + $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); + if (is_array($failedIds) && !empty($failedIds)) { + RetailCrmOrder::uploadOrders(50, true); + } + + return 'RCrmActions::uploadOrdersAgent();'; + } + + /** + * + * Agent function + * + * @return self name + */ + + public static function orderAgent() { + if(COption::GetOptionString('main', 'agents_use_crontab', 'N') != 'N') { + define('NO_AGENT_CHECK', true); + } + + RetailCrmHistory::customerHistory(); + RetailCrmHistory::orderHistory(); + self::uploadOrdersAgent(); + + return 'RCrmActions::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 'ordersEdit': + case 'customersGet': + case 'customersEdit': + try { + $result = $api->$methodApi($params, 'externalId', $site); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + __CLASS__.'::'.$method, 'RetailCrm\ApiClient::'.$methodApi.'::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } catch (InvalidArgumentException $e) { + self::eventLog( + __CLASS__.'::'.$method, 'RetailCrm\ApiClient::'.$methodApi.'::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } + return $result; + + default: + try { + $result = $api->$methodApi($params, $site); + } catch (\RetailCrm\Exception\CurlException $e) { + self::eventLog( + __CLASS__.'::'.$method, 'RetailCrm\ApiClient::'.$methodApi.'::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } catch (InvalidArgumentException $e) { + self::eventLog( + __CLASS__.'::'.$method, 'RetailCrm\ApiClient::'.$methodApi.'::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } + return $result; + } + } +} diff --git a/intaro.intarocrm/classes/general/Response/ApiResponse.php b/intaro.retailcrm/classes/general/Response/ApiResponse.php similarity index 64% rename from intaro.intarocrm/classes/general/Response/ApiResponse.php rename to intaro.retailcrm/classes/general/Response/ApiResponse.php index 3997a725..70c145aa 100644 --- a/intaro.intarocrm/classes/general/Response/ApiResponse.php +++ b/intaro.retailcrm/classes/general/Response/ApiResponse.php @@ -1,11 +1,31 @@ + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + */ + namespace RetailCrm\Response; use RetailCrm\Exception\InvalidJsonException; /** + * PHP version 5.3 + * * Response from retailCRM API + * + * @category RetailCrm + * @package RetailCrm + * @author RetailCrm + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 */ class ApiResponse implements \ArrayAccess { @@ -15,6 +35,14 @@ class ApiResponse implements \ArrayAccess // response assoc array protected $response; + /** + * ApiResponse constructor. + * + * @param int $statusCode HTTP status code + * @param mixed $responseBody HTTP body + * + * @throws InvalidJsonException + */ public function __construct($statusCode, $responseBody = null) { $this->statusCode = (int) $statusCode; @@ -56,7 +84,11 @@ class ApiResponse implements \ArrayAccess /** * Allow to access for the property throw class method * - * @param string $name + * @param string $name method name + * @param mixed $arguments method parameters + * + * @throws \InvalidArgumentException + * * @return mixed */ public function __call($name, $arguments) @@ -74,7 +106,10 @@ class ApiResponse implements \ArrayAccess /** * Allow to access for the property throw object property * - * @param string $name + * @param string $name property name + * + * @throws \InvalidArgumentException + * * @return mixed */ public function __get($name) @@ -87,8 +122,13 @@ class ApiResponse implements \ArrayAccess } /** - * @param mixed $offset - * @param mixed $value + * Offset set + * + * @param mixed $offset offset + * @param mixed $value value + * + * @throws \BadMethodCallException + * @return void */ public function offsetSet($offset, $value) { @@ -96,7 +136,12 @@ class ApiResponse implements \ArrayAccess } /** - * @param mixed $offset + * Offset unset + * + * @param mixed $offset offset + * + * @throws \BadMethodCallException + * @return void */ public function offsetUnset($offset) { @@ -104,7 +149,10 @@ class ApiResponse implements \ArrayAccess } /** - * @param mixed $offset + * Check offset + * + * @param mixed $offset offset + * * @return bool */ public function offsetExists($offset) @@ -113,7 +161,12 @@ class ApiResponse implements \ArrayAccess } /** - * @param mixed $offset + * Get offset + * + * @param mixed $offset offset + * + * @throws \InvalidArgumentException + * * @return mixed */ public function offsetGet($offset) diff --git a/intaro.retailcrm/classes/general/RestApi.php b/intaro.retailcrm/classes/general/RestApi.php new file mode 100644 index 00000000..e7502aff --- /dev/null +++ b/intaro.retailcrm/classes/general/RestApi.php @@ -0,0 +1,746 @@ +url = $url; +// $this->defaultParameters = array('apiKey' => $apiKey); +// $this->siteCode = $site; +// } +// +// /* Методы для работы с заказами */ +// /** +// * Получение заказа по id +// * +// * @param string $id - идентификатор заказа +// * @param string $by - поиск заказа по id или externalId +// * @param string $site - символьный код сайта +// * @return ApiResponse - информация о заказе +// */ +// public function ordersGet($id, $by = 'externalId', $site = null) +// { +// $this->checkIdParameter($by); +// +// return $this->makeRequest("/orders/$id", self::METHOD_GET, $this->fillSite($site, array( +// 'by' => $by +// ))); +// } +// +// /** +// * Получение списка заказов, удовлетворяющих заданному фильтру +// * +// * @param array $filter - фильтры +// * @param int $page - страница +// * @param int $limit - ограничение на размер выборки +// * @return ApiResponse - информация о заказах +// */ +// public function ordersList(array $filter = array(), $page = null, $limit = null) +// { +// $parameters = array(); +// if (sizeof($filter)) { +// $parameters['filter'] = $filter; +// } +// if (null !== $page) { +// $parameters['page'] = (int) $page; +// } +// if (null !== $limit) { +// $parameters['limit'] = (int) $limit; +// } +// return $this->makeRequest('/orders', self::METHOD_GET, $parameters); +// } +// +// /** +// * Создание заказа +// * +// * @param array $order - информация о заказе +// * @param string $site - символьный код сайта +// * @return ApiResponse +// */ +// public function ordersCreate($order, $site = null) +// { +// if (!sizeof($order)) { +// throw new \InvalidArgumentException('Parameter `order` must contains a data'); +// } +// +// return $this->makeRequest("/orders/create", self::METHOD_POST, $this->fillSite($site, array( +// 'order' => json_encode($order) +// ))); +// } +// +// /** +// * Изменение заказа +// * +// * @param array $order - информация о заказе +// * @param string $by - изменение заказа по id или externalId +// * @param string $site - символьный код сайта +// * @return ApiResponse +// */ +// public function orderEdit($order, $by = 'externalId', $site = null) +// { +// if (!sizeof($order)) { +// throw new \InvalidArgumentException('Parameter `order` must contains a data'); +// } +// +// $this->checkIdParameter($by); +// +// if (!isset($order[$by])) { +// throw new \InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by)); +// } +// +// return $this->makeRequest( +// "/orders/" . $order[$by] . "/edit", +// self::METHOD_POST, +// $this->fillSite($site, array( +// 'order' => json_encode($order), +// 'by' => $by, +// )) +// ); +// } +// +// /** +// * Пакетная загрузка заказов +// * +// * @param array $orders - массив заказов +// * @param string $site - символьный код сайта +// * @return ApiResponse +// */ +// public function orderUpload($orders, $site = null) +// { +// if (!sizeof($orders)) { +// throw new \InvalidArgumentException('Parameter `orders` must contains array of the orders'); +// } +// +// return $this->makeRequest("/orders/upload", self::METHOD_POST, $this->fillSite($site, array( +// 'orders' => json_encode($orders), +// ))); +// } +// +// /** +// * Обновление externalId у заказов с переданными id +// * +// * @param array $order - массив, содержащий id и externalId заказа +// * @return ApiResponse +// */ +// public function orderFixExternalIds($order) +// { +// if (!sizeof($order)) { +// throw new \InvalidArgumentException('Method parameter must contains at least one IDs pair'); +// } +// +// return $this->makeRequest("/orders/fix-external-ids", self::METHOD_POST, array( +// 'orders' => json_encode($order), +// )); +// } +// +// /** +// * Получение последних измененных заказов +// * +// * @param \DateTime|string|int $startDate - начальная дата и время выборки (Y-m-d H:i:s) +// * @param \DateTime|string|int $endDate - конечная дата и время выборки (Y-m-d H:i:s) +// * @param int $limit - ограничение на размер выборки +// * @param int $offset - сдвиг +// * @param bool $skipMyChanges +// * @return ApiResponse +// */ +// public function orderHistory( +// $startDate = null, +// $endDate = null, +// $limit = 100, +// $offset = 0, +// $skipMyChanges = true +// ) { +// $parameters = array(); +// +// if ($startDate) { +// $parameters['startDate'] = $this->ensureDateTime($startDate); +// } +// if ($endDate) { +// $parameters['endDate'] = $this->ensureDateTime($endDate); +// } +// if ($limit) { +// $parameters['limit'] = (int) $limit; +// } +// if ($offset) { +// $parameters['offset'] = (int) $offset; +// } +// if ($skipMyChanges) { +// $parameters['skipMyChanges'] = (bool) $skipMyChanges; +// } +// +// return $this->makeRequest('/orders/history', self::METHOD_GET, $parameters); +// } +// +// /* Методы для работы с клиентами */ +// /** +// * Получение клиента по id +// * +// * @param string $id - идентификатор +// * @param string $by - поиск заказа по id или externalId +// * @param string $site - символьный код сайта +// * @return array - информация о клиенте +// */ +// public function customerGet($id, $by = 'externalId', $site = null) +// { +// $this->checkIdParameter($by); +// +// return $this->makeRequest("/customers/$id", self::METHOD_GET, $this->fillSite($site, array( +// 'by' => $by +// ))); +// } +// +// /** +// * Получение списка клиентов в соответсвии с запросом +// * +// * @param array $filter - фильтры +// * @param int $page - страница +// * @param int $limit - ограничение на размер выборки +// * @return ApiResponse +// */ +// public function customersList(array $filter = array(), $page = null, $limit = null) +// { +// $parameters = array(); +// +// if (sizeof($filter)) { +// $parameters['filter'] = $filter; +// } +// +// if (null !== $page) { +// $parameters['page'] = (int) $page; +// } +// +// if (null !== $limit) { +// $parameters['limit'] = (int) $limit; +// } +// +// return $this->makeRequest('/customers', self::METHOD_GET, $parameters); +// } +// +// /** +// * Создание клиента +// * +// * @param array $customer - информация о клиенте +// * @param string $site - символьный код сайта +// * @return ApiResponse +// */ +// public function customersCreate(array $customer, $site = null) +// { +// if (!sizeof($customer)) { +// throw new \InvalidArgumentException('Parameter `customer` must contains a data'); +// } +// +// return $this->makeRequest("/customers/create", self::METHOD_POST, $this->fillSite($site, array( +// 'customer' => json_encode($customer) +// ))); +// } +// +// /** +// * Редактирование клиента +// * +// * @param array $customer - информация о клиенте +// * @param string $by - изменение клиента по id или externalId +// * @param string $site - символьный код сайта +// * @return ApiResponse +// */ +// public function customerEdit($customer, $by = 'externalId', $site = null) +// { +// if (!sizeof($customer)) { +// throw new \InvalidArgumentException('Parameter `customer` must contains a data'); +// } +// +// $this->checkIdParameter($by); +// +// if (!isset($customer[$by])) { +// throw new \InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by)); +// } +// +// return $this->makeRequest( +// "/customers/" . $customer[$by] . "/edit", +// self::METHOD_POST, +// $this->fillSite($site, array( +// 'customer' => json_encode($customer), +// 'by' => $by, +// ) +// )); +// } +// +// /** +// * Пакетная загрузка клиентов +// * +// * @param array $customers - массив клиентов +// * @param string $site - символьный код сайта +// * @return ApiResponse +// */ +// public function customerUpload($customers, $site = null) +// { +// if (!sizeof($customers)) { +// throw new \InvalidArgumentException('Parameter `customers` must contains array of the customers'); +// } +// +// return $this->makeRequest("/customers/upload", self::METHOD_POST, $this->fillSite($site, array( +// 'customers' => json_encode($customers), +// ))); +// } +// +// /** +// * Обновление externalId у клиентов с переданными id +// * +// * @param array $customers - массив, содержащий id и externalId заказа +// * @return array +// */ +// public function customerFixExternalIds($customers) +// { +// if (!sizeof($customers)) { +// throw new \InvalidArgumentException('Method parameter must contains at least one IDs pair'); +// } +// +// return $this->makeRequest("/customers/fix-external-ids", self::METHOD_POST, array( +// 'customers' => json_encode($customers), +// )); +// } +// +// /* Методы для работы со справочниками */ +// +// /** +// * Получение списка типов доставки +// * +// * @return ApiResponse +// */ +// public function deliveryTypesList() +// { +// return $this->makeRequest('/reference/delivery-types', self::METHOD_GET); +// } +// +// /** +// * Редактирование типа доставки +// * +// * @param array $delivery - информация о типе доставки +// * @return ApiResponse +// */ +// public function deliveryTypeEdit($delivery) +// { +// if (!isset($delivery['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/delivery-types/' . $delivery['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'deliveryType' => json_encode($delivery) +// ) +// ); +// } +// +// /** +// * Получение списка служб доставки +// * +// * @return ApiResponse +// */ +// public function deliveryServicesList() +// { +// return $this->makeRequest('/reference/delivery-services', self::METHOD_GET); +// } +// +// /** +// * Редактирование службы доставки +// * +// * @param array $delivery - информация о типе доставки +// * @return ApiResponse +// */ +// public function deliveryServiceEdit($delivery) +// { +// if (!isset($delivery['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/delivery-services/' . $delivery['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'deliveryService' => json_encode($delivery) +// ) +// ); +// } +// +// +// /** +// * Получение списка типов оплаты +// * +// * @return ApiResponse +// */ +// public function paymentTypesList() +// { +// return $this->makeRequest('/reference/payment-types', self::METHOD_GET); +// } +// +// /** +// * Редактирование типа оплаты +// * +// * @param array $paymentType - информация о типе оплаты +// * @return ApiResponse +// */ +// public function paymentTypesEdit($paymentType) +// { +// if (!isset($paymentType['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/payment-types/' . $paymentType['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'paymentType' => json_encode($paymentType) +// ) +// ); +// } +// +// +// /** +// * Получение списка статусов оплаты +// * +// * @return ApiResponse +// */ +// public function paymentStatusesList() +// { +// return $this->makeRequest('/reference/payment-statuses', self::METHOD_GET); +// } +// +// /** +// * Редактирование статуса оплаты +// * +// * @param array $paymentStatus - информация о статусе оплаты +// * @return ApiResponse +// */ +// public function paymentStatusesEdit($paymentStatus) +// { +// if (!isset($paymentStatus['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/payment-statuses/' . $paymentStatus['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'paymentStatus' => json_encode($paymentStatus) +// ) +// ); +// } +// +// +// /** +// * Получение списка типов заказа +// * +// * @return ApiResponse +// */ +// public function orderTypesList() +// { +// return $this->makeRequest('/reference/order-types', self::METHOD_GET); +// } +// +// /** +// * Редактирование типа заказа +// * +// * @param array $orderType - информация о типе заказа +// * @return ApiResponse +// */ +// public function orderTypesEdit($orderType) +// { +// if (!isset($orderType['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/order-types/' . $orderType['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'orderType' => json_encode($orderType) +// ) +// ); +// } +// +// +// /** +// * Получение списка способов оформления заказа +// * +// * @return ApiResponse +// */ +// public function orderMethodsList() +// { +// return $this->makeRequest('/reference/order-methods', self::METHOD_GET); +// } +// +// /** +// * Редактирование способа оформления заказа +// * +// * @param array $orderMethod - информация о способе оформления заказа +// * @return ApiResponse +// */ +// public function orderMethodsEdit($orderMethod) +// { +// if (!isset($orderMethod['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/order-methods/' . $orderMethod['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'orderMethod' => json_encode($orderMethod) +// ) +// ); +// } +// +// /** +// * Получение списка статусов заказа +// * +// * @return ApiResponse +// */ +// public function orderStatusesList() +// { +// return $this->makeRequest('/reference/statuses', self::METHOD_GET); +// } +// +// /** +// * Получение списка сайтов +// * +// * @return ApiResponse +// */ +// public function sitesList() +// { +// return $this->makeRequest('/reference/sites', self::METHOD_GET); +// } +// +// /** +// * Редактирование статуса заказа +// * +// * @param array $status - информация о статусе заказа +// * @return ApiResponse +// */ +// public function orderStatusEdit($status) +// { +// if (!isset($status['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/statuses/' . $status['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'status' => json_encode($status) +// ) +// ); +// } +// +// +// /** +// * Получение списка групп статусов заказа +// * +// * @return ApiResponse +// */ +// public function orderStatusGroupsList() +// { +// return $this->makeRequest('/reference/status-groups', self::METHOD_GET); +// } +// +// /** +// * Обновление статистики +// * +// * @return ApiResponse +// */ +// public function statisticUpdate() +// { +// return $this->makeRequest('/statistic/update', self::METHOD_GET); +// } +// +// /** +// * Обновление остатков +// * +// * @return ApiResponse +// */ +// public function storeUpload($data, $site) +// { +// if (!sizeof($data)) { +// throw new \InvalidArgumentException('Parameter `site` must contains array of the customers'); +// } +// +// return $this->makeRequest('/store/inventories/upload', self::METHOD_POST, $this->fillSite($site, array('offers' => json_encode($data)))); +// } +// +// /** +// * Редактирование сведений о складе +// * +// * @return ApiResponse +// */ +// public function storesEdit($data) +// { +// if (!isset($data['code'])) { +// throw new \InvalidArgumentException('Data must contain "code" parameter.'); +// } +// +// return $this->makeRequest( +// '/reference/stores/' . $data['code'] . '/edit', +// self::METHOD_POST, +// array( +// 'store' => json_encode($data) +// ) +// ); +// } +// +// /** +// * @return \DateTime +// */ +// public function getGeneratedAt() +// { +// return $this->generatedAt; +// } +// +// protected function ensureDateTime($value) +// { +// if ($value instanceof \DateTime) { +// return $value->format('Y-m-d H:i:s'); +// } elseif (is_int($value)) { +// return date('Y-m-d H:i:s', $value); +// } +// +// return $value; +// } +// +// /** +// * Check ID parameter +// * +// * @param string $by +// * @return bool +// */ +// protected function checkIdParameter($by) +// { +// $allowedForBy = array('externalId', 'id'); +// if (!in_array($by, $allowedForBy)) { +// throw new \InvalidArgumentException(sprintf( +// 'Value "%s" for parameter "by" is not valid. Allowed values are %s.', +// $by, +// implode(', ', $allowedForBy) +// )); +// } +// return true; +// } +// +// /** +// * Fill params by site value +// * +// * @param string $site +// * @param array $params +// * @return array +// */ +// protected function fillSite($site, array $params) +// { +// if ($site) { +// $params['site'] = $site; +// } elseif ($this->siteCode) { +// $params['site'] = $this->siteCode; +// } +// +// return $params; +// } +// +// /** +// * Make HTTP request +// * +// * @param string $path +// * @param string $method (default: 'GET') +// * @param array $parameters (default: array()) +// * @param int $timeout +// * @return ApiResponse +// */ +// public function makeRequest($path, $method, $parameters = array(), $timeout = 30) +// { +// $allowedMethods = array(self::METHOD_GET, self::METHOD_POST); +// if (!in_array($method, $allowedMethods)) { +// throw new \InvalidArgumentException(sprintf( +// 'Method "%s" is not valid. Allowed methods are %s', +// $method, +// implode(', ', $allowedMethods) +// )); +// } +// +// $parameters = array_merge($this->defaultParameters, $parameters); +// +// $path = $this->url . $path; +// if (self::METHOD_GET === $method && sizeof($parameters)) { +// $path .= '?' . http_build_query($parameters); +// } +// +// $ch = curl_init(); +// curl_setopt($ch, CURLOPT_URL, $path); +// curl_setopt($ch, CURLOPT_FAILONERROR, false); +// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable +// curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout); // times out after 30s +// // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); +// // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects +// +// if (self::METHOD_POST === $method) { +// curl_setopt($ch, CURLOPT_POST, true); +// curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); +// } +// +// $responseBody = curl_exec($ch); +// $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); +// +// $errno = curl_errno($ch); +// $error = curl_error($ch); +// curl_close($ch); +// +// if ($errno) { +// throw new CurlException($error, $errno); +// } +// +// $result = json_decode($responseBody, true); +// +// if (isset($result['generatedAt'])) { +// $this->generatedAt = new \DateTime($result['generatedAt']); +// unset($result['generatedAt']); +// } +// +// return new ApiResponse($statusCode, $responseBody); +// } +//} diff --git a/intaro.intarocrm/classes/general/RestNormalizer.php b/intaro.retailcrm/classes/general/RestNormalizer.php similarity index 82% rename from intaro.intarocrm/classes/general/RestNormalizer.php rename to intaro.retailcrm/classes/general/RestNormalizer.php index 731970da..b9d1e37f 100644 --- a/intaro.intarocrm/classes/general/RestNormalizer.php +++ b/intaro.retailcrm/classes/general/RestNormalizer.php @@ -1,45 +1,4 @@ . - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * * Neither the name of Dmitry Mamontov nor the names of his - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - * @package restnormalizer - * @author Dmitry Mamontov - * @copyright 2015 Dmitry Mamontov - * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License - * @since File available since Release 1.0.0 - */ /** * RestNormalizer - The main class @@ -54,26 +13,10 @@ class RestNormalizer { - /** - * Cleanup of null values - * @var boolean - * @access public - */ public $clear = true; - - /** - * Sorted file validation - * @var array - * @access private - */ private $validation = array(); - - /** - * File validation - * @var array - * @access private - */ - private $originalValidation = array(); + private $originalValidation = array(); + private $server; /** * Class constructor @@ -86,6 +29,7 @@ class RestNormalizer if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(@date_default_timezone_get()); } + $this->server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); } /** @@ -95,15 +39,16 @@ class RestNormalizer * @access public * @final */ - final public function setValidation($file) - { - if (is_null($file) || is_file($file) === false - || json_decode(file_get_contents($file)) === null - || $this->parseConfig($file) === false) { - ICrmOrderActions::eventLog('RestNormalizer', 'intaro.intarocrm', 'Incorrect file normalize.'); - return false; - } - } +// final public function setValidation($file = false) +// { +// if ($file === false || is_null($file) || is_file($file) === false) { +// $file = $this->server . '/bitrix/modules/intaro.intarocrm/classes/general/config/retailcrm.json'; +// } +// if (json_decode(file_get_contents($file)) === null || $this->parseConfig($file) === false) { +// ICrmOrderActions::eventLog('RestNormalizer', 'intaro.retailcrm', 'Incorrect file normalize.'); +// return false; +// } +// } /** * Parsing the file validation @@ -130,8 +75,17 @@ class RestNormalizer * @access public * @final */ - final public function normalize($data, $key = false) + final public function normalize($data, $key = false, $file = '/bitrix/modules/intaro.retailcrm/classes/general/config/retailcrm.json') { + $server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); + $file = $server . $file; + if (is_null($file) || is_file($file) === false + || json_decode(file_get_contents($file)) === null + || $this->parseConfig($file) === false) { + ICrmOrderActions::eventLog('RestNormalizer', 'intaro.retailcrm', 'Incorrect file normalize.'); + return false; + } + if (is_string($data)) { $data = json_decode($data, true); } @@ -143,7 +97,7 @@ class RestNormalizer } if (!is_array($data) || count($data) < 1) { - ICrmOrderActions::eventLog('RestNormalizer', 'intaro.intarocrm', 'Incorrect data array.'); + ICrmOrderActions::eventLog('RestNormalizer', 'intaro.retailcrm', 'Incorrect data array.'); return false; } @@ -188,7 +142,7 @@ class RestNormalizer if ($skip === false) { foreach ($this->validation as $code => $valid) { if (isset($valid['required']) && $valid['required'] === true && isset($formatted[ $code ]) === false) { - ICrmOrderActions::eventLog('RestNormalizer', 'intaro.intarocrm', "NOT VALID: $code"); + ICrmOrderActions::eventLog('RestNormalizer', 'intaro.retailcrm', "NOT VALID: $code"); } } diff --git a/intaro.retailcrm/classes/general/config/objects.xml b/intaro.retailcrm/classes/general/config/objects.xml new file mode 100644 index 00000000..83346601 --- /dev/null +++ b/intaro.retailcrm/classes/general/config/objects.xml @@ -0,0 +1,100 @@ + + + + id + firstName + lastName + patronymic + email + birthday + phones + manager + commentary + externalId + cumulativeDiscount + personalDiscount + discountCardNumber + + index + countryIso + region + city + street + building + house + block + flat + floor + intercomCode + metro + notes + + contragentType + legalName + legalAddress + certificateNumber + certificateDate + bank + bankAddress + corrAccount + bankAccount + + id + createdAt + orderType + orderMethod + site + status + statusComment + manager + firstName + lastName + patronymic + phone + additionalPhone + email + paymentType + paymentStatus + discount + discountPercent + prepaySum + customerComment + managerComment + shipmentStore + shipmentDate + shipped + + + id + initialPrice + discount + discountPercent + quantity + status + + code + service + date + time + cost + netCost + + country + index + region + city + street + building + house + block + flat + floor + intercomCode + metro + notes + + status + trackNumber + courier + + \ No newline at end of file diff --git a/intaro.intarocrm/classes/general/config/options.xml b/intaro.retailcrm/classes/general/config/options.xml similarity index 97% rename from intaro.intarocrm/classes/general/config/options.xml rename to intaro.retailcrm/classes/general/config/options.xml index 95c4ce1f..789cb31d 100644 --- a/intaro.intarocrm/classes/general/config/options.xml +++ b/intaro.retailcrm/classes/general/config/options.xml @@ -13,7 +13,7 @@ Город Индекс Улица - Строение + Номер дома Квартира Домофон Этаж diff --git a/intaro.intarocrm/classes/general/config/retailcrm.json b/intaro.retailcrm/classes/general/config/retailcrm.json similarity index 99% rename from intaro.intarocrm/classes/general/config/retailcrm.json rename to intaro.retailcrm/classes/general/config/retailcrm.json index 0ec120bb..4c612a0c 100644 --- a/intaro.intarocrm/classes/general/config/retailcrm.json +++ b/intaro.retailcrm/classes/general/config/retailcrm.json @@ -377,6 +377,9 @@ }, "text": { "type": "string" + }, + "shipmentStore": { + "type": "string" } } } \ No newline at end of file diff --git a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php new file mode 100644 index 00000000..b2da1501 --- /dev/null +++ b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php @@ -0,0 +1,216 @@ + $arFields['ID'], + 'firstName' => $arFields['NAME'], + 'lastName' => $arFields['LAST_NAME'], + 'patronymic' => $arFields['SECOND_NAME'], + 'email' => $arFields['EMAIL'] + ); + if(isset($arFields['PERSONAL_PHONE'])){ + $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; + } + if(isset($arFields['WORK_PHONE'])){ + $customer['phones'][]['number'] = $arFields['WORK_PHONE']; + } + + if (function_exists('retailcrmBeforeCustomerSend')) { + $newResCustomer = intarocrm_before_customer_send($customer); + if (is_array($newResCustomer) && !empty($newResCustomer)) { + $customer = $newResCustomer; + } + } + $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); + + $api = new RetailCrm\ApiClient($api_host, $api_key); + + //ищем юзера по id и др. данным. + //апдейтим если находим + } + + /** + * onBeforeOrderAdd + * + * @param mixed $arFields - User arFields + */ + function onBeforeOrderAdd($arFields = array()) { + $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false; + return; + } + + /** + * OnOrderSave + * + * @param mixed $ID - Order id + * @param mixed $arFields - Order arFields + */ + function OnOrderSave($ID, $arFields, $arOrder, $isNew) { + $GLOBALS['RETAILCRM_EVENT_OLD'] = true; + return; + } + + /** + * onUpdateOrder + * + * @param mixed $ID - Order id + * @param mixed $arFields - Order arFields + */ + function onUpdateOrder($ID, $arFields) { + if(isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']){ + $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false; + return; + } + + $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = true; + return; + } + + /** + * orderDelete + * + * @param object $event - Order object + */ + function orderDelete($event){ + $GLOBALS['RETAILCRM_ORDER_DELETE'] = true; + return; + } + + /** + * orderSave + * + * @param object $event - Order object + */ + + function orderSave($event){ + if($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true){ + + if (!CModule::IncludeModule('iblock')) { + RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found'); + return true; + } + + if (!CModule::IncludeModule("sale")) { + RCrmActions::eventLog('RetailCrmEvent::orderSave', 'sale', 'module not found'); + return true; + } + + if (!CModule::IncludeModule("catalog")) { + RCrmActions::eventLog('RetailCrmEvent::orderSave', 'catalog', 'module not found'); + return true; + } + + //проверка на существование getParameter("ENTITY") + if(method_exists($event, 'getId')){ + $obOrder = $event; + } + elseif(method_exists($event, 'getParameter')){ + $obOrder = $event->getParameter("ENTITY"); + } + else{ + RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error'); + return true; + } + + $arOrder = RetailCrmOrder::orderObjToArr($obOrder); + + //api + $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); + $api = new RetailCrm\ApiClient($api_host, $api_key); + + //params + $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)); + $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 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)); + + $arParams = RCrmActions::clearArr(array( + 'optionsOrderTypes' => $optionsOrderTypes, + 'optionsDelivTypes' => $optionsDelivTypes, + 'optionsPayTypes' => $optionsPayTypes, + 'optionsPayStatuses' => $optionsPayStatuses, + 'optionsPayment' => $optionsPayment, + 'optionsOrderProps' => $optionsOrderProps, + 'optionsLegalDetails' => $optionsLegalDetails, + 'optionsContragentType' => $optionsContragentType, + 'optionsSitesList' => $optionsSitesList, + 'optionsCustomFields' => $optionsCustomFields + )); + + //многосайтовость + $site = count($optionsSitesList)>1 ? $optionsSitesList[$arOrder['LID']] : null; + + //проверка на новый заказ + $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site); + if(isset($orderCrm['order'])){ + $methodApi = 'ordersEdit'; + } + else{ + $methodApi = 'ordersCreate'; + } + + //user + $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site); + if(!isset($userCrm['customer'])){ + $arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch(); + $resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site); + if(!$resultUser) { + RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer'); + return true; + } + } + + //order + $resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi); + if(!$resultOrder) { + RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order'); + return true; + } + + return true; + } + + return; + } +} \ No newline at end of file diff --git a/intaro.retailcrm/classes/general/history/RetailCrmHistory.php b/intaro.retailcrm/classes/general/history/RetailCrmHistory.php new file mode 100644 index 00000000..0777035f --- /dev/null +++ b/intaro.retailcrm/classes/general/history/RetailCrmHistory.php @@ -0,0 +1,1168 @@ + 0){ + $historyFilter['sinceId'] = $historyStart; + } + + while(true){ + try { + $customerHistory = $api->customersHistory($historyFilter); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::customerHistory', 'RetailCrm\RestApi::customersHistory::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::customerHistory', 'RetailCrm\RestApi::customersHistory::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } + + $customerH = isset($customerHistory['history']) ? $customerHistory['history'] : array(); + + $log = new Logger(); + $log->write($customerH, 'customerHistory'); + if(count($customerH) == 0){ + return true; + } + + $customers = self::assemblyCustomer($customerH); + + $GLOBALS['RETAIL_CRM_HISTORY'] = true; + + $newUser = new CUser; + + foreach($customers as $customer){ + if (function_exists('retailCrmBeforeCustomerSave')) { + $newResCustomer = retailCrmBeforeCustomerSave($customer); + if (is_array($newResCustomer) && !empty($newResCustomer)) { + $customer = $newResCustomer; + } + } + + if(isset($customer['deleted'])){ + continue; + } + + if (!isset($customer['externalId'])) { + if (!isset($customer['id'])) { + continue; + } + + $registerNewUser = true; + if (!isset($customer['email']) || $customer['email'] == '') { + $login = $customer['email'] = uniqid('user_' . time()) . '@crm.com'; + } else { + $dbUser = CUser::GetList(($by = 'ID'), ($sort = 'ASC'), array('=EMAIL' => $customer['email'])); + switch ($dbUser->SelectedRowsCount()) { + case 0: + $login = $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(); + + $arFields = array( + "EMAIL" => $customer['email'], + "LOGIN" => $login, + "ACTIVE" => "Y", + "PASSWORD" => $userPassword, + "CONFIRM_PASSWORD" => $userPassword + ); + $registeredUserID = $newUser->Add($arFields); + if ($registeredUserID === false) { + RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'CUser::Register', 'Error register user'); + continue; + } + + try { + $api->customersFixExternalIds(array(array('id' => $customer['id'], 'externalId' => $registeredUserID))); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } + } + + $customer['externalId'] = $registeredUserID; + } + + if(isset($customer['externalId'])){ + $arUser = array(); + if(array_key_exists('firstName', $customer)){ + $arUser["NAME"] = $customer['firstName'] ? RCrmActions::fromJSON($customer['firstName']) : ''; + } + if(array_key_exists('lastName', $customer)){ + $arUser["LAST_NAME"] = $customer['lastName'] ? RCrmActions::fromJSON($customer['lastName']) : ''; + } + if(array_key_exists('patronymic', $customer)){ + $arUser["SECOND_NAME"] = $customer['patronymic'] ? RCrmActions::fromJSON($customer['patronymic']) : ''; + } + + if(array_key_exists('email', $customer)){ + $arUser["EMAIL"] = $customer['email'] ? RCrmActions::fromJSON($customer['email']) : ''; + } + + if(isset($customer['phones'])){ + $user = CUser::GetList(($by="ID"), ($order="desc"), array('ID' => $customer['externalId']), array('FIELDS' => array('PERSONAL_PHONE', 'PERSONAL_MOBILE')))->fetch(); + foreach($customer['phones'] as $phone){ + if(isset($phone['old_number']) && in_array($phone['old_number'], $user)){ + $key = array_search($phone['old_number'], $user); + if(isset($phone['number'])){ + $arUser[$key] = $phone['number']; + $user[$key] = $phone['number']; + } + else{ + $arUser[$key] = ''; + $user[$key] = ''; + } + } + if(isset($phone['number'])){ + if((!isset($user['PERSONAL_PHONE']) || strlen($user['PERSONAL_PHONE']) == 0) && $user['PERSONAL_MOBILE'] != $phone['number']){ + $arUser['PERSONAL_PHONE'] = $phone['number']; + $user['PERSONAL_PHONE'] = $phone['number']; + continue; + } + if((!isset($user['PERSONAL_MOBILE']) || strlen($user['PERSONAL_MOBILE']) == 0) && $user['PERSONAL_PHONE'] != $phone['number']){ + $arUser['PERSONAL_MOBILE'] = $phone['number']; + $user['PERSONAL_MOBILE'] = $phone['number']; + continue; + } + } + } + } + + $u = $newUser->Update($customer['externalId'], $arUser); + if(!$u){ + RCrmActions::eventLog('RetailCrmHistory::customerHistory', 'Error update user', $newUser->LAST_ERROR); + } + + if (function_exists('retailCrmAfterCustomerSave')) { + retailCrmAfterCustomerSave($customer); + } + } + } + + $GLOBALS['RETAIL_CRM_HISTORY'] = false; + + //запоминаем номер последнего изменения + $end = array_pop($customerH); + COption::SetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY, $end['id']); + + if($customerHistory['pagination']['totalPageCount'] == 1){ + return true; + } + //новый фильтр для истории + $historyFilter['sinceId'] = $end['id']; + } + } + + public static function orderHistory() { + global $USER; + if (is_object($USER) == false) { + $USER = new RetailUser; + } + if (!CModule::IncludeModule("iblock")) { + RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found'); + return false; + } + if (!CModule::IncludeModule("sale")) { + RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'sale', 'module not found'); + return false; + } + if (!CModule::IncludeModule("catalog")) { + RCrmActions::eventLog('RetailCrmHistory::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)); + $optionsOrderNumbers = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_NUMBERS, 0); + $optionsCanselOrder = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CANSEL_ORDER, 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\ApiClient($api_host, $api_key); + + $historyFilter = array(); + $historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY); + if($historyStart && $historyStart > 0){ + $historyFilter['sinceId'] = $historyStart; + } + + while(true){ + try { + $orderHistory = $api->ordersHistory($historyFilter); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersHistory::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersHistory::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + return false; + } + + $orderH = isset($orderHistory['history']) ? $orderHistory['history'] : array(); + + $log = new Logger(); + $log->write($orderH, 'orderHistory'); + if(count($orderH) == 0){ + return true; + } + + $orders = self::assemblyOrder($orderH); + + $GLOBALS['RETAIL_CRM_HISTORY'] = true; + + //обработка заказа + foreach ($orders as $order) { + if (function_exists('retailCrmBeforeOrderSave')) { + $newResOrder = retailCrmBeforeOrderSave($order); + if (is_array($newResOrder) && !empty($newResOrder)) { + $order = $newResOrder; + } + } + + if(isset($order['deleted'])){ + continue; + } + + if (!isset($order['externalId'])) { + if (!isset($order['customer']['externalId'])) { + if (!isset($order['customer']['id'])) { + continue; + } + + $registerNewUser = true; + + if (!isset($order['customer']['email']) || $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" => RCrmActions::fromJSON($order['customer']['firstName']), + "LAST_NAME" => RCrmActions::fromJSON($order['customer']['lastName']), + "SECOND_NAME" => RCrmActions::fromJSON($order['customer']['patronymic']), + "EMAIL" => $order['customer']['email'], + "LOGIN" => $login, + "ACTIVE" => "Y", + "PASSWORD" => $userPassword, + "CONFIRM_PASSWORD" => $userPassword + ); + if($order['customer']['phones'][0]){ + $arFields['PERSONAL_PHONE'] = $order['customer']['phones'][0]; + } + if($order['customer']['phones'][1]){ + $arFields['PERSONAL_MOBILE'] = $order['customer']['phones'][1]; + } + $registeredUserID = $newUser->Add($arFields); + if ($registeredUserID === false) { + RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'CUser::Register', 'Error register user'); + continue; + } + + try { + $api->customersFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::customerFixExternalIds::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } + } + + $order['customer']['externalId'] = $registeredUserID; + } + + if(isset($optionsSitesList)){ + $site = array_search($order['site'], $optionsSitesList); + } + else{ + $site = CSite::GetDefSite(); + } + + $newOrder = Bitrix\Sale\Order::create($site, $order['customer']['externalId']); + $newOrder = $newOrder->save(); + $externalId = $newOrder->getId(); + + if (isset($externalId)) { + try { + $api->ordersFixExternalIds(array(array('id' => $order['id'], 'externalId' => $externalId))); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::orderFixExternalIds::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::orderFixExternalIds::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + continue; + } + } + else{ + RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::create', 'Error order create'); + } + $order['externalId'] = $externalId; + } + + if (isset($order['externalId']) && $order['externalId']) { + $newOrder = Bitrix\Sale\Order::load($order['externalId']); + if(!$newOrder){ + RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::load', 'Error order load'); + continue; + } + + if($optionsOrderNumbers == 'Y' && isset($order['number'])){ + $newOrder->setField('ACCOUNT_NUMBER', $order['number']); + } + + if($optionsOrderTypes[$order['orderType']]){ + $personType = $optionsOrderTypes[$order['orderType']]; + $newOrder->setField('PERSON_TYPE_ID', $personType); + } + else{ + $personType = $newOrder->getField('PERSON_TYPE_ID'); + } + + //status + if($optionsPayStatuses[$order['status']]){ + $newOrder->setField('STATUS_ID', $optionsPayStatuses[$order['status']]); + if(in_array($optionsPayStatuses[$order['status']], $optionsCanselOrder)){ + $newOrder->setField('CANCELED', 'Y'); + } + else{ + $newOrder->setField('CANCELED', 'N'); + } + } + + if(array_key_exists('statusComment', $order)){ + self::setProp($newOrder, $order['statusComment'], 'REASON_CANCELED'); + } + + $propertyCollection = $newOrder->getPropertyCollection(); + $propertyCollectionArr = $propertyCollection->getArray(); + + $propsKey = array(); + foreach($propertyCollectionArr['properties'] as $prop){ + $propsKey[$prop['CODE']]['ID'] = $prop['ID']; + $propsKey[$prop['CODE']]['TYPE'] = $prop['ID']; + } + //fio + if($order['firstName'] || $order['lastName'] || $order['patronymic']){ + $fio = ''; + foreach($propertyCollectionArr['properties'] as $prop){ + if(in_array($optionsOrderProps[$personType]['fio'], $prop)){ + $fio = $newOrder->getPropertyCollection()->getItemByOrderPropertyId($prop['ID']); + } + } + + $fio = RCrmActions::explodeFIO($fio); + if($fio){ + $order['fio'] = trim( + implode( + ' ', + array( + isset($order['lastName']) ? $order['lastName'] : (isset($fio['lastName']) ? $fio['lastName'] : ''), + isset($order['firstName']) ? $order['firstName'] : (isset($fio['firstName']) ? $fio['firstName'] : ''), + isset($order['patronymic']) ? $order['patronymic'] : (isset($fio['patronymic']) ? $fio['patronymic'] : ''), + ) + ) + ); + } + else{ + $order['fio'] = trim( + implode( + ' ', + array( + isset($order['lastName']) ? $order['lastName'] : '', + isset($order['firstName']) ? $order['firstName'] : '', + isset($order['patronymic']) ? $order['patronymic'] : '', + ) + ) + ); + } + } + + //optionsOrderProps + + if($optionsOrderProps[$personType]){ + foreach($optionsOrderProps[$personType] as $key => $orderProp){ + if(array_key_exists($key, $order)){ + $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); + self::setProp($somePropValue, $order[$key]); + } + elseif(array_key_exists($key, $order['delivery']['address'])){ + if($propsKey[$key]['TYPE'] == 'LOCATION'){ + $parameters['filter']['NAME'] = $order['delivery']['address'][$key]; + $parameters['filter']['LANGUAGE_ID'] = 'ru'; + $location = \Bitrix\Sale\Location\LocationTable::getListFast($parameters)->fetch(); + $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); + self::setProp($somePropValue, $location['CODE']); + } + else{ + $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); + self::setProp($somePropValue, $order['delivery']['address'][$key]); + } + } + } + } + //optionsLegalDetails + if($optionsLegalDetails[$personType]){ + foreach($optionsLegalDetails[$personType] as $key => $orderProp){ + if(array_key_exists($key, $order)){ + $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$key]['ID']); + self::setProp($somePropValue, $order[$key]); + } + } + } + //paymentStatus + if($optionsPayment[$order['paymentStatus']]){ + $newOrder->setField('PAYED', $optionsPayment[$order['paymentStatus']]); + } + //comments + if(array_key_exists('customerComment', $order)){ + self::setProp($newOrder, $order['customerComment'], 'USER_DESCRIPTION'); + } + if(array_key_exists('managerComment', $order)){ + self::setProp($newOrder, $order['managerComment'], 'COMMENTS'); + } + + //items + $basket = $newOrder->getBasket(); + + foreach($order['items'] as $product){ + $item = self::getExistsItem($basket, 'catalog', $product['offer']['externalId']); + if(!$item){ + $item = $basket->createItem('catalog', $product['offer']['externalId']); + $item->setFields(array( + 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), + 'LID' => \Bitrix\Main\Context::getCurrent()->getSite(), + 'BASE_PRICE' => $product['initialPrice'], + 'NAME' => $product['offer']['name'], + 'DETAIL_PAGE_URL' => self::getUrl($product['offer']['externalId']) + )); + } + + if($product['quantity']){ + $item->setField('QUANTITY', $product['quantity']); + } + + if(array_key_exists('discount', $product) || array_key_exists('discountPercent', $product)){ + if(!isset($orderCrm)){ + try { + $orderCrm = $api->ordersGet($order['id'], 'id'); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersGet::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + } + } + + foreach($orderCrm['order']['items'] as $itemCrm){ + if($itemCrm['offer']['externalId'] == $product['offer']['externalId']){ + $itemCost = $itemCrm['initialPrice'] - $itemCrm['discount'] - round(($itemCrm['initialPrice'] / 100 * $itemCrm['discountPercent']), 2); + break; + } + } + + if(isset($itemCost) && $itemCost > 0){ + $item->setField('CUSTOM_PRICE', 'Y'); + $item->setField('PRICE', $itemCost); + $item->setField('DISCOUNT_NAME', ''); + $item->setField('DISCOUNT_VALUE', ''); + } + } + + if($product['delete']){ + $item->delete(); + } + $basket->save(); + + } + + $orderSumm = 0; + foreach($basket as $item){ + $orderSumm += $item->getFinalPrice(); + } + + if(array_key_exists('cost', $order['delivery'])){ + $deliverySumm = $order['delivery']['cost']; + } + else{ + $deliverySumm = $newOrder->getDeliveryPrice(); + } + + $orderSumm += $deliverySumm; + + $newOrder->setField('PRICE', $orderSumm); + $order['summ'] = $orderSumm; + $newOrder->save(); + + //payment + if(array_key_exists('paymentType', $order)){ + self::paySystemUpdate($order, $optionsPayTypes); + } + + //delivery + if(array_key_exists('code', $order['delivery'])/* || array_key_exists('service', $order['delivery'])*/){ + //если пусто, удаляем, если нет, update или add + if(!isset($orderCrm)){ + try { + $orderCrm = $api->ordersGet($order['id'], 'id'); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersGet2::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + } + } + self::shipmentUpdate($orderCrm['order'], $optionsDelivTypes); + } + if(isset($orderCrm)){ + unset($orderCrm); + } + + //delivery cost + if(array_key_exists('cost', $order['delivery'])){//сделать такую же для оплаты при изменении суммы + $shipment = Bitrix\Sale\Shipment::getList(array( + 'filter' => array('ORDER_ID' => $order['externalId'], 'SYSTEM' => 'N'), + 'order' => array('ID') + ))->fetch(); + if($shipment){ + Bitrix\Sale\Internals\ShipmentTable::update($shipment['ID'], array('BASE_PRICE_DELIVERY' => $order['delivery']['cost'], 'PRICE_DELIVERY' => $order['delivery']['cost'], 'CUSTOM_PRICE_DELIVERY' => 'Y')); + } + + Bitrix\Sale\OrderTable::update($order['externalId'], array('PRICE_DELIVERY' => $order['delivery']['cost']));//не пишется в историю, надо добавить + } + + Bitrix\Sale\OrderTable::update($order['externalId'], array('MARKED' => 'N', 'EMP_MARKED_ID' => '', 'REASON_MARKED' => '')); + + if (function_exists('retailCrmAfterOrderSave')) { + retailCrmAfterOrderSave($order); + } + } + } + + $GLOBALS['RETAIL_CRM_HISTORY'] = false; + + //запоминаем номер последнего изменения + $end = array_pop($orderH); + COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY, $end['id']); + + if($orderHistory['pagination']['totalPageCount'] == 1){ + return true; + } + //новый фильтр для истории + $historyFilter['sinceId'] = $end['id']; + } + + } + + public static function assemblyCustomer($customerHistory){ + $server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); + $fields = array(); + if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) { + $objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml'); + foreach($objects->fields->field as $object) + { + $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; + } + } + $customers = array(); + foreach ($customerHistory as $change) { + $change['customer'] = self::removeEmpty($change['customer']); + if($customers[$change['customer']['id']]){ + $customers[$change['customer']['id']] = array_merge($customers[$change['customer']['id']], $change['customer']); + } + else{ + $customers[$change['customer']['id']] = $change['customer']; + } + + if($change['customer']['contragent']['contragentType']){ + $change['customer']['contragentType'] = self::newValue($change['customer']['contragent']['contragentType']); + unset($change['customer']['contragent']); + } + + if($fields['customer'][$change['field']] == 'phones'){ + $key = count($customers[$change['customer']['id']]['phones']); + if(isset($change['oldValue'])){ + $customers[$change['customer']['id']]['phones'][$key]['old_number'] = $change['oldValue']; + } + if(isset($change['newValue'])){ + $customers[$change['customer']['id']]['phones'][$key]['number'] = $change['newValue']; + } + } + else{ + if($fields['customerAddress'][$change['field']]){ + $customers[$change['customer']['id']]['address'][$fields['customerAddress'][$change['field']]] = $change['newValue']; + } + elseif($fields['customerContragent'][$change['field']]){ + $customers[$change['customer']['id']]['contragent'][$fields['customerContragent'][$change['field']]] = $change['newValue']; + } + elseif($fields['customer'][$change['field']]){ + $customers[$change['customer']['id']][$fields['customer'][$change['field']]] = self::newValue($change['newValue']); + } + + if(isset($change['created'])){ + $customers[$change['customer']['id']]['create'] = 1; + } + + if(isset($change['deleted'])){ + $customers[$change['customer']['id']]['deleted'] = 1; + } + } + } + return $customers; + } + + public static function assemblyOrder($orderHistory){ + $server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); + if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) { + $objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml'); + foreach($objects->fields->field as $object) + { + $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; + } + } + $orders = array(); + foreach ($orderHistory as $change) { + $change['order'] = self::removeEmpty($change['order']); + if($change['order']['items']){ + $items = array(); + foreach($change['order']['items'] as $item){ + if(isset($change['created'])){ + $item['create'] = 1; + } + $items[$item['id']] = $item; + } + $change['order']['items'] = $items; + } + + if($change['order']['contragent']['contragentType']){ + $change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']); + unset($change['order']['contragent']); + } + + if($orders[$change['order']['id']]){ + $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']); + } + else{ + $orders[$change['order']['id']] = $change['order']; + } + + if($change['item']){ + if($orders[$change['order']['id']]['items'][$change['item']['id']]){ + $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']); + } + else{ + $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; + } + + if(empty($change['oldValue']) && $change['field'] == 'order_product'){ + $orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1; + unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']); + } + if(empty($change['newValue']) && $change['field'] == 'order_product'){ + $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1; + } + if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]){ + $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; + } + } + else{ + if($fields['delivery'][$change['field']] == 'service'){ + $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); + } + elseif($fields['delivery'][$change['field']]){ + $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']); + } + elseif($fields['orderAddress'][$change['field']]){ + $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; + } + elseif($fields['integrationDelivery'][$change['field']]){ + $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']); + } + elseif($fields['customerContragent'][$change['field']]){ + $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); + } + elseif(strripos($change['field'], 'custom_') !== false){ + $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); + } + elseif($fields['order'][$change['field']]){ + $orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']); + } + + if(isset($change['created'])){ + $orders[$change['order']['id']]['create'] = 1; + } + + if(isset($change['deleted'])){ + $orders[$change['order']['id']]['deleted'] = 1; + } + } + } + return $orders; + } + + public static function shipmentUpdate($orderCrm, $optionsDelivTypes){ + if(isset($orderCrm['delivery']['code'])){ + $crmCode = $orderCrm['delivery']['code']; + + if(isset($orderCrm['delivery']['data']['deliveryType'])){ + $crmService = $orderCrm['delivery']['data']['deliveryType']; + } + elseif (isset($orderCrm['delivery']['service'])) { + $crmService = $orderCrm['delivery']['service']; + } + + //подбираем код битриксового сервиса + $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); + foreach($arDeliveryServiceAll as $arDeliveryService){ + $arDeliveryCode[$arDeliveryService['CODE']] = $arDeliveryService['ID']; + $arDeliveryID[$arDeliveryService['ID']] = $arDeliveryService; + if($arDeliveryService['ID'] == $optionsDelivTypes[$crmCode]){ + $dCode = $arDeliveryService['CODE'] . ':' . $crmService; + } + } + //будем менять доставку на этот id + if($crmService && $arDeliveryCode[$dCode]){ + $nowDelivery = $arDeliveryCode[$dCode]; + } + else{ + $nowDelivery = $optionsDelivTypes[$crmCode]; + } + + //найти текущую доставку в заказе + $cnt = Bitrix\Sale\Internals\ShipmentTable::getCount(array('ORDER_ID' => $orderCrm['externalId'])); + if($cnt > 0){//обновляем + $obDeliverys = \Bitrix\Sale\Shipment::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']), + 'order' => array('ID'))); + while($arDelivery = $obDeliverys->fetch()){ + if($arDelivery['DELIVERY_ID'] != $nowDelivery){ + \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery)); + \Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $nowDelivery, 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME'])); + } + } + } + else{//создаем + \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery)); + $shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array( + 'ORDER_ID' => $orderCrm['externalId'], + 'STATUS_ID' => 'DN', + 'CUSTOM_PRICE_DELIVERY' => 'N', + 'ALLOW_DELIVERY' => 'N', + 'DEDUCTED' => 'N', + 'RESERVED' => 'N', + 'DELIVERY_ID' => $nowDelivery, + 'DELIVERY_NAME' => $nowDelivery[$nowDelivery]['NAME'], + 'CANCELED' => 'N', + 'MARKED' => 'N', + 'SYSTEM' => 'Y', + 'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/1', + 'EXTERNAL_DELIVERY' => 'N', + 'UPDATED_1C' => 'N', + 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() + )); + $shipment = Bitrix\Sale\Internals\ShipmentTable::add(array( + 'ORDER_ID' => $orderCrm['externalId'], + 'STATUS_ID' => 'DN', + 'PRICE_DELIVERY' => 0, + 'BASE_PRICE_DELIVERY' => 0, + 'CUSTOM_PRICE_DELIVERY' => 'N', + 'ALLOW_DELIVERY' => 'N', + 'DEDUCTED' => 'N', + 'RESERVED' => 'N', + 'DELIVERY_ID' => $nowDelivery, + 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME'], + 'CANCELED' => 'N', + 'MARKED' => 'N', + 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), + 'SYSTEM' => 'N', + 'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/2', + 'EXTERNAL_DELIVERY' => 'N', + 'UPDATED_1C' => 'N', + 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() + )); + } + } + else{ + //ищем у заказа на сайте доставки и удаляем/заменяем на без доставки + $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); + \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $noOrderId)); + $obDeliverys = Bitrix\Sale\Shipment::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']), + 'order' => array('ID'))); + $create = true; + while($arDelivery = $obDeliverys->fetch()){ + \Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $noOrderId, 'DELIVERY_NAME' => 'Без доставки')); + $create = false; + } + if($create){ + $shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array( + 'ORDER_ID' => $orderCrm['externalId'], + 'STATUS_ID' => 'DN', + 'CUSTOM_PRICE_DELIVERY' => 'N', + 'ALLOW_DELIVERY' => 'N', + 'DEDUCTED' => 'N', + 'RESERVED' => 'N', + 'DELIVERY_ID' => $nowDelivery, + 'DELIVERY_NAME' => $nowDelivery[$nowDelivery]['NAME'], + 'CANCELED' => 'N', + 'MARKED' => 'N', + 'SYSTEM' => 'Y', + 'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/1', + 'EXTERNAL_DELIVERY' => 'N', + 'UPDATED_1C' => 'N', + 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() + )); + $shipment = Bitrix\Sale\Internals\ShipmentTable::add(array( + 'ORDER_ID' => $orderCrm['externalId'], + 'STATUS_ID' => 'DN', + 'PRICE_DELIVERY' => 0, + 'BASE_PRICE_DELIVERY' => 0, + 'CUSTOM_PRICE_DELIVERY' => 'N', + 'ALLOW_DELIVERY' => 'N', + 'DEDUCTED' => 'N', + 'RESERVED' => 'N', + 'DELIVERY_ID' => $nowDelivery, + 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME'], + 'CANCELED' => 'N', + 'MARKED' => 'N', + 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), + 'SYSTEM' => 'N', + 'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/2', + 'EXTERNAL_DELIVERY' => 'N', + 'UPDATED_1C' => 'N', + 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() + )); + } + } + + return true; + } + + public static function paySystemUpdate($order, $optionsPayment){ + if(isset($order['paymentType'])){ + if($optionsPayment[$order['paymentType']]){ + $paymentList = RCrmActions::PaymentList(); + $arPayments = array(); + $arPaymentsName = array(); + foreach($paymentList as $payment){ + $arPayments[] = $payment['ID']; + $arPaymentsName[$payment['ID']] = $payment['NAME']; + } + + if(in_array($optionsPayment[$order['paymentType']], $arPayments)){ + \Bitrix\Sale\OrderTable::update($order['externalId'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']])); + $payment = \Bitrix\Sale\Payment::getList(array( + 'filter' => array('ORDER_ID' => $order['externalId']), + 'order' => array('ID') + ))->fetch(); + if($payment){ + //если уже существует, update + \Bitrix\Sale\Internals\PaymentTable::update($payment['ID'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']], 'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]], 'SUM' => $order['summ'])); + } + else{ + \Bitrix\Sale\Internals\PaymentTable::add(array( + 'ORDER_ID' => $order['externalId'], + 'PAID' => 'N', + 'PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']], + 'SUM' => $order['summ'], + 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), + 'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]], + 'IS_RETURN' => 'N', + 'ACCOUNT_NUMBER' => $order['externalId'] . '/1', + 'PRICE_COD' => '0.00', + 'EXTERNAL_PAYMENT' => 'N', + 'UPDATED_1C' => 'N' + )); + } + //запись в историю + } + else{ + //ошибка, нет такой активной платежной системы + RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found'); + } + } + else{ + //ошибка, возможно платежная система не сопоставлена + RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in option');; + } + } + else{ + \Bitrix\Sale\OrderTable::update($order['externalId'], array('PAY_SYSTEM_ID' => '')); + $payment = \Bitrix\Sale\Payment::getList(array( + 'filter' => array('ORDER_ID' => $order['externalId']), + 'order' => array('ID') + ))->fetch(); + + if($payment['ID']){ + \Bitrix\Sale\Internals\PaymentTable::delete($payment['ID']); + } + //запись в историю + } + } + + public static function newValue($value){ + if(isset($value['code'])){ + return $value['code']; + } + else{ + return $value; + } + } + + public static function removeEmpty($inputArray){ + $outputArray = array(); + if (!empty($inputArray)){ + foreach ($inputArray as $key => $element){ + if(!empty($element) || $element === 0 || $element === '0'){ + if (is_array($element)){ + $element = self::removeEmpty($element); + } + $outputArray[$key] = $element; + } + } + } + + return $outputArray; + } + + public static function setProp($obj, $value, $prop){ + if($prop && $value){ + $obj->setField($prop, $value); + } + elseif($value){ + $obj->setValue($value); + } + else{ + $obj->delete(); + } + + return true; + } + + public static function getExistsItem($basket, $moduleId, $productId){ + foreach ($basket as $basketItem) + { + $itemExists = ($basketItem->getField('PRODUCT_ID') == $productId && $basketItem->getField('MODULE') == $moduleId); + + if ($itemExists) + { + return $basketItem; + } + } + + return false; + } + + public static function getUrl($offerId){ + $parent = CCatalogSku::GetProductInfo($offerId); + if($parent){ + $element = $parent['ID']; + } + else{ + $element = $offerId; + } + $elementInfo = \Bitrix\Iblock\ElementTable::getById($element)->fetch(); + + $iblockInfo = \Bitrix\Iblock\IblockTable::getById($elementInfo['IBLOCK_ID'])->fetch(); + $url = $iblockInfo['DETAIL_PAGE_URL']; + if(substr_count($url, '#SITE_DIR#')>0){ + $url = str_replace('#SITE_DIR#', '', $url); + } + if(substr_count($url, '#SECTION_CODE#')>0){ + $value = \Bitrix\Iblock\SectionTable::getById($elementInfo['IBLOCK_SECTION_ID'])->fetch(); + $url = str_replace('#SECTION_CODE#', $value['CODE'], $url); + } + if(substr_count($url, '#SECTION_ID#')>0){ + $value = $elementInfo['IBLOCK_SECTION_ID']; + $url = str_replace('#SECTION_ID#', $value, $url); + } + if(substr_count($url, '#ELEMENT_CODE#')>0){ + $value = $elementInfo['CODE']; + $url = str_replace('#ELEMENT_CODE#', $value, $url); + } + elseif(substr_count($url, '#CODE#')>0){ + $value = $elementInfo['CODE']; + $url = str_replace('#CODE#', $value, $url); + } + if(substr_count($url, '#ELEMENT_ID#')>0){ + $value = $elementInfo['ID']; + $url = str_replace('#ELEMENT_ID#', $value, $url); + } + elseif(substr_count($url, '#ID#')>0){ + $value = $elementInfo['ID']; + $url = str_replace('#ID#', $value, $url); + } + + return $url; + } +} + +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 + ); + $id = $retailUser->Add($arFields); + if (!$id) { + return null; + } else { + return $id; + } + } + } +} \ No newline at end of file diff --git a/intaro.retailcrm/classes/general/icml/RetailCrmICML.php b/intaro.retailcrm/classes/general/icml/RetailCrmICML.php new file mode 100644 index 00000000..4f069d3e --- /dev/null +++ b/intaro.retailcrm/classes/general/icml/RetailCrmICML.php @@ -0,0 +1,561 @@ + 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('DEF' => 'Y'))->Fetch(); + $this->encodingDefault = $defaultSite["CHARSET"]; + + $url = 'https://' . $this->serverName; + $curlHandler = curl_init(); + curl_setopt($curlHandler, CURLOPT_URL, $url); + $responseBody = curl_exec($curlHandler); + $statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); + curl_close($curlHandler); + if($statusCode == 200){ + $this->protocol = 'https://'; + } + else{ + $this->protocol = 'http://'; + } + + $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($defaultSite['ABS_DOC_ROOT'] . $this->filename); + rename($defaultSite['ABS_DOC_ROOT'] . $this->filename. '.tmp', $defaultSite['ABS_DOC_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 + ); + + 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", + "NAME", + "DETAIL_PICTURE", + "PREVIEW_PICTURE", + "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_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 + ); + $order = array("id"); + $arNavStatParams = Array( + "iNumPage" => 1, + "nPageSize" => $this->pageSize, + ); + + // Cycle page to page + do { + // Get products on this page + $elems = array(); + $dbResProductsIds = CIBlockElement::GetList($order, $filter, false, $arNavStatParams, array('ID')); + while($obIds = $dbResProductsIds->Fetch()) + { + $elems[] = $obIds['ID']; + } + $arfilter = array( + "IBLOCK_ID" => $id, + "ID" => $elems + ); + + $dbResProducts = CIBlockElement::GetList($order, $arfilter, false, false, $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']; + } + } + unset($product); + unset($detailPicture, $previewPicture, $picture); + + $pictureIDs = array_keys($pictures); + + // 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'] = $this->protocol . + $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; + } + unset($offer, $dbResOffers); + } + + $stringOffers = ""; + foreach ($products as $product) { + + // 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) { + $catId = $this->mainSection + $id; + $categories[$catId] = $allCategories[$catId]; + } + + + $existOffer = false; + if (!empty($iblockOffer['IBLOCK_ID'])) { + + 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'] = $offer["ACTIVE"]; + $offer['PRICE'] = $offer['CATALOG_PRICE_' . $basePriceId]; + $offer['PURCHASE_PRICE'] = $offer['CATALOG_PURCHASING_PRICE']; + $offer['QUANTITY'] = $offer["CATALOG_QUANTITY"]; + + // Get properties of product + foreach ($this->propertiesSKU[$id] as $key => $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 (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] != "" || $this->propertiesProduct[$id][str_replace("_UNIT", "", $key)] != "") { + $product['_PROP_' . $key] = $propProduct; + } + } + + $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'] = $dbResProductsIds->NavPageNomer + 1; + } + while ($dbResProductsIds->NavPageNomer < $dbResProductsIds->NavPageCount); + } + } + + 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; + } + } + + } + $arOffer['DETAIL_PAGE_URL'] = str_replace("#SECTION_PATH#", $path, $arOffer['DETAIL_PAGE_URL']); + } + + $offer .= "" . $this->PrepareValue($arOffer["PICTURE"]) . "\n"; + $offer .= "" . $this->protocol . $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"; + } + } + } + + $offer.= "\n"; + return $offer; + } +} \ No newline at end of file diff --git a/intaro.retailcrm/classes/general/order/RetailCrmOrder.php b/intaro.retailcrm/classes/general/order/RetailCrmOrder.php new file mode 100644 index 00000000..81ebc971 --- /dev/null +++ b/intaro.retailcrm/classes/general/order/RetailCrmOrder.php @@ -0,0 +1,328 @@ + $customer) + */ + public static function orderSend($arFields, $api, $arParams, $send = false, $site = null, $methodApi = 'ordersEdit') { + if(!$api || empty($arParams)) { // add cond to check $arParams + return false; + } + if (empty($arFields)) { + RCrmActions::eventLog('RetailCrmOrder::orderSend', 'empty($arFields)', 'incorrect order'); + return false; + } + + $order = array( + 'number' => $arFields['NUMBER'], + 'externalId' => $arFields['ID'], + 'createdAt' => new \DateTime($arFields['DATE_INSERT']), + 'customer' => array('externalId' => $arFields['USER_ID']), + 'paymentType' => isset($arParams['optionsPayTypes'][$arFields['PAYMENTS'][0]]) ? + $arParams['optionsPayTypes'][$arFields['PAYMENTS'][0]] : '', + 'paymentStatus' => isset($arParams['optionsPayment'][$arFields['PAYED']]) ? + $arParams['optionsPayment'][$arFields['PAYED']] : '', + 'orderType' => isset($arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']]) ? + $arParams['optionsOrderTypes'][$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'] + ), + ); + if(isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != ''){ + $order['customer']['browserId'] = $_COOKIE['_rc']; + } + $order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']]; + + //свойства + foreach($arFields['PROPS']['properties'] as $prop){ + if ($search = array_search($prop['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) { + $order['contragent'][$search] = $prop['VALUE'][0];//юр данные заказа + } elseif ($search = array_search($prop['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) { + $order['customFields'][$search] = $prop['VALUE'][0];//кастомные свойства + } elseif ($search = array_search($prop['CODE'], $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']])) {//остальное + if (in_array($search, array('fio', 'phone', 'email'))) {//фио, телефон, почта + if ($search == 'fio') { + $order = array_merge($order, RCrmActions::explodeFIO($prop['VALUE'][0]));//добавляем поля фио + } else { + $order[$search] = $prop['VALUE'][0];//телефон и почта + } + } else {//остальное - адрес + if ($prop['TYPE'] == 'LOCATION') { + $arLoc = \Bitrix\Sale\Location\LocationTable::getByCode($prop['VALUE'][0])->fetch(); + $location = \Bitrix\Sale\Location\Name\LocationTable::getList(array( + 'filter' => array('=LOCATION_ID' => $arLoc['CITY_ID'], 'LANGUAGE_ID'=>'ru') + ))->fetch(); + + $prop['VALUE'][0] = $location['NAME']; + } + + $order['delivery']['address'][$search] = $prop['VALUE'][0]; + } + } + } + + //доставки + if (array_key_exists($arFields['DELIVERYS'][0]['id'], $arParams['optionsDelivTypes'])) { + $order['delivery']['code'] = $arParams['optionsDelivTypes'][$arFields['DELIVERYS'][0]['id']]; + if (isset($arFields['DELIVERYS'][0]['service'])) { + $order['delivery']['service'] = $arFields['DELIVERYS'][0]['service']; + } + } + + //корзина + foreach($arFields['BASKET'] as $product){ + $item = array( + 'quantity' => $product['QUANTITY'], + 'offer' => array('externalId' => $product['PRODUCT_ID'], + 'xmlId' => $product['PRODUCT_XML_ID'] + ), + 'productName' => $product['NAME'] + ); + + $pp = CCatalogProduct::GetByID($product['PRODUCT_ID']); + if (is_null($pp['PURCHASING_PRICE']) == false) { + $item['purchasePrice'] = $pp['PURCHASING_PRICE']; + } + $item['discount'] = (double) $product['DISCOUNT_PRICE']; + $item['discountPercent'] = 0; + $item['initialPrice'] = (double) $product['PRICE'] + (double) $product['DISCOUNT_PRICE']; + + $order['items'][] = $item; + } + + //отправка + if (function_exists('retailCrmBeforeOrderSend')) { + $newResOrder = retailCrmBeforeOrderSend($order); + if (is_array($newResOrder) && !empty($newResOrder)) { + $order = $newResOrder; + } + } + + $normalizer = new RestNormalizer(); + $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']]; + } + + $log = new Logger(); + $log->write($order, 'order'); + + if($send) { + if (!RCrmActions::apiMethod($api, $methodApi, __METHOD__, $order, $site)) { + return false; + } + } + + return $order; + } + + /** + * Mass order uploading, without repeating; always returns true, but writes error log + * @param $pSize + * @param $failed -- flag to export failed orders + * @return boolean + */ + public static function uploadOrders($pSize = 50, $failed = false, $orderList = false) { + if (!CModule::IncludeModule("iblock")) { + RCrmActions::eventLog('RetailCrmOrder::uploadOrders', 'iblock', 'module not found'); + return true; + } + if (!CModule::IncludeModule("sale")) { + RCrmActions::eventLog('RetailCrmOrder::uploadOrders', 'sale', 'module not found'); + return true; + } + if (!CModule::IncludeModule("catalog")) { + RCrmActions::eventLog('RetailCrmOrder::uploadOrders', 'catalog', 'module not found'); + return true; + } + + $resOrders = array(); + $resCustomers = array(); + $orderIds = array(); + + $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)); + + if ($failed == true && $failedIds !== false && count($failedIds) > 0) { + $orderIds = $failedIds; + } elseif ($orderList !== false && count($orderList) > 0) { + $orderIds = $orderList; + } else { + $dbOrder = \Bitrix\Sale\Order::GetList(array( + 'order' => array("ID" => "ASC"), + 'filter' => array('>ID' => $lastUpOrderId), + 'limit' => $pSize, + 'select' => array('ID') + )); + while($arOrder = $dbOrder->fetch()){ + $orderIds[] = $arOrder['ID']; + } + } + + if (count($orderIds)<=0) { + 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\ApiClient($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(); + foreach($orderIds as $orderId){ + $id = \Bitrix\Sale\Order::load($orderId); + if(!$id){ + continue; + } + $order = self::orderObjToArr($id); + $user = Bitrix\Main\UserTable::getById($order['USER_ID'])->fetch(); + + $site = count($optionsSitesList) > 1 ? $optionsSitesList[$order['LID']] : null; + + $arCustomers = RetailCrmUser::customerSend($user, $api, $optionsContragentType[$order['PERSON_TYPE_ID']], false, $site); + $arOrders = self::orderSend($order, $api, $arParams, false, $site); + + if (!$arCustomers || !$arOrders){ + continue; + } + + $resCustomers[$order['LID']][] = $arCustomers; + $resOrders[$order['LID']][] = $arOrders; + + $recOrders[] = $orderId; + } + + if(count($resOrders) > 0){ + foreach($resCustomers as $key => $customerLoad){ + $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; + if (RCrmActions::apiMethod($api, 'customersUpload', __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 (RCrmActions::apiMethod($api, 'ordersUpload', __METHOD__, $orderLoad, $site) === false) { + return false; + } + if (count($optionsSitesList) > 1) { + time_nanosleep(0, 250000000); + } + } + 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)); + } + } + + return true; + } + + public static function orderObjToArr($obOrder){ + $arOrder = array( + 'ID' => $obOrder->getId(), + 'NUMBER' => $obOrder->getField('ACCOUNT_NUMBER'), + 'LID' => $obOrder->getSiteId(), + 'DATE_INSERT' => $obOrder->getDateInsert(), + 'STATUS_ID' => $obOrder->getField('STATUS_ID'), + 'USER_ID' => $obOrder->getUserId(), + 'PERSON_TYPE_ID' => $obOrder->getPersonTypeId(), + 'CURRENCY' => $obOrder->getCurrency(), + 'PAYMENTS' => $obOrder->getPaymentSystemId(), + 'PAYED' => $obOrder->isPaid(), + 'DELIVERYS' => array(), + 'PRICE_DELIVERY' => $obOrder->getDeliveryPrice(), + 'PROPS' => $obOrder->getPropertyCollection()->getArray(), + 'DISCOUNTS' => $obOrder->getDiscount()->getApplyResult(), + 'BASKET' => array(), + 'USER_DESCRIPTION' => $obOrder->getField('USER_DESCRIPTION'), + 'COMMENTS' => $obOrder->getField('COMMENTS'), + ); + + $shipmentList = $obOrder->getShipmentCollection(); + foreach($shipmentList as $shipmentData){ + if($shipmentData->getDeliveryId()){ + $delivery = \Bitrix\Sale\Delivery\Services\Manager::getById($shipmentData->getDeliveryId()); + if($delivery['PARENT_ID']){ + $servise = explode(':', $delivery['CODE']); + $shipment = array('id' => $delivery['PARENT_ID'], 'service' => $servise[1]); + } + else{ + $shipment = array('id' => $delivery['ID']); + } + $arOrder['DELIVERYS'][] = $shipment; + } + } + + $basketItems = $obOrder->getBasket(); + foreach($basketItems as $item){ + $arOrder['BASKET'][] = $item->getFields(); + } + + return $arOrder; + } +} diff --git a/intaro.retailcrm/classes/general/user/RetailCrmUser.php b/intaro.retailcrm/classes/general/user/RetailCrmUser.php new file mode 100644 index 00000000..73c7da9b --- /dev/null +++ b/intaro.retailcrm/classes/general/user/RetailCrmUser.php @@ -0,0 +1,54 @@ + $arFields['ID'], + 'firstName' => $arFields['NAME'], + 'lastName' => $arFields['LAST_NAME'], + 'patronymic' => $arFields['SECOND_NAME'], + 'createdAt' => new \DateTime($arFields['DATE_REGISTER']), + 'contragentType' => $contragentType + ); + if(isset($arFields['PERSONAL_PHONE'])){ + $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; + } + if(isset($arUser['WORK_PHONE'])){ + $customer['phones'][]['number'] = $arFields['WORK_PHONE']; + } + if(isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != ''){ + $customer['browserId'] = $_COOKIE['_rc']; + } + + if (function_exists('retailCrmBeforeCustomerSend')) { + $newResCustomer = retailCrmBeforeCustomerSend($customer); + if (is_array($newResCustomer) && !empty($newResCustomer)) { + $customer = $newResCustomer; + } + } + + $normalizer = new RestNormalizer(); + $customer = $normalizer->normalize($customer, 'customers'); + + $log = new Logger(); + $log->write($customer, 'customer'); + + if($send) { + if (!RCrmActions::apiMethod($api, 'customersCreate', __METHOD__, $customer, $site)) { + return false; + } + } + + return $customer; + } + +} \ No newline at end of file diff --git a/intaro.retailcrm/description.ru b/intaro.retailcrm/description.ru new file mode 100644 index 00000000..678e0109 --- /dev/null +++ b/intaro.retailcrm/description.ru @@ -0,0 +1,2 @@ +- Переход на новое API Битрикса +- Переход на API црм v4 \ No newline at end of file diff --git a/intaro.intarocrm/export/export_run.php b/intaro.retailcrm/export/export_run.php similarity index 93% rename from intaro.intarocrm/export/export_run.php rename to intaro.retailcrm/export/export_run.php index d1f17c90..d1e3b3e8 100644 --- a/intaro.intarocrm/export/export_run.php +++ b/intaro.retailcrm/export/export_run.php @@ -11,13 +11,13 @@ else{ return; if (!CModule::IncludeModule("catalog")) return; - if (!CModule::IncludeModule("intaro.intarocrm")) + if (!CModule::IncludeModule("intaro.retailcrm")) return; $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); while ($ar = $rsSites->Fetch()){ if($ar['DEF'] == 'Y'){ - $SERVER_NAME = $ar['SERVER_NAME'];//разделить потом с учетом многосайтовости + $SERVER_NAME = $ar['SERVER_NAME']; } } @@ -72,7 +72,7 @@ else{ } } - $loader = new ICMLLoader(); + $loader = new RetailCrmICML(); $loader->profileID = $PROFILE_ID; $loader->iblocks = $IBLOCK_EXPORT; $loader->propertiesSKU = $IBLOCK_PROPERTY_SKU; diff --git a/intaro.intarocrm/export/export_setup.php b/intaro.retailcrm/export/export_setup.php similarity index 99% rename from intaro.intarocrm/export/export_setup.php rename to intaro.retailcrm/export/export_setup.php index bc74d92b..54187f3b 100644 --- a/intaro.intarocrm/export/export_setup.php +++ b/intaro.retailcrm/export/export_setup.php @@ -16,9 +16,9 @@ else{ if(!check_bitrix_sessid()) return; - __IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.intarocrm/lang/", "/icml_export_setup.php")); + __IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.retailcrm/lang/", "/icml_export_setup.php")); - $MODULE_ID = 'intaro.intarocrm'; + $MODULE_ID = 'intaro.retailcrm'; $CRM_CATALOG_BASE_PRICE = 'catalog_base_price'; $basePriceId = COption::GetOptionString($MODULE_ID, $CRM_CATALOG_BASE_PRICE . '_' . $_REQUEST['PROFILE_ID'], 1); @@ -554,7 +554,7 @@ else{ 'catalog', 'export_default_path', '/bitrix/catalog_export/')) - .'intarocrm'/* .mt_rand(0, 999999) */.'.xml' + .'retailcrm'/* .mt_rand(0, 999999) */.'.xml' ); ?>" size="50">

diff --git a/intaro.retailcrm/include.php b/intaro.retailcrm/include.php new file mode 100644 index 00000000..af464738 --- /dev/null +++ b/intaro.retailcrm/include.php @@ -0,0 +1,21 @@ +getServer()->getDocumentRoot(); + +CModule::AddAutoloadClasses( + 'intaro.retailcrm', // module name + array ( + 'RestNormalizer' => file_exists($server . '/bitrix/php_interface/retailcrm/RestNormalizer.php') ? $server . '/bitrix/php_interface/retailcrm/RestNormalizer.php' : 'classes/general/RestNormalizer.php', + 'Logger' => file_exists($server . '/bitrix/php_interface/retailcrm/Logger.php') ? $server . '/bitrix/php_interface/retailcrm/Logger.php' : 'classes/general/Logger.php', + 'RetailCrm\ApiClient' => file_exists($server . '/bitrix/php_interface/retailcrm/ApiClient.php') ? $server . '/bitrix/php_interface/retailcrm/ApiClient.php' : 'classes/general/ApiClient.php', + 'RetailCrm\Http\Client' => file_exists($server . '/bitrix/php_interface/retailcrm/Client.php') ? $server . '/bitrix/php_interface/retailcrm/Client.php' : 'classes/general/Http/Client.php', + 'RCrmActions' => file_exists($server . '/bitrix/php_interface/retailcrm/RCrmActions.php') ? $server . '/bitrix/php_interface/retailcrm/RCrmActions.php' : 'classes/general/RCrmActions.php', + 'RetailCrmUser' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmUser.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmUser.php' : 'classes/general/user/RetailCrmUser.php', + 'RetailCrmOrder' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmOrder.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmOrder.php' : 'classes/general/order/RetailCrmOrder.php', + 'RetailCrmHistory' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmHistory.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmHistory.php' : 'classes/general/history/RetailCrmHistory.php', + 'RetailCrmICML' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmICML.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmICML.php' : 'classes/general/icml/RetailCrmICML.php', + 'RetailCrmEvent' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmEvent.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmEvent.php' : 'classes/general/events/RetailCrmEvent.php', + 'RetailCrm\Response\ApiResponse' => 'classes/general/Response/ApiResponse.php', + 'RetailCrm\Exception\InvalidJsonException' => 'classes/general/Exception/InvalidJsonException.php', + 'RetailCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php', + ) +); \ No newline at end of file diff --git a/intaro.retailcrm/install/export/retailcrm_run.php b/intaro.retailcrm/install/export/retailcrm_run.php new file mode 100644 index 00000000..fed5b8f0 --- /dev/null +++ b/intaro.retailcrm/install/export/retailcrm_run.php @@ -0,0 +1,3 @@ +retailCRM +require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.retailcrm/export/export_run.php"); \ No newline at end of file diff --git a/intaro.retailcrm/install/export/retailcrm_setup.php b/intaro.retailcrm/install/export/retailcrm_setup.php new file mode 100644 index 00000000..2158098e --- /dev/null +++ b/intaro.retailcrm/install/export/retailcrm_setup.php @@ -0,0 +1,3 @@ +retailCRM +require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.retailcrm/export/export_setup.php"); \ No newline at end of file diff --git a/intaro.intarocrm/install/index.php b/intaro.retailcrm/install/index.php similarity index 62% rename from intaro.intarocrm/install/index.php rename to intaro.retailcrm/install/index.php index 47d3be15..35c42cc4 100644 --- a/intaro.intarocrm/install/index.php +++ b/intaro.retailcrm/install/index.php @@ -2,26 +2,29 @@ /** * Module Install/Uninstall script - * Module name: intaro.intarocrm - * Class name: intaro_intarocrm + * Module name: intaro.retailcrm + * Class name: intaro_retailcrm */ global $MESS; IncludeModuleLangFile(__FILE__); -if (class_exists('intaro_intarocrm')) +if (class_exists('intaro_retailcrm')) return; -class intaro_intarocrm extends CModule { +class intaro_retailcrm extends CModule { - var $MODULE_ID = 'intaro.intarocrm'; + var $MODULE_ID = 'intaro.retailcrm'; + var $OLD_MODULE_ID = 'intaro.intarocrm'; var $MODULE_VERSION; var $MODULE_VERSION_DATE; var $MODULE_NAME; var $MODULE_DESCRIPTION; var $MODULE_GROUP_RIGHTS = 'N'; + var $PARTNER_NAME; var $PARTNER_URI; - var $INTARO_CRM_API; - var $INTARO_CRM_EXPORT = 'intarocrm'; + + var $RETAIL_CRM_API; + var $RETAIL_CRM_EXPORT = 'retailcrm'; var $CRM_API_HOST_OPTION = 'api_host'; var $CRM_API_KEY_OPTION = 'api_key'; var $CRM_SITES_LIST= 'sites_list'; @@ -38,12 +41,15 @@ class intaro_intarocrm extends CModule { var $CRM_CONTRAGENT_TYPE = 'contragent_type'; var $CRM_ORDER_DISCHARGE = 'order_discharge'; var $CRM_ORDER_FAILED_IDS = 'order_failed_ids'; - var $CRM_ORDER_HISTORY_DATE = 'order_history_date'; + var $CRM_ORDER_HISTORY = 'order_history'; + var $CRM_CUSTOMER_HISTORY = 'customer_history'; var $CRM_CATALOG_BASE_PRICE = 'catalog_base_price'; var $CRM_CATALOG_IBLOCKS = 'catalog_base_iblocks'; + var $CRM_ORDER_NUMBERS = 'order_numbers'; + var $CRM_CANSEL_ORDER = 'cansel_order'; var $INSTALL_PATH; - function intaro_intarocrm() { + function intaro_retailcrm() { $arModuleVersion = array(); $path = str_replace("\\", "/", __FILE__); $path = substr($path, 0, strlen($path) - strlen("/index.php")); @@ -51,7 +57,7 @@ class intaro_intarocrm extends CModule { include($path . "/version.php"); $this->MODULE_VERSION = $arModuleVersion["VERSION"]; $this->MODULE_VERSION_DATE = $arModuleVersion["VERSION_DATE"]; - $this->MODULE_NAME = GetMessage('INTARO_MODULE_NAME'); + $this->MODULE_NAME = GetMessage('RETAIL_MODULE_NAME'); $this->MODULE_DESCRIPTION = GetMessage('MODULE_DESCRIPTION'); $this->PARTNER_NAME = GetMessage('MODULE_PARTNER_NAME'); $this->PARTNER_URI = GetMessage('MODULE_PARTNER_URI'); @@ -65,7 +71,13 @@ class intaro_intarocrm extends CModule { global $APPLICATION, $step, $arResult; if (!in_array('curl', get_loaded_extensions())) { - $APPLICATION->ThrowException(GetMessage("INTAROCRM_CURL_ERR")); + $APPLICATION->ThrowException(GetMessage("RETAILCRM_CURL_ERR")); + return false; + } + + $infoSale = CModule::CreateModuleObject('sale')->MODULE_VERSION; + if (version_compare($infoSale, '16', '<=')) { + $APPLICATION->ThrowException(GetMessage("SALE_VERSION_ERR")); return false; } @@ -76,19 +88,30 @@ class intaro_intarocrm extends CModule { } } - include($this->INSTALL_PATH . '/../classes/general/RestApi.php'); + include($this->INSTALL_PATH . '/../classes/general/ApiClient.php'); + include($this->INSTALL_PATH . '/../classes/general/Http/Client.php'); include($this->INSTALL_PATH . '/../classes/general/Response/ApiResponse.php'); +<<<<<<< HEAD:intaro.intarocrm/install/index.php include($this->INSTALL_PATH . '/../classes/general/ICrmOrderActions.php'); include($this->INSTALL_PATH . '/../classes/general/ICMLLoader.php'); include($this->INSTALL_PATH . '/../classes/general/Logger.php'); +======= + include($this->INSTALL_PATH . '/../classes/general/RCrmActions.php'); + include($this->INSTALL_PATH . '/../classes/general/user/RetailCrmUser.php'); + include($this->INSTALL_PATH . '/../classes/general/order/RetailCrmOrder.php'); + include($this->INSTALL_PATH . '/../classes/general/history/RetailCrmHistory.php'); + include($this->INSTALL_PATH . '/../classes/general/events/RetailCrmEvent.php'); + include($this->INSTALL_PATH . '/../classes/general/icml/RetailCrmICML.php'); +>>>>>>> upstream/master:intaro.retailcrm/install/index.php include($this->INSTALL_PATH . '/../classes/general/Exception/InvalidJsonException.php'); include($this->INSTALL_PATH . '/../classes/general/Exception/CurlException.php'); include($this->INSTALL_PATH . '/../classes/general/RestNormalizer.php'); + include($this->INSTALL_PATH . '/../classes/general/Logger.php'); $step = intval($_REQUEST['step']); - if (file_exists($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.intarocrm/classes/general/config/options.xml')) { - $options = simplexml_load_file($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.intarocrm/classes/general/config/options.xml'); + if (file_exists($this->INSTALL_PATH . '/../classes/general/config/options.xml')) { + $options = simplexml_load_file($this->INSTALL_PATH . '/../classes/general/config/options.xml'); foreach($options->contragents->contragent as $contragent) { @@ -118,11 +141,7 @@ class intaro_intarocrm extends CModule { } if($step == 11){ - $arResult['arSites'] = array(); - $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); - while ($ar = $rsSites->Fetch()){ - $arResult['arSites'][] = $ar; - } + $arResult['arSites'] = RCrmActions::SitesList(); if(count($arResult['arSites'])<2){ $step = 2; } @@ -139,14 +158,16 @@ class intaro_intarocrm extends CModule { if (!CModule::IncludeModule("catalog")) { $arResult['errCode'] = 'ERR_CATALOG'; } - - $arResult['arSites'] = array(); - $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); - while ($ar = $rsSites->Fetch()) - $arResult['arSites'][] = $ar; - + + if($api_host = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_API_HOST_OPTION, 0)){ + $arResult['API_HOST'] = $api_host; + } + if($api_key = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_API_KEY_OPTION, 0)){ + $arResult['API_KEY'] = $api_key; + } + $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); } else if ($step == 11) { //new page @@ -164,9 +185,9 @@ class intaro_intarocrm extends CModule { if (isset($arResult['errCode']) && $arResult['errCode']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); + return; } @@ -181,27 +202,26 @@ class intaro_intarocrm extends CModule { if (!$api_host || !$api_key) { $arResult['errCode'] = 'ERR_FIELDS_API_HOST'; $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); + return; } - $this->INTARO_CRM_API = new RetailCrm\RestApi($api_host, $api_key); + $this->RETAIL_CRM_API = new RetailCrm\ApiClient($api_host, $api_key); //api key ok and sites list try { - $arResult['sitesList'] = $APPLICATION->ConvertCharsetArray($this->INTARO_CRM_API->sitesList()->sites, 'utf-8', SITE_CHARSET); + $arResult['sitesList'] = $APPLICATION->ConvertCharsetArray($this->RETAIL_CRM_API->sitesList()->sites, 'utf-8', SITE_CHARSET); } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::sitesList', + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::sitesList', $e->getCode() . ': ' . $e->getMessage() ); $arResult['errCode'] = 'ERR_' . $e->getCode(); $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); return; @@ -209,10 +229,13 @@ class intaro_intarocrm extends CModule { COption::SetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, $api_host); COption::SetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, $api_key); + + if($sites_list = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_SITES_LIST, 0)){ + $arResult['SITES_LIST'] = unserialize($sites_list); + } $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step11.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php' ); } else if ($step == 2) {//доставки, оплаты, типы заказов @@ -230,40 +253,25 @@ class intaro_intarocrm extends CModule { if (isset($arResult['errCode']) && $arResult['errCode']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); return; } - $arResult['arSites'] = array(); - $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); - while ($ar = $rsSites->Fetch()){ - if(!$ar["SERVER_NAME"]){ - $arResult['errCode'] = 'URL_NOT_FOUND'; - $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' - ); - return; - } - else{ - $arResult['arSites'][] = $ar; - } - } - + $arResult['arSites'] = RCrmActions::SitesList(); + /* if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) { $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); - $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key); + $this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); //prepare crm lists try { - $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList()->orderTypes; + $arResult['orderTypesList'] = $this->RETAIL_CRM_API->orderTypesList()->orderTypes; } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::orderTypesList::CurlException', + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::orderTypesList::CurlException', $e->getCode() . ': ' . $e->getMessage() ); @@ -273,26 +281,28 @@ class intaro_intarocrm extends CModule { } try { - $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList()->deliveryTypes; - $arResult['deliveryServicesList'] = $this->INTARO_CRM_API->deliveryServicesList()->deliveryServices; - $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList()->paymentTypes; - $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList()->paymentStatuses; // --statuses - $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList()->statuses; - $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList()->statusGroups; // -- statuses groups + $arResult['deliveryTypesList'] = $this->RETAIL_CRM_API->deliveryTypesList()->deliveryTypes; + $arResult['deliveryServicesList'] = $this->RETAIL_CRM_API->deliveryServicesList()->deliveryServices; + $arResult['paymentTypesList'] = $this->RETAIL_CRM_API->paymentTypesList()->paymentTypes; + $arResult['paymentStatusesList'] = $this->RETAIL_CRM_API->paymentStatusesList()->paymentStatuses; // --statuses + $arResult['paymentList'] = $this->RETAIL_CRM_API->orderStatusesList()->statuses; + $arResult['paymentGroupList'] = $this->RETAIL_CRM_API->orderStatusGroupsList()->statusGroups; // -- statuses groups } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::*List::CurlException', + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::*List::CurlException', $e->getCode() . ': ' . $e->getMessage() ); } //bitrix orderTypesList -- personTypes $dbOrderTypesList = CSalePersonType::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y", - ), false, false, array() + array( + "SORT" => "ASC", + "NAME" => "ASC" + ), + array( + "ACTIVE" => "Y", + ), + false, false, array() ); @@ -393,11 +403,11 @@ class intaro_intarocrm extends CModule { $paymentArr['Y'] = htmlspecialchars(trim($_POST['payment-Y'])); $paymentArr['N'] = htmlspecialchars(trim($_POST['payment-N'])); - COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_TYPES_ARR, serialize(ICrmOrderActions::clearArr($orderTypesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, serialize(ICrmOrderActions::clearArr($deliveryTypesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_TYPES, serialize(ICrmOrderActions::clearArr($paymentTypesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES, serialize(ICrmOrderActions::clearArr($paymentStatusesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT, serialize(ICrmOrderActions::clearArr($paymentArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_TYPES_ARR, serialize(RCrmActions::clearArr($orderTypesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, serialize(RCrmActions::clearArr($deliveryTypesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_TYPES, serialize(RCrmActions::clearArr($paymentTypesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES, serialize(RCrmActions::clearArr($paymentStatusesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT, serialize(RCrmActions::clearArr($paymentArr))); // generate updated select inputs $input = array(); @@ -529,10 +539,10 @@ class intaro_intarocrm extends CModule { $APPLICATION->RestartBuffer(); header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET); die(json_encode(array("success" => true, "result" => $input))); - } + }*/ if(count($arResult['arSites'])>1){ - // api load + $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); @@ -541,16 +551,15 @@ class intaro_intarocrm extends CModule { $siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-'.$site['LID']])); } } - if (count($arResult['arSites'])!=count($siteCode)) { + if (count($arResult['arSites']) != count($siteCode)) { $arResult['errCode'] = 'ERR_FIELDS_API_HOST'; $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step11.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php' ); return; } - $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key); + $this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); COption::SetOptionString($this->MODULE_ID, $this->CRM_SITES_LIST, serialize($siteCode)); } else{//если 1 сайт @@ -565,27 +574,25 @@ class intaro_intarocrm extends CModule { if (!$api_host || !$api_key) { $arResult['errCode'] = 'ERR_FIELDS_API_HOST'; $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); return; } - $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key); + $this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); try { - $this->INTARO_CRM_API->paymentStatusesList()->paymentStatuses; + $this->RETAIL_CRM_API->paymentStatusesList()->paymentStatuses; } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::paymentStatusesList::CurlException', + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::paymentStatusesList::CurlException', $e->getCode() . ': ' . $e->getMessage() ); $arResult['errCode'] = 'ERR_' . $e->getCode(); $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); return; @@ -596,110 +603,50 @@ class intaro_intarocrm extends CModule { //prepare crm lists try { - $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList()->orderTypes; - $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList()->deliveryTypes; - $arResult['deliveryServicesList'] = $this->INTARO_CRM_API->deliveryServicesList()->deliveryServices; - $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList()->paymentTypes; - $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList()->paymentStatuses; // --statuses - $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList()->statuses; - $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList()->statusGroups; // -- statuses groups + $arResult['orderTypesList'] = $this->RETAIL_CRM_API->orderTypesList()->orderTypes; + $arResult['deliveryTypesList'] = $this->RETAIL_CRM_API->deliveryTypesList()->deliveryTypes; + $arResult['deliveryServicesList'] = $this->RETAIL_CRM_API->deliveryServicesList()->deliveryServices; + $arResult['paymentTypesList'] = $this->RETAIL_CRM_API->paymentTypesList()->paymentTypes; + $arResult['paymentStatusesList'] = $this->RETAIL_CRM_API->paymentStatusesList()->paymentStatuses; + $arResult['paymentList'] = $this->RETAIL_CRM_API->statusesList()->statuses; + $arResult['paymentGroupList'] = $this->RETAIL_CRM_API->statusGroupsList()->statusGroups; } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::*List::CurlException', + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::*List::CurlException', $e->getCode() . ': ' . $e->getMessage() ); } - //bitrix orderTypesList -- personTypes - $dbOrderTypesList = CSalePersonType::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y", - ), false, false, array() - ); + + //bitrix personTypes + $arResult['bitrixOrderTypesList'] = RCrmActions::OrderTypesList($arResult['arSites']); + + //bitrix deliveryList + $arResult['bitrixDeliveryTypesList'] = RCrmActions::DeliveryList(); - if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { - do { - $arResult['bitrixOrderTypesList'][] = $arOrderTypesList; - } while ($arOrderTypesList = $dbOrderTypesList->Fetch()); + //bitrix paymentList + $arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList(); + + //bitrix statusesList --statuses + $arResult['bitrixStatusesList'] = RCrmActions::StatusesList(); + + if($order_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_TYPES_ARR, 0)){ + $arResult['ORDER_TYPES'] = array_flip(unserialize($order_types)); } - - //bitrix deliveryTypesList - $dbDeliveryTypesList = CSaleDelivery::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y", - ), false, false, array() - ); - - if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) { - do { - $arResult['bitrixDeliveryTypesList'][] = $arDeliveryTypesList; - } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()); + if($delivery_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, 0)){ + $arResult['DELIVERY_TYPES'] = array_flip(unserialize($delivery_types)); } - - // bitrix deliveryServicesList - $dbDeliveryServicesList = CSaleDeliveryHandler::GetList( - array( - 'SORT' => 'ASC', - 'NAME' => 'ASC' - ), - array( - 'ACTIVE' => 'Y', - 'SITE_ID' => $arResult['arSites'][0]['LID'] - ) - ); - - if ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()) { - do { - $arResult['bitrixDeliveryTypesList'][] = array('ID' => $arDeliveryServicesList['SID'], 'NAME' => $arDeliveryServicesList['NAME']); - } while ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()); + if($payment_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT_TYPES, 0)){ + $arResult['PAYMENT_TYPES'] = array_flip(unserialize($payment_types)); } - - //bitrix paymentTypesList - $dbPaymentTypesList = CSalePaySystem::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y" - ) - ); - - if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) { - do { - $arResult['bitrixPaymentTypesList'][] = $arPaymentTypesList; - } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch()); + if($payment_statuses = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT_STATUSES, 0)){ + $arResult['PAYMENT_STATUSES'] = array_flip(unserialize($payment_statuses)); } - - //bitrix paymentStatusesList --statuses - $dbPaymentStatusesList = CSaleStatus::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "LID" => "ru", //ru - "ACTIVE" => "Y" - ) - ); - - if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) { - do { - $arResult['bitrixPaymentStatusesList'][$arPaymentStatusesList['ID']] = $arPaymentStatusesList; - } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); + if($payment = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT, 0)){ + $arResult['PAYMENT'] = array_flip(unserialize($payment)); } - $arResult['bitrixPaymentStatusesList'][] = array( - 'ID' => 'YY', - 'NAME' => GetMessage('CANCELED') - ); - $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step2.php' ); } else if ($step == 3) {//сопостовление свойств заказа if (!CModule::IncludeModule("sale")) { @@ -708,192 +655,95 @@ class intaro_intarocrm extends CModule { if (isset($_POST['back']) && $_POST['back']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' ); } // api load $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); - $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key); + $this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); - //bitrix orderTypesList -- personTypes - $dbOrderTypesList = CSalePersonType::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y", - ), false, false, array() - ); - - //form order types ids arr + //bitrix orderTypesList + $arResult['arSites'] = RCrmActions::SitesList(); + $arResult['bitrixOrderTypesList'] = RCrmActions::OrderTypesList($arResult['arSites']); + $orderTypesArr = array(); - $arResult['bitrixOrderTypesList'] = array(); - if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { - do { - $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']])); - $arResult['bitrixOrderTypesList'][] = $arOrderTypesList; - } while ($arOrderTypesList = $dbOrderTypesList->Fetch()); + foreach($arResult['bitrixOrderTypesList'] as $orderType){ + $orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']])); } //bitrix deliveryTypesList - $dbDeliveryTypesList = CSaleDelivery::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y", - ), false, false, array() - ); + $arResult['bitrixDeliveryTypesList'] = RCrmActions::DeliveryList(); - //bitrix deliveryServicesList - $rsSites = CSite::GetList($by, $sort, array()); - while ($ar = $rsSites->Fetch()){ - $arResult['arSites'][] = $ar; + if (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'false') {//сами настраиваем доставки + $deliveryTypesArr = array(); + foreach($arResult['bitrixDeliveryTypesList'] as $delivery){ + $deliveryTypesArr[$delivery['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $delivery['ID']])); + } } - $dbDeliveryServicesList = CSaleDeliveryHandler::GetList( - array( - 'SORT' => 'ASC', - 'NAME' => 'ASC' - ), - array( - 'ACTIVE' => 'Y', - 'SITE_ID' => $arResult['arSites'][0]['LID'] - ) - ); - - //form delivery types / services ids arr - $deliveryTypesArr = array(); - - if (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'false') { - if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) { - do { - $deliveryTypesArr[$arDeliveryTypesList['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryTypesList['ID']])); - } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()); - } - - if ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()) { - do { - //auto delivery types - $deliveryTypesArr[$arDeliveryServicesList['SID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryServicesList['SID']])); - - } while ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()); - } - } elseif (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'true') { + elseif (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'true') {//отправка доставок в црм // send to intaro crm and save delivery types! - if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) { - do { - // parse id - $arId = array(); - $resultDeliveryTypeId = 0; - if (strpos($arDeliveryTypesList['ID'], ":") !== false) - $arId = explode(":", $arDeliveryTypesList['ID']); - - if ($arId) - $resultDeliveryTypeId = $arId[0]; - else - $resultDeliveryTypeId = $arDeliveryTypesList['ID']; - - $deliveryTypesArr[$arDeliveryTypesList['ID']] = $resultDeliveryTypeId; - - // send to crm - try { - $this->INTARO_CRM_API->deliveryTypeEdit(ICrmOrderActions::clearArr(array( - 'code' => $resultDeliveryTypeId, - 'name' => ICrmOrderActions::toJSON($arDeliveryTypesList['NAME']), - 'defaultCost' => $arDeliveryTypesList['PRICE'], - 'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']), - 'paymentTypes' => '' - ))); - } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::deliveryTypeEdit::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - } - - } while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()); - } - - if ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()) { - do { - - $deliveryTypesArr[$arDeliveryServicesList['SID']] = $arDeliveryServicesList['SID']; - - // send to crm - try { - $this->INTARO_CRM_API->deliveryTypeEdit(ICrmOrderActions::clearArr(array( - 'code' => $arDeliveryServicesList['SID'], - 'name' => ICrmOrderActions::toJSON($arDeliveryServicesList['NAME']), - 'defaultCost' => 0, - 'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']), - 'paymentTypes' => '' - ))); - } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::deliveryTypeEdit::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); - } - - foreach($arDeliveryServicesList['PROFILES'] as $id => $profile) { - // send to crm - try { - $this->INTARO_CRM_API->deliveryServiceEdit(ICrmOrderActions::clearArr(array( - 'code' => $arDeliveryServicesList['SID'] . '-' . $id, - 'name' => ICrmOrderActions::toJSON($profile['TITLE']), - 'deliveryType' => $arDeliveryServicesList['SID'] - ))); - } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryServiceEdit::CurlException', - $e->getCode() . ': ' . $e->getMessage() - ); + foreach($optionsDelivTypes as $deliveryType){ + $load = true; + try { + $this->RETAIL_CRM_API->deliveryTypesEdit(RCrmActions::clearArr(array( + 'code' => $deliveryType['ID'], + 'name' => RCrmActions::toJSON($deliveryType['NAME']), + 'defaultCost' => $deliveryType['CONFIG']['MAIN']['PRICE'], + 'description' => RCrmActions::toJSON($deliveryType['DESCRIPTION']), + 'paymentTypes' => '' + ))); + } catch (\RetailCrm\Exception\CurlException $e) { + $load = false; + RCrmActions::eventLog( + 'intaro.crm/install/index.php', 'RetailCrm\ApiClient::deliveryTypeEdit::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + } + if($load){ + foreach($optionsDelivTypes as $deliveryService){ + if($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $deliveryType['ID']){ + $srv = explode(':', $deliveryService['CODE']); + if(count($srv) == 2){ + try { + $this->RETAIL_CRM_API->deliveryServicesEdit(RCrmActions::clearArr(array( + 'code' => $srv[1], + 'name' => RCrmActions::toJSON($deliveryService['NAME']), + 'deliveryType' => $deliveryType['ID'] + ))); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'intaro.retailcrm/options.php', 'RetailCrm\ApiClient::deliveryServiceEdit::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + } + } } } - - } while ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()); + } } } //bitrix paymentTypesList - $dbPaymentTypesList = CSalePaySystem::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y" - ) - ); - - //form payment types ids arr + $arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList(); + $paymentTypesArr = array(); - if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) { - do { - $paymentTypesArr[$arPaymentTypesList['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $arPaymentTypesList['ID']])); - } while ($arPaymentTypesList = $dbPaymentTypesList->Fetch()); + foreach($arResult['bitrixPaymentTypesList'] as $payment){ + $paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']])); } - //bitrix paymentStatusesList - $dbPaymentStatusesList = CSaleStatus::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "LID" => "ru", //ru - "ACTIVE" => "Y" - ) - ); + //bitrix statusesList + $arResult['bitrixStatusesList'] = RCrmActions::StatusesList(); + + $paymentStatusesArr = array(); + $canselOrderArr = array(); - //form payment statuses ids arr - $paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY'])); - - if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) { - do { - $paymentStatusesArr[$arPaymentStatusesList['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $arPaymentStatusesList['ID']])); - } while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()); + foreach($arResult['bitrixStatusesList'] as $status){ + $paymentStatusesArr[$status['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $status['ID']])); + if(trim($_POST['order-cansel-' . $status['ID']]) == 'Y'){ + $canselOrderArr[] = $status['ID']; + } } //form payment ids arr @@ -901,24 +751,35 @@ class intaro_intarocrm extends CModule { $paymentArr['Y'] = htmlspecialchars(trim($_POST['payment-Y'])); $paymentArr['N'] = htmlspecialchars(trim($_POST['payment-N'])); - //form orderProps - $dbProp = CSaleOrderProps::GetList(array(), array()); - while ($arProp = $dbProp->GetNext()) { - $arResult['arProp'][$arProp['PERSON_TYPE_ID']][] = $arProp; - } + //new page + //form orderProps + $arResult['arProp'] = RCrmActions::OrderPropsList(); - COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_TYPES_ARR, serialize(ICrmOrderActions::clearArr($orderTypesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, serialize(ICrmOrderActions::clearArr($deliveryTypesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_TYPES, serialize(ICrmOrderActions::clearArr($paymentTypesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES, serialize(ICrmOrderActions::clearArr($paymentStatusesArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT, serialize(ICrmOrderActions::clearArr($paymentArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_TYPES_ARR, serialize(RCrmActions::clearArr($orderTypesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, serialize(RCrmActions::clearArr($deliveryTypesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_TYPES, serialize(RCrmActions::clearArr($paymentTypesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT_STATUSES, serialize(RCrmActions::clearArr($paymentStatusesArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_PAYMENT, serialize(RCrmActions::clearArr($paymentArr))); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE, 1); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, serialize(array())); + COption::SetOptionString($this->MODULE_ID, $this->CRM_CANSEL_ORDER, serialize(RCrmActions::clearArr($canselOrderArr))); + + if($orderProps = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_PROPS, 0)){ + $arResult['ORDER_PROPS'] = unserialize($orderProps); + } + if($customFields = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_CUSTOM_FIELDS, 0)){ + $arResult['CUSTOM_FIELDS'] = unserialize($customFields); + } + if($legalDetails = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_LEGAL_DETAILS, 0)){ + $arResult['LEGAL_DETAILS'] = unserialize($legalDetails); + } + if($contragentType = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_CONTRAGENT_TYPE, 0)){ + $arResult['CONTRAGENT_TYPES'] = unserialize($contragentType); + } $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step3.php' ); } else if ($step == 4) {//выгрузка старых заказов if (!CModule::IncludeModule("sale")) { @@ -927,28 +788,28 @@ class intaro_intarocrm extends CModule { if (isset($_POST['back']) && $_POST['back']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step2.php' ); } - + //order upload if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) { - ICrmOrderActions::uploadOrders(); // each 50 + RetailCrmOrder::uploadOrders(); // each 50 $lastUpOrderId = COption::GetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0); - $countLeft = (int) CSaleOrder::GetList(array("ID" => "ASC"), array('>ID' => $lastUpOrderId), array()); - $countAll = (int) CSaleOrder::GetList(array("ID" => "ASC"), array(), array()); + $countLeft = (int) \Bitrix\Sale\Internals\OrderTable::getCount(array('>ID' => $lastUpOrderId)); + $countAll = (int) \Bitrix\Sale\Internals\OrderTable::getCount(); - if (!isset($_POST['finish'])) + if (!isset($_POST['finish'])){ $finish = 0; - else + } + else{ $finish = (int) $_POST['finish']; - + } $percent = round(100 - ($countLeft * 100 / $countAll), 1); - if (!$countLeft) + if (!$countLeft){ $finish = 1; - + } $APPLICATION->RestartBuffer(); header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET); die(json_encode(array("finish" => $finish, "percent" => $percent))); @@ -956,28 +817,16 @@ class intaro_intarocrm extends CModule { if (isset($_POST['back']) && $_POST['back']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step2.php' ); } - //bitrix orderTypesList -- personTypes - $dbOrderTypesList = CSalePersonType::GetList( - array( - "SORT" => "ASC", - "NAME" => "ASC" - ), array( - "ACTIVE" => "Y", - ), false, false, array() - ); - - //form order types ids arr + //bitrix orderTypesList + $orderTypesList = RCrmActions::OrderTypesList(RCrmActions::SitesList()); + $orderTypesArr = array(); - $orderTypesList = array(); - if ($arOrderTypesList = $dbOrderTypesList->Fetch()) { - do { - $orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']])); - $orderTypesList[] = $arOrderTypesList; - } while ($arOrderTypesList = $dbOrderTypesList->Fetch()); + foreach($orderTypesList as $orderType){ + $orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']])); } $orderPropsArr = array(); @@ -998,7 +847,6 @@ class intaro_intarocrm extends CModule { foreach ($orderTypesList as $orderType) { $_legalDetailsArr = array(); foreach ($arResult['legalDetails'] as $legalDetails) { - $_legalDetailsArr[$legalDetails['ID']] = htmlspecialchars(trim($_POST['legal-detail-' . $legalDetails['ID'] . '-' . $orderType['ID']])); } $legalDetailsArr[$orderType['ID']] = $_legalDetailsArr; @@ -1019,14 +867,13 @@ class intaro_intarocrm extends CModule { $contragentTypeArr[$orderType['ID']] = htmlspecialchars(trim($_POST['contragent-type-' . $orderType['ID']])); } - COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_PROPS, serialize(ICrmOrderActions::clearArr($orderPropsArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOM_FIELDS, serialize(ICrmOrderActions::clearArr($customFieldsArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_LEGAL_DETAILS, serialize(ICrmOrderActions::clearArr($legalDetailsArr))); - COption::SetOptionString($this->MODULE_ID, $this->CRM_CONTRAGENT_TYPE, serialize(ICrmOrderActions::clearArr($contragentTypeArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_PROPS, serialize(RCrmActions::clearArr($orderPropsArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOM_FIELDS, serialize(RCrmActions::clearArr($customFieldsArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_LEGAL_DETAILS, serialize(RCrmActions::clearArr($legalDetailsArr))); + COption::SetOptionString($this->MODULE_ID, $this->CRM_CONTRAGENT_TYPE, serialize(RCrmActions::clearArr($contragentTypeArr))); $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step4.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step4.php' ); } else if ($step == 5) {//экспорт каталога @@ -1037,6 +884,48 @@ class intaro_intarocrm extends CModule { if (!CModule::IncludeModule("catalog")) { $arResult['errCode'] = 'ERR_CATALOG'; } + $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); + $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); + $api = new \RetailCrm\ApiClient($api_host, $api_key); + + $customerH = self::historyLoad($api, 'customersHistory'); + COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY, $customerH); + //если есть старое значение, переделываем его на новый лад, иначе вычисляем + if($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)){ + try { + $history = $api->ordersHistory(array('startDate' => $historyDate)); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\RestApi::ordersHistory::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\RestApi::ordersHistory::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + + } + if(isset($history['history'])){ + $hIs = (int)$history['history'][0]['id'] - 1; + $orderH = $hIs; + } + else{ + $orderH = self::historyLoad($api, 'ordersHistory'); + } + } + else{ + $orderH = self::historyLoad($api, 'ordersHistory'); + } + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY, $orderH); + + if($orderLastId = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_LAST_ID, 0)){ + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, $orderLastId); + } + if($orderFailedIds = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_FAILED_IDS, 0)){ + COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, $orderFailedIds); + } $arResult['PRICE_TYPES'] = array(); @@ -1049,8 +938,7 @@ class intaro_intarocrm extends CModule { } $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php' ); } else if ($step == 6) {//регистрация модуля @@ -1064,16 +952,14 @@ class intaro_intarocrm extends CModule { if (isset($arResult['errCode']) && $arResult['errCode']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php' ); return; } if (isset($_POST['back']) && $_POST['back']) { $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step3.php' ); } @@ -1083,14 +969,14 @@ class intaro_intarocrm extends CModule { $iblocks = $_POST['IBLOCK_EXPORT']; $iblockProperties = Array( - "article" => "article", + "article" => "article", "manufacturer" => "manufacturer", - "color" =>"color", - "weight" => "weight", - "size" => "size", - "length" => "length", - "width" => "width", - "height" => "height", + "color" => "color", + "weight" => "weight", + "size" => "size", + "length" => "length", + "width" => "width", + "height" => "height", ); $propertiesSKU = array(); @@ -1150,50 +1036,47 @@ class intaro_intarocrm extends CModule { global $oldValues; $oldValues = $arOldValues; $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php' ); return; } RegisterModule($this->MODULE_ID); - RegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSalePayOrder"); - RegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleCancelOrder"); - RegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAccountNumberSet"); - RegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "ICrmOrderEvent", "onSendOrderMail"); - RegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "ICrmOrderEvent", "onUpdateOrder"); - RegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAdd"); - RegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "ICrmOrderEvent", "OnSaleBeforeReserveOrder"); - RegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleReserveOrder"); - + //RegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "RetailCrmEvent", "onSalePayOrder"); + //RegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleCancelOrder"); + //RegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAccountNumberSet"); + //RegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "RetailCrmEvent", "onSendOrderMail"); + RegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder"); + RegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd"); + RegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave"); + //RegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "OnSaleBeforeReserveOrder"); + //RegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleReserveOrder"); + //RegisterModuleDependences("main", "OnAfterUserRegister", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserRegister"); + //RegisterModuleDependences("main", "OnAfterUserAdd", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserAdd"); + RegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate"); + RegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave"); + RegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete"); + COption::SetOptionString($this->MODULE_ID, $this->CRM_CATALOG_BASE_PRICE, htmlspecialchars(trim($_POST['price-types']))); COption::SetOptionString($this->MODULE_ID, $this->CRM_CATALOG_IBLOCKS, $iblocks); $this->CopyFiles(); - if (isset($_POST['LOAD_NOW'])) { - $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); - while ($ar = $rsSites->Fetch()){ - if($ar['DEF'] == 'Y'){ - $SERVER_NAME = $ar['SERVER_NAME'];//разделить потом с учетом многосайтовости - } - } - - $loader = new ICMLLoader(); + if (isset($_POST['LOAD_NOW'])) { + $loader = new RetailCrmICML(); $loader->iblocks = $iblocks; $loader->propertiesUnitProduct = $propertiesUnitProduct; $loader->propertiesProduct = $propertiesProduct; $loader->propertiesUnitSKU = $propertiesUnitSKU; $loader->propertiesSKU = $propertiesSKU; $loader->filename = $filename; - $loader->serverName = $SERVER_NAME; + $loader->serverName = \Bitrix\Main\Context::getCurrent()->getServer()->getHttpHost(); $loader->application = $APPLICATION; - $loader->Load(); - + $loader->Load(); } if ($typeLoading == 'agent' || $typeLoading == 'cron') { - if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->INTARO_CRM_EXPORT . '_run.php')) { - $dbProfile = CCatalogExport::GetList(array(), array("FILE_NAME" => $this->INTARO_CRM_EXPORT)); + if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->RETAIL_CRM_EXPORT . '_run.php')) { + $dbProfile = CCatalogExport::GetList(array(), array("FILE_NAME" => $this->RETAIL_CRM_EXPORT)); while ($arProfile = $dbProfile->Fetch()) { if ($arProfile["DEFAULT_PROFILE"] != "Y") { @@ -1204,15 +1087,15 @@ class intaro_intarocrm extends CModule { } $ar = $this->GetProfileSetupVars($iblocks, $propertiesProduct, $propertiesUnitProduct, $propertiesSKU, $propertiesUnitSKU, $filename); $PROFILE_ID = CCatalogExport::Add(array( - "LAST_USE" => false, - "FILE_NAME" => $this->INTARO_CRM_EXPORT, - "NAME" => $profileName, - "DEFAULT_PROFILE" => "N", - "IN_MENU" => "N", - "IN_AGENT" => "N", - "IN_CRON" => "N", - "NEED_EDIT" => "N", - "SETUP_VARS" => $ar + "LAST_USE" => false, + "FILE_NAME" => $this->RETAIL_CRM_EXPORT, + "NAME" => $profileName, + "DEFAULT_PROFILE" => "N", + "IN_MENU" => "N", + "IN_AGENT" => "N", + "IN_CRON" => "N", + "NEED_EDIT" => "N", + "SETUP_VARS" => $ar )); if (intval($PROFILE_ID) <= 0) { $arResult['errCode'] = 'ERR_IBLOCK'; @@ -1294,7 +1177,7 @@ class intaro_intarocrm extends CModule { $dateAgent->add($intAgent); CAgent::AddAgent( - "ICrmOrderActions::orderAgent();", $this->MODULE_ID, "N", 600, // interval - 10 mins + "RCrmActions::orderAgent();", $this->MODULE_ID, "N", 600, // interval - 10 mins $dateAgent->format('d.m.Y H:i:s'), // date of first check "Y", // agent is active $dateAgent->format('d.m.Y H:i:s'), // date of first start @@ -1303,12 +1186,12 @@ class intaro_intarocrm extends CModule { $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); - $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key); + $this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); try { - $this->INTARO_CRM_API->statisticUpdate(); + $this->RETAIL_CRM_API->statisticUpdate(); } catch (\RetailCrm\Exception\CurlException $e) { - ICrmOrderActions::eventLog( - 'intaro.crm/install/index.php', 'RetailCrm\RestApi::statisticUpdate::CurlException', + RCrmActions::eventLog( + 'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::statisticUpdate::CurlException', $e->getCode() . ': ' . $e->getMessage() ); } @@ -1316,8 +1199,7 @@ class intaro_intarocrm extends CModule { COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE, date('Y-m-d H:i:s')); $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_INSTALL_TITLE'), - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step6.php' + GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step6.php' ); } } @@ -1325,9 +1207,7 @@ class intaro_intarocrm extends CModule { function DoUninstall() { global $APPLICATION; - CAgent::RemoveAgent("ICrmOrderActions::uploadOrdersAgent();", $this->MODULE_ID); - CAgent::RemoveAgent("ICrmOrderActions::orderHistoryAgent();", $this->MODULE_ID); - CAgent::RemoveAgent("ICrmOrderActions::orderAgent();", $this->MODULE_ID); + CAgent::RemoveAgent("RCrmActions::orderAgent();", $this->MODULE_ID); COption::RemoveOption($this->MODULE_ID, $this->CRM_API_HOST_OPTION); COption::RemoveOption($this->MODULE_ID, $this->CRM_API_KEY_OPTION); @@ -1344,21 +1224,31 @@ class intaro_intarocrm extends CModule { COption::RemoveOption($this->MODULE_ID, $this->CRM_SITES_LIST); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS); - COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE); + COption::RemoveOption($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY); + COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_HISTORY); COption::RemoveOption($this->MODULE_ID, $this->CRM_CATALOG_BASE_PRICE); COption::RemoveOption($this->MODULE_ID, $this->CRM_CATALOG_IBLOCKS); + COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_NUMBERS); + COption::RemoveOption($this->MODULE_ID, $this->CRM_CANSEL_ORDER); - UnRegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSalePayOrder"); - UnRegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleCancelOrder"); - UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "ICrmOrderEvent", "onSendOrderMail"); - UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "ICrmOrderEvent", "onUpdateOrder"); - UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAdd"); - UnRegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "ICrmOrderEvent", "onBeforeOrderAccountNumberSet"); - UnRegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleBeforeReserveOrder"); - UnRegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "ICrmOrderEvent", "onSaleReserveOrder"); + //UnRegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "RetailCrmEvent", "onSalePayOrder"); + //UnRegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleCancelOrder"); + //UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "RetailCrmEvent", "onSendOrderMail"); + UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder"); + UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd"); + UnRegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave"); + //UnRegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAccountNumberSet"); + //UnRegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleBeforeReserveOrder"); + //UnRegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleReserveOrder"); + //UnRegisterModuleDependences("main", "OnAfterUserRegister", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserRegister"); + //UnRegisterModuleDependences("main", "OnAfterUserAdd", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserAdd"); + UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate"); + UnRegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave"); + UnRegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete"); + if (CModule::IncludeModule("catalog")) { - if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->INTARO_CRM_EXPORT . '_run.php')) { - $dbProfile = CCatalogExport::GetList(array(), array("FILE_NAME" => $this->INTARO_CRM_EXPORT)); + if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->RETAIL_CRM_EXPORT . '_run.php')) { + $dbProfile = CCatalogExport::GetList(array(), array("FILE_NAME" => $this->RETAIL_CRM_EXPORT)); while ($arProfile = $dbProfile->Fetch()) { if ($arProfile["DEFAULT_PROFILE"] != "Y") { @@ -1374,27 +1264,14 @@ class intaro_intarocrm extends CModule { UnRegisterModule($this->MODULE_ID); $APPLICATION->IncludeAdminFile( - GetMessage('MODULE_UNINSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/unstep1.php' + GetMessage('MODULE_UNINSTALL_TITLE'), $this->INSTALL_PATH . '/unstep1.php' ); - } + } function CopyFiles() { CopyDirFiles( - $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/export/', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/', true, true + $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/export/', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/', true, true ); - - $rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y')); - $defaultSite = array(); - while ($ar = $rsSites->Fetch()) { - $defaultSite = $ar; - break; - } - - if(mkdir($defaultSite['ABS_DOC_ROOT'] . '/retailcrm/')) { - CopyDirFiles( - $defaultSite['ABS_DOC_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/retailcrm/', $defaultSite['ABS_DOC_ROOT'] . '/retailcrm/', true, true - ); - } } function DeleteFiles() { @@ -1405,8 +1282,8 @@ class intaro_intarocrm extends CModule { break; } - unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_run.php'); - unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/intarocrm_setup.php'); + unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/retailcrm_run.php'); + unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/retailcrm_setup.php'); unlink($defaultSite['ABS_DOC_ROOT'] . '/retailcrm/agent.php'); rmdir($defaultSite['ABS_DOC_ROOT'] . '/retailcrm/'); } @@ -1439,4 +1316,45 @@ class intaro_intarocrm extends CModule { return $strVars; } + + function historyLoad($api, $method){ + $historyFilter = array(); + while(true){ + try { + $history = $api->$method($historyFilter); + } catch (\RetailCrm\Exception\CurlException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::CurlException', + $e->getCode() . ': ' . $e->getMessage() + ); + $end['id'] = 0; + + return $end['id']; + } catch (InvalidArgumentException $e) { + RCrmActions::eventLog( + 'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::InvalidArgumentException', + $e->getCode() . ': ' . $e->getMessage() + ); + $end['id'] = 0; + + return $end['id']; + } + + if(isset($history['history'])){ + $end = array_pop($history['history']); + } + else{ + $end['id'] = 0; + break; + } + + if($history['pagination']['totalPageCount'] == 1){ + break; + } + + $historyFilter['sinceId'] = $end['id']; + } + + return $end['id']; + } } \ No newline at end of file diff --git a/intaro.intarocrm/install/step1.php b/intaro.retailcrm/install/step1.php similarity index 85% rename from intaro.intarocrm/install/step1.php rename to intaro.retailcrm/install/step1.php index 7c47880e..150b738c 100644 --- a/intaro.intarocrm/install/step1.php +++ b/intaro.retailcrm/install/step1.php @@ -9,7 +9,7 @@
- + @@ -31,11 +31,11 @@ - + - + diff --git a/intaro.intarocrm/install/step11.php b/intaro.retailcrm/install/step11.php similarity index 89% rename from intaro.intarocrm/install/step11.php rename to intaro.retailcrm/install/step11.php index 70a02ae3..9047df99 100644 --- a/intaro.intarocrm/install/step11.php +++ b/intaro.retailcrm/install/step11.php @@ -9,7 +9,7 @@ - + @@ -36,7 +36,7 @@ diff --git a/intaro.intarocrm/install/step2.php b/intaro.retailcrm/install/step2.php similarity index 73% rename from intaro.intarocrm/install/step2.php rename to intaro.retailcrm/install/step2.php index f1a46f47..90f4487c 100644 --- a/intaro.intarocrm/install/step2.php +++ b/intaro.retailcrm/install/step2.php @@ -1,7 +1,7 @@ 'eshop-individual', - 2 => 'eshop-legal' -); +if(isset($arResult['ORDER_TYPES'])){ + $defaultOrderTypes = $arResult['ORDER_TYPES']; +} +else{ + $defaultOrderTypes = array ( + 1 => 'eshop-individual', + 2 => 'eshop-legal' + ); +} -$defaultDelivTypes = array ( - 1 => 'courier', - 2 => 'self-delivery' -); +if(isset($arResult['DELIVERY_TYPES'])){ + $defaultDelivTypes = $arResult['DELIVERY_TYPES']; +} +else{ + $defaultDelivTypes = array ( + 1 => 'courier', + 2 => 'self-delivery' + ); +} -$defaultPayTypes = array ( - 1 => 'cash', - 5 => 'bank-transfer', - 6 => 'bank-transfer' -); +if(isset($arResult['PAYMENT_TYPES'])){ + $defaultPayTypes = $arResult['PAYMENT_TYPES']; +} +else{ + $defaultPayTypes = array ( + 1 => 'cash', + 4 => 'e-money', + 5 => 'bank-card', + 9 => 'bank-transfer' + ); +} -$defaultPayStatuses = array ( - 'N' => 'new', - 'P' => 'approval', - 'F' => 'complete', - 'Y' => 'cancel-other' -); +if(isset($arResult['PAYMENT_STATUSES'])){ + $defaultPayStatuses = $arResult['PAYMENT_STATUSES']; +} +else{ + $defaultPayStatuses = array ( + 'N' => 'new', + 'P' => 'prepayed', + 'F' => 'complete', + ); +} -$defaultPayment = array( - 'Y' => 'paid', - 'N' => 'not-paid' -); +if(isset($arResult['PAYMENT'])){ + $defaultPayment = $arResult['PAYMENT']; +} +else{ + $defaultPayment = array( + 'Y' => 'paid', + 'N' => 'not-paid' + ); +} ?> @@ -106,18 +131,18 @@ $defaultPayment = array( - + - + @@ -180,27 +205,47 @@ $defaultPayment = array( - - + + + + + diff --git a/intaro.intarocrm/install/step3.php b/intaro.retailcrm/install/step3.php similarity index 87% rename from intaro.intarocrm/install/step3.php rename to intaro.retailcrm/install/step3.php index 6a94c8fa..95764ca8 100644 --- a/intaro.intarocrm/install/step3.php +++ b/intaro.retailcrm/install/step3.php @@ -3,22 +3,28 @@ if (!check_bitrix_sessid()) return; IncludeModuleLangFile(__FILE__); -$defaultOrderProps = array( - 1 => array( - 'fio' => 'FIO', - 'index' => 'ZIP', - 'text' => 'ADDRESS', - 'phone' => 'PHONE', - 'email' => 'EMAIL' - ), - 2 => array( - 'fio' => 'FIO', - 'index' => 'ZIP', - 'text' => 'ADDRESS', - 'phone' => 'PHONE', - 'email' => 'EMAIL' - ) -); +if(isset($arResult['ORDER_PROPS'])){ + $defaultOrderProps = $arResult['ORDER_PROPS']; +} +else{ + $defaultOrderProps = array( + 1 => array( + 'fio' => 'FIO', + 'index' => 'ZIP', + 'text' => 'ADDRESS', + 'phone' => 'PHONE', + 'email' => 'EMAIL' + ), + 2 => array( + 'fio' => 'CONTACT_PERSON', + 'index' => 'ZIP', + 'text' => 'ADDRESS', + 'phone' => 'PHONE', + 'email' => 'EMAIL' + ) + ); +} +echo"
";var_export($arResult);echo"
"; ?>
- + + + + + + +
+
+ - + + + + + +
+ + + +