1
0
mirror of synced 2024-11-22 13:26:10 +03:00
This commit is contained in:
Евгений 2017-09-04 11:36:04 +03:00 committed by Alex Lushpai
parent 02dc926ea3
commit fea35d72ae
31 changed files with 6116 additions and 882 deletions

View File

@ -1,3 +1,17 @@
## 2017-08-21 v.2.2.1
* Добавлена встроенная функция retailCrmApiResult
* Добавлен триггерный вариант истории изменений
* Исправлены ошибки
## 2017-08-21 v.2.2.0
* API V5
* Возможность выбора версии API
* Добавлена возможность выгрузки остатков в разрезе складов
* Добавлена возможность выгрузки типов цен
* Добавлена базовая интеграция Demon Collector
* Добавлена интеграция с Universal Analytics
* Доработана логика работы встроенных функций для модификации данных
* Исправлены ошибки
## 2016-12-09 v.2.1.2 ## 2016-12-09 v.2.1.2
* Добавлены единицы измерения в экспорте каталога * Добавлены единицы измерения в экспорте каталога
* Исправлены пути в include * Исправлены пути в include

View File

@ -97,6 +97,35 @@ class ApiClient
); );
} }
/**
* Get user groups
*
* @param null $page
* @param null $limit
*
* @throws \RetailCrm\Exception\InvalidJsonException
* @throws \RetailCrm\Exception\CurlException
*
* @return ApiResponse
*/
public function usersGroups($page = null, $limit = null)
{
$parameters = array();
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest(
'/user-groups',
Client::METHOD_GET,
$parameters
);
}
/** /**
* Returns user data * Returns user data
* *
@ -804,7 +833,7 @@ class ApiClient
return $this->client->makeRequest( return $this->client->makeRequest(
sprintf('/store/setting/%s/edit', $configuration['code']), sprintf('/store/setting/%s/edit', $configuration['code']),
Client::METHOD_POST, Client::METHOD_POST,
$configuration array('configuration' => json_encode($configuration))
); );
} }
@ -834,6 +863,33 @@ class ApiClient
$this->fillSite($site, array('offers' => json_encode($offers))) $this->fillSite($site, array('offers' => json_encode($offers)))
); );
} }
/**
* Upload store prices
*
* @param array $prices prices data
* @param string $site default: null)
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function storePricesUpload(array $prices, $site = null)
{
if (!count($prices)) {
throw new \InvalidArgumentException(
'Parameter `prices` must contains array of the prices'
);
}
return $this->client->makeRequest(
'/store/prices/upload',
Client::METHOD_POST,
$this->fillSite($site, array('prices' => json_encode($prices)))
);
}
/** /**
* Get products * Get products
@ -945,7 +1001,7 @@ class ApiClient
return $this->client->makeRequest( return $this->client->makeRequest(
sprintf('/delivery/generic/%s/tracking', $code), sprintf('/delivery/generic/%s/tracking', $code),
Client::METHOD_POST, Client::METHOD_POST,
$statusUpdate array('statusUpdate' => json_encode($statusUpdate))
); );
} }
@ -1419,6 +1475,54 @@ class ApiClient
); );
} }
/**
* Get prices types
*
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function pricesTypes()
{
return $this->client->makeRequest(
'/reference/price-types',
Client::METHOD_GET
);
}
/**
* Edit price type
*
* @param array $data
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function pricesEdit(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/price-types/%s/edit', $data['code']),
Client::METHOD_POST,
array('priceType' => json_encode($data))
);
}
/** /**
* Get telephony settings * Get telephony settings
* *
@ -1652,6 +1756,32 @@ class ApiClient
); );
} }
/**
* Edit marketplace configuration
*
* @param array $configuration
*
* @throws \RetailCrm\Exception\InvalidJsonException
* @throws \RetailCrm\Exception\CurlException
* @throws \InvalidArgumentException
*
* @return ApiResponse
*/
public function marketplaceSettingsEdit(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('/marketplace/external/setting/%s/edit', $configuration['code']),
Client::METHOD_POST,
array('configuration' => json_encode($configuration))
);
}
/** /**
* Update CRM basic statistic * Update CRM basic statistic
* *

File diff suppressed because it is too large Load Diff

View File

@ -4,6 +4,7 @@ class RCrmActions
{ {
public static $MODULE_ID = 'intaro.retailcrm'; public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_ORDER_FAILED_IDS = 'order_failed_ids'; public static $CRM_ORDER_FAILED_IDS = 'order_failed_ids';
public static $CRM_API_VERSION = 'api_version';
const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED'; const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
@ -41,8 +42,17 @@ class RCrmActions
$bitrixDeliveryTypesList = array(); $bitrixDeliveryTypesList = array();
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
$noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
$groups = array();
foreach ($arDeliveryServiceAll as $arDeliveryService) { foreach ($arDeliveryServiceAll as $arDeliveryService) {
if (($arDeliveryService['PARENT_ID'] == '0' || $arDeliveryService['PARENT_ID'] == null) && $arDeliveryService['ID'] != $noOrderId) { if ($arDeliveryService['CLASS_NAME'] == '\Bitrix\Sale\Delivery\Services\Group') {
$groups[] = $arDeliveryService['ID'];
}
}
foreach ($arDeliveryServiceAll as $arDeliveryService) {
if ((($arDeliveryService['PARENT_ID'] == '0' || $arDeliveryService['PARENT_ID'] == null) ||
in_array($arDeliveryService['PARENT_ID'], $groups)) &&
$arDeliveryService['ID'] != $noOrderId &&
$arDeliveryService['CLASS_NAME'] != '\Bitrix\Sale\Delivery\Services\Group') {
$bitrixDeliveryTypesList[] = $arDeliveryService; $bitrixDeliveryTypesList[] = $arDeliveryService;
} }
} }
@ -63,7 +73,7 @@ class RCrmActions
return $bitrixPaymentTypesList; return $bitrixPaymentTypesList;
} }
public static function StatusesList() public static function StatusesList()
{ {
$bitrixPaymentStatusesList = array(); $bitrixPaymentStatusesList = array();
@ -79,8 +89,8 @@ class RCrmActions
} }
return $bitrixPaymentStatusesList; return $bitrixPaymentStatusesList;
} }
public static function OrderPropsList() public static function OrderPropsList()
{ {
$bitrixPropsList = array(); $bitrixPropsList = array();
@ -93,6 +103,57 @@ class RCrmActions
return $bitrixPropsList; return $bitrixPropsList;
} }
public static function PricesExportList()
{
$priceId = COption::GetOptionString(self::$MODULE_ID, 'catalog_base_price', 0);
$catalogExportPrices = array();
$dbPriceType = CCatalogGroup::GetList(array(), array('!ID' => $priceId), false, false, array('ID', 'NAME', 'NAME_LANG'));
while ($arPriceType = $dbPriceType->Fetch())
{
$catalogExportPrices[$arPriceType['ID']] = $arPriceType;
}
return $catalogExportPrices;
}
public static function StoresExportList()
{
$catalogExportStores = array();
$dbStores = CCatalogStore::GetList(array(), array("ACTIVE" => "Y"), false, false, array('ID', 'TITLE'));
while ($stores = $dbStores->Fetch()) {
$catalogExportStores[] = $stores;
}
return $catalogExportStores;
}
public static function IblocksExportList()
{
$catalogExportIblocks = array();
$dbIblocks = CIBlock::GetList(array("IBLOCK_TYPE" => "ASC", "NAME" => "ASC"), array('CHECK_PERMISSIONS' => 'Y','MIN_PERMISSION' => 'W'));
while ($iblock = $dbIblocks->Fetch()) {
if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) {
if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") {
$catalogExportIblocks[$iblock['ID']] = array(
'ID' => $iblock['ID'],
'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'],
'LID' => $iblock['LID'],
'CODE' => $iblock['CODE'],
'NAME' => $iblock['NAME'],
);
if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") {
$iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]);
$catalogExportIblocks[$iblock['ID']]['SKU'] = $iblockOffer;
}
}
}
}
return $catalogExportIblocks;
}
/** /**
* *
* w+ event in bitrix log * w+ event in bitrix log
@ -124,7 +185,7 @@ class RCrmActions
RetailCrmOrder::uploadOrders(50, true); RetailCrmOrder::uploadOrders(50, true);
} }
return 'RCrmActions::uploadOrdersAgent();'; return;
} }
/** /**
@ -199,10 +260,14 @@ class RCrmActions
public static function explodeFIO($fio) public static function explodeFIO($fio)
{ {
$fio = preg_replace('|[\s]+|s', ' ', trim($fio));
$newFio = empty($fio) ? false : explode(" ", $fio, 3);
$result = array(); $result = array();
$fio = preg_replace('|[\s]+|s', ' ', trim($fio));
if (empty($fio)) {
return $result;
} else {
$newFio = explode(" ", $fio, 3);
}
switch (count($newFio)) { switch (count($newFio)) {
default: default:
case 0: case 0:
@ -232,61 +297,114 @@ class RCrmActions
public static function apiMethod($api, $methodApi, $method, $params, $site = null) public static function apiMethod($api, $methodApi, $method, $params, $site = null)
{ {
switch ($methodApi) { switch ($methodApi) {
case 'ordersPaymentDelete':
case 'ordersHistory':
case 'customerHistory':
case 'ordersFixExternalIds':
case 'customersFixExternalIds':
return self::proxy($api, $methodApi, $method, array($params));
case 'orderGet':
return self::proxy($api, 'ordersGet', $method, array($params, 'id', $site));
case 'ordersGet': case 'ordersGet':
case 'ordersEdit': case 'ordersEdit':
case 'customersGet': case 'customersGet':
case 'customersEdit': case 'customersEdit':
try { case 'ordersPaymentEdit':
$result = $api->$methodApi($params, 'externalId', $site); return self::proxy($api, $methodApi, $method, array($params, 'externalId', $site));
if (isset($result['errorMsg'])) {
self::eventLog(__CLASS__.'::'.$method, 'RetailCrm\ApiClient::'.$methodApi, $result['errorMsg']);
$log = new Logger();
$log->write(array($methodApi, $result['errorMsg'], $result['errors'], $params), 'apiErrors');
}
} 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: default:
try { return self::proxy($api, $methodApi, $method, array($params, $site));
$result = $api->$methodApi($params, $site);
if (isset($result['errorMsg'])) {
if ($methodApi != 'customersUpload' && $methodApi != 'ordersUpload') {
self::eventLog(__CLASS__.'::'.$method, 'RetailCrm\ApiClient::'.$methodApi, $result['errorMsg']);
}
$log = new Logger();
$log->write(array($methodApi, $result['errorMsg'], $result['errors'], $params), 'apiErrors');
}
} 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;
} }
} }
private function proxy($api, $methodApi, $method, $params) {
$log = new Logger();
$version = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_VERSION, 0);
try {
$result = call_user_func_array(array($api, $methodApi), $params);
if ($result->getStatusCode() !== 200 && $result->getStatusCode() !== 201) {
if ($methodApi == 'ordersGet' || $methodApi == 'customersGet') {
$log->write(array(
'api' => $version,
'methodApi' => $methodApi,
'errorMsg' => !empty($result['errorMsg']) ? $result['errorMsg'] : '',
'errors' => !empty($result['errors']) ? $result['errors'] : '',
'params' => $params
), 'apiErrors');
} elseif ($methodApi == 'customersUpload' || $methodApi == 'ordersUpload') {
$log->write(array(
'api' => $version,
'methodApi' => $methodApi,
'errorMsg' => !empty($result['errorMsg']) ? $result['errorMsg'] : '',
'errors' => !empty($result['errors']) ? $result['errors'] : '',
'params' => $params
), 'uploadApiErrors');
} else {
self::eventLog(__CLASS__ . '::' . $method, 'RetailCrm\ApiClient::' . $methodApi, !empty($result['errorMsg']) ? $result['errorMsg'] : '');
$log->write(array(
'api' => $version,
'methodApi' => $methodApi,
'errorMsg' => !empty($result['errorMsg']) ? $result['errorMsg'] : '',
'errors' => !empty($result['errors']) ? $result['errors'] : '',
'params' => $params
), 'apiErrors');
}
if (function_exists('retailCrmApiResult')) {
retailCrmApiResult($methodApi, false, $result->getStatusCode());
}
if ($result->getStatusCode() == 460) {
return true;
}
return false;
}
} catch (\RetailCrm\Exception\CurlException $e) {
self::eventLog(
__CLASS__ . '::' . $method, 'RetailCrm\ApiClient::' . $methodApi . '::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$log->write(array(
'api' => $version,
'methodApi' => $methodApi,
'errorMsg' => $e->getMessage(),
'errors' => $e->getCode(),
'params' => $params
), 'apiErrors');
if (function_exists('retailCrmApiResult')) {
retailCrmApiResult($methodApi, false, 'CurlException');
}
return false;
} catch (InvalidArgumentException $e) {
self::eventLog(
__CLASS__ . '::' . $method, 'RetailCrm\ApiClient::' . $methodApi . '::InvalidArgumentException',
$e->getCode() . ': ' . $e->getMessage()
);
$log->write(array(
'api' => $version,
'methodApi' => $methodApi,
'errorMsg' => $e->getMessage(),
'errors' => $e->getCode(),
'params' => $params
), 'apiErrors');
if (function_exists('retailCrmApiResult')) {
retailCrmApiResult($methodApi, false, 'ArgumentException');
}
return false;
}
if (function_exists('retailCrmApiResult')) {
retailCrmApiResult($methodApi, true, $result->getStatusCode());
}
return $result;
}
} }

View File

@ -0,0 +1,32 @@
<?php
class RetailCrmCollector
{
public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_COLL_KEY = 'coll_key';
public static $CRM_COLL = 'collector';
public static function add()
{
$keys = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_COLL_KEY, 0));
$collector = COption::GetOptionString(self::$MODULE_ID, self::$CRM_COLL, 0);
if ($collector === 'Y' && !empty($keys[SITE_ID]) && ADMIN_SECTION !== true) {
global $APPLICATION;
global $USER;
$params = array();
if ($USER->IsAuthorized()) {
$params['customerId'] = $USER->GetID();
}
$str = "<script type=\"text/javascript\">
(function(_,r,e,t,a,i,l){_['retailCRMObject']=a;_[a]=_[a]||function(){(_[a].q=_[a].q||[]).push(arguments)};_[a].l=1*new Date();l=r.getElementsByTagName(e)[0];i=r.createElement(e);i.async=!0;i.src=t;l.parentNode.insertBefore(i,l)})(window,document,'script','https://collector.retailcrm.pro/w.js','_rc');
_rc('create', '" . $keys[SITE_ID] . "', " . json_encode((object) $params) . ");
_rc('send', 'pageView');
</script>";
$APPLICATION->AddHeadString($str, true);
} else {
return false;
}
}
}

View File

@ -71,6 +71,13 @@
<field id="order_product.discount_percent" group="item">discountPercent</field> <field id="order_product.discount_percent" group="item">discountPercent</field>
<field id="order_product.quantity" group="item">quantity</field> <field id="order_product.quantity" group="item">quantity</field>
<field id="order_product.status" group="item">status</field> <field id="order_product.status" group="item">status</field>
<field id="order_product.discount_total" group="item">discountTotal</field>
<field id="payments.status" group="payment">status</field>
<field id="payments.type" group="payment">type</field>
<field id="payments.external_id" group="payment">externalId</field>
<field id="payments.amount" group="payment">amount</field>
<field id="payments.comment" group="payment">comment</field>
<field id="delivery_type" group="delivery">code</field> <field id="delivery_type" group="delivery">code</field>
<field id="delivery_service" group="delivery">service</field> <field id="delivery_service" group="delivery">service</field>

View File

@ -131,11 +131,11 @@
"type": "string" "type": "string"
}, },
"managerId": { "managerId": {
"type": "int" "type": "int"
}, },
"browserId": { "browserId": {
"type": "string" "type": "string"
} }
}, },
"orders": { "orders": {
"number": { "number": {
@ -149,6 +149,19 @@
"type": "datetime", "type": "datetime",
"format": "Y-m-d H:i:s" "format": "Y-m-d H:i:s"
}, },
"discountManualAmount": {
"type": "double",
"default": 0,
"min": 0,
"decimals": 2
},
"discountManualPercent": {
"type": "double",
"default": 0,
"max": 100,
"min": 0,
"decimals": 2
},
"discount": { "discount": {
"type": "double", "type": "double",
"default": 0, "default": 0,
@ -287,6 +300,19 @@
"paymentStatus": { "paymentStatus": {
"type": "string" "type": "string"
}, },
"type": {
"type": "string"
},
"amount": {
"type": "double",
"default": 0,
"min": 0,
"decimals": 2
},
"paidAt": {
"type": "datetime",
"format": "Y-m-d H:i:s"
},
"status": { "status": {
"type": "string" "type": "string"
}, },

View File

@ -2,6 +2,7 @@
/** /**
* RCrmEvent * RCrmEvent
*/ */
use \Bitrix\Main\Event;
class RetailCrmEvent class RetailCrmEvent
{ {
protected static $MODULE_ID = 'intaro.retailcrm'; protected static $MODULE_ID = 'intaro.retailcrm';
@ -47,29 +48,7 @@ class RetailCrmEvent
} }
return true; return true;
} }
/**
* 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 * onUpdateOrder
@ -84,7 +63,8 @@ class RetailCrmEvent
return; return;
} }
$GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = true; $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = true;
return; return;
} }
@ -95,7 +75,8 @@ class RetailCrmEvent
*/ */
function orderDelete($event) function orderDelete($event)
{ {
$GLOBALS['RETAILCRM_ORDER_DELETE'] = true; $GLOBALS['RETAILCRM_ORDER_DELETE'] = true;
return; return;
} }
@ -110,26 +91,30 @@ class RetailCrmEvent
if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true) { if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true) {
if (!CModule::IncludeModule('iblock')) { if (!CModule::IncludeModule('iblock')) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found');
return true; return true;
} }
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'sale', 'module not found'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'sale', 'module not found');
return true; return true;
} }
if (!CModule::IncludeModule("catalog")) { if (!CModule::IncludeModule("catalog")) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'catalog', 'module not found'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'catalog', 'module not found');
return true; return true;
} }
//проверка на существование getParameter("ENTITY") //exists getParameter("ENTITY")
if (method_exists($event, 'getId')) { if (method_exists($event, 'getId')) {
$obOrder = $event; $obOrder = $event;
} elseif (method_exists($event, 'getParameter')) { } elseif (method_exists($event, 'getParameter')) {
$obOrder = $event->getParameter("ENTITY"); $obOrder = $event->getParameter("ENTITY");
} else { } else {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error');
return true; return true;
} }
@ -165,13 +150,18 @@ class RetailCrmEvent
'optionsCustomFields' => $optionsCustomFields 'optionsCustomFields' => $optionsCustomFields
)); ));
//многосайтовость //many sites?
$site = count($optionsSitesList) > 1 ? $optionsSitesList[$arOrder['LID']] : null; if(!empty($optionsSitesList) && array_key_exists($arOrder['LID'], $optionsSitesList)) {
$site = $optionsSitesList[$arOrder['LID']];
} else {
$site = null;
}
//проверка на новый заказ //new order?
$orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site);
if (isset($orderCrm['order'])) { if (isset($orderCrm['order'])) {
$methodApi = 'ordersEdit'; $methodApi = 'ordersEdit';
$arParams['crmOrder'] = $orderCrm['order'];
} else { } else {
$methodApi = 'ordersCreate'; $methodApi = 'ordersCreate';
} }
@ -183,6 +173,7 @@ class RetailCrmEvent
$resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site); $resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site);
if (!$resultUser) { if (!$resultUser) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer');
return true; return true;
} }
} }
@ -191,12 +182,13 @@ class RetailCrmEvent
$resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi); $resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi);
if (!$resultOrder) { if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order');
return true; return true;
} }
return true; return true;
} }
return; return true;
} }
} }

View File

@ -0,0 +1,31 @@
<?php
define("NO_KEEP_STATISTIC", true);
require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php');
$GLOBALS['APPLICATION']->RestartBuffer();
$moduleId = 'intaro.retailcrm';
$historyTime = 'history_time';
$idOrderCRM = (int)$_REQUEST['idOrderCRM'];
if (CModule::IncludeModule($moduleId) && $idOrderCRM && $idOrderCRM > 0) {
$timeBd = COption::GetOptionString($moduleId, $historyTime, 0);
$nowDate = date('Y-m-d H:i:s');
if (!empty($timeBd)) {
$timeBdObj = new \DateTime($timeBd);
$newTimeBdObj = $timeBdObj->modify('+5 min');
$nowDateObj = new \DateTime($nowDate);
//If there is a record, but it is older than 5 minutes, overwrite
if ($newTimeBdObj < $nowDateObj) {
COption::SetOptionString($moduleId, $historyTime, $nowDate);
//call history
RCrmActions::orderAgent();
COption::RemoveOption($moduleId, $historyTime);
}
} else {
COption::SetOptionString($moduleId, $historyTime, $nowDate);
//call history
RCrmActions::orderAgent();
COption::RemoveOption($moduleId, $historyTime);
}
}

View File

@ -29,14 +29,17 @@ class RetailCrmHistory
{ {
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found');
return false; return false;
} }
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'sale', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'sale', 'module not found');
return false; return false;
} }
if (!CModule::IncludeModule("catalog")) { if (!CModule::IncludeModule("catalog")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'catalog', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'catalog', 'module not found');
return false; return false;
} }
@ -47,34 +50,26 @@ class RetailCrmHistory
$historyFilter = array(); $historyFilter = array();
$historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY); $historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY);
if ($historyStart && $historyStart > 0) { if ($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart; $historyFilter['sinceId'] = $historyStart;
} }
while (true) { while (true) {
try { $customerHistory = RCrmActions::apiMethod($api, 'ordersHistory', __METHOD__, $historyFilter);
$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(); $customerH = isset($customerHistory['history']) ? $customerHistory['history'] : array();
$log = new Logger(); $log = new Logger();
$log->write($customerH, 'customerHistory'); $log->write($customerH, 'customerHistory');
if(count($customerH) == 0){
if (count($customerH) == 0) {
if ($customerHistory['history']['totalPageCount'] > $customerHistory['history']['currentPage']) {
$historyFilter['page'] = $customerHistory['history']['currentPage'] + 1;
continue;
}
return true; return true;
} }
@ -89,6 +84,10 @@ class RetailCrmHistory
$newResCustomer = retailCrmBeforeCustomerSave($customer); $newResCustomer = retailCrmBeforeCustomerSave($customer);
if (is_array($newResCustomer) && !empty($newResCustomer)) { if (is_array($newResCustomer) && !empty($newResCustomer)) {
$customer = $newResCustomer; $customer = $newResCustomer;
} elseif ($newResCustomer === false) {
RCrmActions::eventLog('RetailCrmHistory::customerHistory', 'retailCrmBeforeCustomerSave()', 'UserCrmId = ' . $customer['id'] . '. Sending canceled after retailCrmBeforeCustomerSave');
continue;
} }
} }
@ -137,23 +136,10 @@ class RetailCrmHistory
continue; continue;
} }
try { if(RCrmActions::apiMethod($api, 'customersFixExternalIds', __METHOD__, array(array('id' => $customer['id'], 'externalId' => $registeredUserID))) == false) {
$api->customersFixExternalIds(array(array('id' => $customer['id'], 'externalId' => $registeredUserID))); continue;
} 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; $customer['externalId'] = $registeredUserID;
@ -171,9 +157,9 @@ class RetailCrmHistory
$arUser["SECOND_NAME"] = $customer['patronymic'] ? RCrmActions::fromJSON($customer['patronymic']) : ''; $arUser["SECOND_NAME"] = $customer['patronymic'] ? RCrmActions::fromJSON($customer['patronymic']) : '';
} }
if (array_key_exists('email', $customer)) { // if (array_key_exists('email', $customer)) {
$arUser["EMAIL"] = $customer['email'] ? RCrmActions::fromJSON($customer['email']) : ''; // $arUser["EMAIL"] = $customer['email'] ? RCrmActions::fromJSON($customer['email']) : '';
} // }
if (isset($customer['phones'])) { if (isset($customer['phones'])) {
$user = CUser::GetList(($by="ID"), ($order="desc"), array('ID' => $customer['externalId']), array('FIELDS' => array('PERSONAL_PHONE', 'PERSONAL_MOBILE')))->fetch(); $user = CUser::GetList(($by="ID"), ($order="desc"), array('ID' => $customer['externalId']), array('FIELDS' => array('PERSONAL_PHONE', 'PERSONAL_MOBILE')))->fetch();
@ -222,14 +208,14 @@ class RetailCrmHistory
$GLOBALS['RETAIL_CRM_HISTORY'] = false; $GLOBALS['RETAIL_CRM_HISTORY'] = false;
//запоминаем номер последнего изменения //last id
$end = array_pop($customerH); $end = array_pop($customerH);
COption::SetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY, $end['id']); COption::SetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY, $end['id']);
if ($customerHistory['pagination']['totalPageCount'] == 1) { if ($customerHistory['pagination']['totalPageCount'] == 1) {
return true; return true;
} }
//новый фильтр для истории //new filter
$historyFilter['sinceId'] = $end['id']; $historyFilter['sinceId'] = $end['id'];
} }
} }
@ -242,14 +228,17 @@ class RetailCrmHistory
} }
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found');
return false; return false;
} }
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'sale', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'sale', 'module not found');
return false; return false;
} }
if (!CModule::IncludeModule("catalog")) { if (!CModule::IncludeModule("catalog")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'catalog', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'catalog', 'module not found');
return false; return false;
} }
@ -278,29 +267,20 @@ class RetailCrmHistory
} }
while (true) { while (true) {
try { $orderHistory = RCrmActions::apiMethod($api, 'ordersHistory', __METHOD__, $historyFilter);
$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(); $orderH = isset($orderHistory['history']) ? $orderHistory['history'] : array();
$log = new Logger(); $log = new Logger();
$log->write($orderH, 'orderHistory'); $log->write($orderH, 'orderHistory');
if (count($orderH) == 0) { if (count($orderH) == 0) {
if ($orderHistory['history']['totalPageCount'] > $orderHistory['history']['currentPage']) {
$historyFilter['page'] = $orderHistory['history']['currentPage'] + 1;
continue;
}
return true; return true;
} }
@ -308,12 +288,16 @@ class RetailCrmHistory
$GLOBALS['RETAIL_CRM_HISTORY'] = true; $GLOBALS['RETAIL_CRM_HISTORY'] = true;
//обработка заказа //orders with changes
foreach ($orders as $order) { foreach ($orders as $order) {
if (function_exists('retailCrmBeforeOrderSave')) { if (function_exists('retailCrmBeforeOrderSave')) {
$newResOrder = retailCrmBeforeOrderSave($order); $newResOrder = retailCrmBeforeOrderSave($order);
if (is_array($newResOrder) && !empty($newResOrder)) { if (is_array($newResOrder) && !empty($newResOrder)) {
$order = $newResOrder; $order = $newResOrder;
} elseif ($newResOrder === false) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'retailCrmBeforeOrderSave()', 'OrderCrmId = ' . $order['id'] . '. Sending canceled after retailCrmBeforeOrderSave');
continue;
} }
} }
@ -370,62 +354,40 @@ class RetailCrmHistory
if ($order['customer']['phones'][1]) { if ($order['customer']['phones'][1]) {
$arFields['PERSONAL_MOBILE'] = $order['customer']['phones'][1]; $arFields['PERSONAL_MOBILE'] = $order['customer']['phones'][1];
} }
$registeredUserID = $newUser->Add($arFields); $registeredUserID = $newUser->Add($arFields);
if ($registeredUserID === false) { if ($registeredUserID === false) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'CUser::Register', 'Error register user'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'CUser::Register', 'Error register user');
continue; continue;
} }
try { if(RCrmActions::apiMethod($api, 'customersFixExternalIds', __METHOD__, array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))) == false) {
$api->customersFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID))); continue;
} 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; $order['customer']['externalId'] = $registeredUserID;
} }
if ($optionsSitesList) { if (isset($optionsSitesList)) {
$site = array_search($order['site'], $optionsSitesList); $site = array_search($order['site'], $optionsSitesList);
} else { } else {
$site = CSite::GetDefSite(); $site = CSite::GetDefSite();
} }
if (empty($site)) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::create', 'Site = ' . $order['site'] . ' not found in setting. Order crm id=' . $order['id']);
continue;
}
$newOrder = Bitrix\Sale\Order::create($site, $order['customer']['externalId']); $newOrder = Bitrix\Sale\Order::create($site, $order['customer']['externalId']);
$newOrder = $newOrder->save(); $newOrder->save();
$externalId = $newOrder->getId(); $externalId = $newOrder->getId();
if (isset($externalId)) { if (isset($externalId)) {
try { if(RCrmActions::apiMethod($api, 'ordersFixExternalIds', __METHOD__, array(array('id' => $order['id'], 'externalId' => $externalId))) == false){
$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; continue;
} }
} else { } else {
@ -436,20 +398,43 @@ class RetailCrmHistory
if (isset($order['externalId']) && $order['externalId']) { if (isset($order['externalId']) && $order['externalId']) {
$itemUpdate = false; $itemUpdate = false;
$newOrder = Bitrix\Sale\Order::load($order['externalId']); try {
$newOrder = Bitrix\Sale\Order::load($order['externalId']);
} catch (Bitrix\Main\ArgumentNullException $e) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::load', $e->getMessage() . ': ' . $order['externalId']);
continue;
}
if (!$newOrder instanceof \Bitrix\Sale\Order) { if (!$newOrder instanceof \Bitrix\Sale\Order) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::load', 'Error order load id=' . $order['externalId']); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::load', 'Error order load id=' . $order['externalId']);
continue; continue;
} }
if ($optionsSitesList) { if ($optionsSitesList) {
$site = array_search($order['site'], $optionsSitesList); $site = array_search($order['site'], $optionsSitesList);
} else { } else {
$site = CSite::GetDefSite(); $site = CSite::GetDefSite();
} }
if (empty($site)) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::edit', 'Site = ' . $order['site'] . ' not found in setting. Order id=' . $order['externalId']);
continue;
}
if ($optionsOrderNumbers == 'Y' && isset($order['number'])) { if ($optionsOrderNumbers == 'Y' && isset($order['number'])) {
$searchFilter = array(
'filter' => array('ACCOUNT_NUMBER' => $order['number']),
'select' => array('ID'),
);
$searchOrder = reset(Bitrix\Sale\Order::loadByFilter($searchFilter));
if (!empty($searchOrder)) {
if ($searchOrder->getId() != $order['externalId']) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'setField("ACCOUNT_NUMBER")', 'Error order load id=' . $order['externalId']) . '. Number ' . $order['number'] . ' already exists';
continue;
}
}
$newOrder->setField('ACCOUNT_NUMBER', $order['number']); $newOrder->setField('ACCOUNT_NUMBER', $order['number']);
} }
@ -484,10 +469,11 @@ class RetailCrmHistory
} }
} }
if (array_key_exists('statusComment', $order)) { if (array_key_exists('statusComment', $order)) {
self::setProp($newOrder, RCrmActions::fromJSON($order['statusComment']), 'REASON_CANCELED'); self::setProp($newOrder, RCrmActions::fromJSON($order['statusComment']), 'REASON_CANCELED');
} }
//props
$propertyCollection = $newOrder->getPropertyCollection(); $propertyCollection = $newOrder->getPropertyCollection();
$propertyCollectionArr = $propertyCollection->getArray(); $propertyCollectionArr = $propertyCollection->getArray();
$nProps = array(); $nProps = array();
@ -500,20 +486,13 @@ class RetailCrmHistory
} }
$propertyCollectionArr['properties'] = $nProps; $propertyCollectionArr['properties'] = $nProps;
if ($propsRemove) {//удаляем старые свойства if ($propsRemove) {//delete props
foreach ($propertyCollectionArr['properties'] as $orderProp) { foreach ($propertyCollectionArr['properties'] as $orderProp) {
$somePropValue = $propertyCollection->getItemByOrderPropertyId($orderProp['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($orderProp['ID']);
self::setProp($somePropValue); self::setProp($somePropValue);
} }
$orderCrm = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
try {
$orderCrm = $api->ordersGet($order['id'], 'id', $order['site']);
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersGet0::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
}
$orderDump = $order; $orderDump = $order;
$order = $orderCrm['order']; $order = $orderCrm['order'];
} }
@ -562,22 +541,28 @@ class RetailCrmHistory
} }
} elseif (array_key_exists($key, $order['delivery']['address'])) { } elseif (array_key_exists($key, $order['delivery']['address'])) {
if ($propsKey[$orderProp]['TYPE'] == 'LOCATION') { if ($propsKey[$orderProp]['TYPE'] == 'LOCATION') {
$order['delivery']['address'][$key] = trim($order['delivery']['address'][$key]);
if(!empty($order['delivery']['address'][$key])){ if(!empty($order['delivery']['address'][$key])){
$parameters = array(); $parameters = array();
$loc = explode('.', $order['delivery']['address'][$key]); $loc = explode('.', $order['delivery']['address'][$key]);
if (count($loc) == 1) { if (count($loc) == 1) {
$parameters['filter']['NAME'] = RCrmActions::fromJSON(trim($loc[0])); $parameters['filter']['PHRASE'] = RCrmActions::fromJSON(trim($loc[0]));
} elseif (count($loc) == 2) { } elseif (count($loc) == 2) {
$parameters['filter']['NAME'] = RCrmActions::fromJSON(trim($loc[1])); $parameters['filter']['PHRASE'] = RCrmActions::fromJSON(trim($loc[1]));
} else{ } else{
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'RetailCrmHistory::setProp', 'Error location ' . $order['delivery']['address'][$key] . ' not found add in order id=' . $order['externalId']); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'RetailCrmHistory::setProp', 'Error location. ' . $order['delivery']['address'][$key] . ' not found add in order id=' . $order['externalId']);
continue; continue;
} }
$parameters['filter']['LANGUAGE_ID'] = 'ru'; $parameters['filter']['NAME.LANGUAGE_ID'] = 'ru';
$location = \Bitrix\Sale\Location\LocationTable::getListFast($parameters)->fetch(); $location = \Bitrix\Sale\Location\Search\Finder::find($parameters, array('USE_INDEX' => false, 'USE_ORM' => false))->fetch();
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, $location['CODE']);
} else {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'RetailCrmHistory::setProp', 'Error location. ' . $order['delivery']['address'][$key] . ' is empty in order id=' . $order['externalId']);
continue;
} }
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, $location['CODE']);
} else { } else {
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, RCrmActions::fromJSON($order['delivery']['address'][$key])); self::setProp($somePropValue, RCrmActions::fromJSON($order['delivery']['address'][$key]));
@ -585,6 +570,7 @@ class RetailCrmHistory
} }
} }
} }
//optionsLegalDetails //optionsLegalDetails
if ($optionsLegalDetails[$personType]) { if ($optionsLegalDetails[$personType]) {
foreach ($optionsLegalDetails[$personType] as $key => $orderProp) { foreach ($optionsLegalDetails[$personType] as $key => $orderProp) {
@ -646,14 +632,7 @@ class RetailCrmHistory
if (array_key_exists('discount', $product) || array_key_exists('discountPercent', $product)) { if (array_key_exists('discount', $product) || array_key_exists('discountPercent', $product)) {
if (!isset($orderCrm)) { if (!isset($orderCrm)) {
try { $orderCrm = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
$orderCrm = $api->ordersGet($order['id'], 'id', $order['site']);
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersGet1::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
}
} }
if (isset($orderCrm['order']['items'])) { if (isset($orderCrm['order']['items'])) {
foreach ($orderCrm['order']['items'] as $itemCrm) { foreach ($orderCrm['order']['items'] as $itemCrm) {
@ -663,6 +642,7 @@ class RetailCrmHistory
} }
} }
} }
if (isset($itemCost) && $itemCost > 0) { if (isset($itemCost) && $itemCost > 0) {
$item->setField('CUSTOM_PRICE', 'Y'); $item->setField('CUSTOM_PRICE', 'Y');
$item->setField('PRICE', $itemCost); $item->setField('PRICE', $itemCost);
@ -694,27 +674,22 @@ class RetailCrmHistory
//payment //payment
if (array_key_exists('paymentType', $order)) { if (array_key_exists('paymentType', $order)) {
self::paySystemUpdate($order, $optionsPayTypes); self::paySystemUpdate($order, $optionsPayTypes, $newOrder->getField('ACCOUNT_NUMBER'));
} }
//delivery //delivery
if (array_key_exists('code', $order['delivery'])) { if (array_key_exists('code', $order['delivery'])) {
$itemUpdate = true; $itemUpdate = true;
//если пусто, удаляем, если нет, update или add //delete empty
if (!isset($orderCrm)) { if (!isset($orderCrm)) {
try { $orderCrm = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
$orderCrm = $api->ordersGet($order['id'], 'id', $order['site']); }
} catch (\RetailCrm\Exception\CurlException $e) { if ($orderCrm) {
RCrmActions::eventLog( self::shipmentUpdate($orderCrm['order'], $optionsDelivTypes, $newOrder->getField('ACCOUNT_NUMBER'));
'RetailCrmHistory::orderHistory', 'RetailCrm\RestApi::ordersGet2::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
}
} }
self::shipmentUpdate($orderCrm['order'], $optionsDelivTypes);
} }
if (isset($orderCrm)) { if (isset($orderCrm)) {
unset($orderCrm); unset($orderCrm);
} }
//delivery cost //delivery cost
@ -727,7 +702,7 @@ class RetailCrmHistory
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\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('PRICE_DELIVERY' => $order['delivery']['cost']));
} }
Bitrix\Sale\OrderTable::update($order['externalId'], array('MARKED' => 'N', 'EMP_MARKED_ID' => '', 'REASON_MARKED' => '')); Bitrix\Sale\OrderTable::update($order['externalId'], array('MARKED' => 'N', 'EMP_MARKED_ID' => '', 'REASON_MARKED' => ''));
@ -744,17 +719,16 @@ class RetailCrmHistory
$GLOBALS['RETAIL_CRM_HISTORY'] = false; $GLOBALS['RETAIL_CRM_HISTORY'] = false;
//запоминаем номер последнего изменения //end id
$end = array_pop($orderH); $end = array_pop($orderH);
COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY, $end['id']); COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY, $end['id']);
if ($orderHistory['pagination']['totalPageCount'] == 1) { if ($orderHistory['pagination']['totalPageCount'] == 1) {
return true; return true;
} }
//новый фильтр для истории //new filter
$historyFilter['sinceId'] = $end['id']; $historyFilter['sinceId'] = $end['id'];
} }
} }
public static function assemblyCustomer($customerHistory) public static function assemblyCustomer($customerHistory)
@ -892,18 +866,24 @@ class RetailCrmHistory
return $orders; return $orders;
} }
public static function shipmentUpdate($orderCrm, $optionsDelivTypes) public static function shipmentUpdate($orderCrm, $optionsDelivTypes, $accountNumber = '')
{ {
if (strlen($accountNumber) < 1) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'shipmentUpdate', 'ACCOUNT_NUMBER not found');
return false;
}
if (isset($orderCrm['delivery']['code'])) { if (isset($orderCrm['delivery']['code'])) {
$crmCode = $orderCrm['delivery']['code']; $crmCode = $orderCrm['delivery']['code'];
if (isset($orderCrm['delivery']['data']['deliveryType'])) { if (isset($orderCrm['delivery']['data']['deliveryType'])) {
$crmService = $orderCrm['delivery']['data']['deliveryType']; $crmService = $orderCrm['delivery']['data']['deliveryType'];
} elseif (isset($orderCrm['delivery']['service'])) { } elseif (isset($orderCrm['delivery']['service'])) {
$crmService = $orderCrm['delivery']['service']; $crmService = $orderCrm['delivery']['service']['code'];
} }
//подбираем код битриксового сервиса //select bitrix service code
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
foreach ($arDeliveryServiceAll as $arDeliveryService) { foreach ($arDeliveryServiceAll as $arDeliveryService) {
$arDeliveryCode[$arDeliveryService['CODE']] = $arDeliveryService['ID']; $arDeliveryCode[$arDeliveryService['CODE']] = $arDeliveryService['ID'];
@ -912,16 +892,20 @@ class RetailCrmHistory
$dCode = $arDeliveryService['CODE'] . ':' . $crmService; $dCode = $arDeliveryService['CODE'] . ':' . $crmService;
} }
} }
//будем менять доставку на этот id //We will change delivery to this id
if ($crmService && $arDeliveryCode[$dCode]) { if ($crmService && $arDeliveryCode[$dCode]) {
$nowDelivery = $arDeliveryCode[$dCode]; $nowDelivery = $arDeliveryCode[$dCode];
} else { } elseif (!empty($optionsDelivTypes[$crmCode])) {
$nowDelivery = $optionsDelivTypes[$crmCode]; $nowDelivery = $optionsDelivTypes[$crmCode];
} else {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'shipmentUpdate', 'Delivery ' . $crmCode . ' not found in options');
return false;
} }
//найти текущую доставку в заказе //Find the current delivery in the order
$cnt = Bitrix\Sale\Internals\ShipmentTable::getCount(array('ORDER_ID' => $orderCrm['externalId'])); $cnt = Bitrix\Sale\Internals\ShipmentTable::getCount(array('ORDER_ID' => $orderCrm['externalId']));
if ($cnt > 0) {//обновляем if ($cnt > 0) {//update
$obDeliverys = \Bitrix\Sale\Internals\ShipmentTable::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']), $obDeliverys = \Bitrix\Sale\Internals\ShipmentTable::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']),
'order' => array('ID'))); 'order' => array('ID')));
while ($arDelivery = $obDeliverys->fetch()) { while ($arDelivery = $obDeliverys->fetch()) {
@ -930,7 +914,29 @@ class RetailCrmHistory
\Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $nowDelivery, 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME'])); \Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $nowDelivery, 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME']));
} }
} }
} else {//создаем if ($cnt = 1 && $arDelivery['DELIVERY_ID'] == 0) {
$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' => $accountNumber . '/2',
'EXTERNAL_DELIVERY' => 'N',
'UPDATED_1C' => 'N',
'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime()
));
}
} else {//create
\Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery)); \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery));
$shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array( $shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array(
'ORDER_ID' => $orderCrm['externalId'], 'ORDER_ID' => $orderCrm['externalId'],
@ -944,7 +950,7 @@ class RetailCrmHistory
'CANCELED' => 'N', 'CANCELED' => 'N',
'MARKED' => 'N', 'MARKED' => 'N',
'SYSTEM' => 'Y', 'SYSTEM' => 'Y',
'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/1', 'ACCOUNT_NUMBER' => $accountNumber . '/1',
'EXTERNAL_DELIVERY' => 'N', 'EXTERNAL_DELIVERY' => 'N',
'UPDATED_1C' => 'N', 'UPDATED_1C' => 'N',
'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime()
@ -964,21 +970,21 @@ class RetailCrmHistory
'MARKED' => 'N', 'MARKED' => 'N',
'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(),
'SYSTEM' => 'N', 'SYSTEM' => 'N',
'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/2', 'ACCOUNT_NUMBER' => $accountNumber . '/2',
'EXTERNAL_DELIVERY' => 'N', 'EXTERNAL_DELIVERY' => 'N',
'UPDATED_1C' => 'N', 'UPDATED_1C' => 'N',
'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime()
)); ));
} }
} else { } else {
//ищем у заказа на сайте доставки и удаляем/заменяем на без доставки //search for the order on the delivery site and delete / replace with no delivery
$noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
\Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $noOrderId)); \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $noOrderId));
$obDeliverys = Bitrix\Sale\Internals\ShipmentTable::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']), $obDeliverys = Bitrix\Sale\Internals\ShipmentTable::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']),
'order' => array('ID'))); 'order' => array('ID')));
$create = true; $create = true;
while ($arDelivery = $obDeliverys->fetch()) { while ($arDelivery = $obDeliverys->fetch()) {
\Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $noOrderId, 'DELIVERY_NAME' => 'Без доставки')); \Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $noOrderId, 'DELIVERY_NAME' => GetMessage('NO_DELIVERY')));
$create = false; $create = false;
} }
if ($create) { if ($create) {
@ -989,12 +995,12 @@ class RetailCrmHistory
'ALLOW_DELIVERY' => 'N', 'ALLOW_DELIVERY' => 'N',
'DEDUCTED' => 'N', 'DEDUCTED' => 'N',
'RESERVED' => 'N', 'RESERVED' => 'N',
'DELIVERY_ID' => $nowDelivery, 'DELIVERY_ID' => $noOrderId,
'DELIVERY_NAME' => $nowDelivery[$nowDelivery]['NAME'], 'DELIVERY_NAME' => GetMessage('NO_DELIVERY'),
'CANCELED' => 'N', 'CANCELED' => 'N',
'MARKED' => 'N', 'MARKED' => 'N',
'SYSTEM' => 'Y', 'SYSTEM' => 'Y',
'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/1', 'ACCOUNT_NUMBER' => $accountNumber . '/1',
'EXTERNAL_DELIVERY' => 'N', 'EXTERNAL_DELIVERY' => 'N',
'UPDATED_1C' => 'N', 'UPDATED_1C' => 'N',
'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime()
@ -1008,13 +1014,13 @@ class RetailCrmHistory
'ALLOW_DELIVERY' => 'N', 'ALLOW_DELIVERY' => 'N',
'DEDUCTED' => 'N', 'DEDUCTED' => 'N',
'RESERVED' => 'N', 'RESERVED' => 'N',
'DELIVERY_ID' => $nowDelivery, 'DELIVERY_ID' => $noOrderId,
'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME'], 'DELIVERY_NAME' => GetMessage('NO_DELIVERY'),
'CANCELED' => 'N', 'CANCELED' => 'N',
'MARKED' => 'N', 'MARKED' => 'N',
'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(),
'SYSTEM' => 'N', 'SYSTEM' => 'N',
'ACCOUNT_NUMBER' => $orderCrm['externalId'] . '/2', 'ACCOUNT_NUMBER' => $accountNumber . '/2',
'EXTERNAL_DELIVERY' => 'N', 'EXTERNAL_DELIVERY' => 'N',
'UPDATED_1C' => 'N', 'UPDATED_1C' => 'N',
'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime()
@ -1031,6 +1037,7 @@ class RetailCrmHistory
'filter' => array('ORDER_ID' => $orderId), 'filter' => array('ORDER_ID' => $orderId),
'select' => array('ID', 'QUANTITY') 'select' => array('ID', 'QUANTITY')
)); ));
$basketItems = array(); $basketItems = array();
while ($basketItem = $orderBasket->fetch()) { while ($basketItem = $orderBasket->fetch()) {
$basketItems[] = $basketItem; $basketItems[] = $basketItem;
@ -1041,6 +1048,7 @@ class RetailCrmHistory
'filter' => array('ORDER_ID' => $orderId), 'filter' => array('ORDER_ID' => $orderId),
'select' => array('ID') 'select' => array('ID')
)); ));
$shipmentItems = array(); $shipmentItems = array();
while ($arShipment = $obShipments->fetch()) { while ($arShipment = $obShipments->fetch()) {
$dlvBaslet = \Bitrix\Sale\Internals\ShipmentItemTable::getList(array( $dlvBaslet = \Bitrix\Sale\Internals\ShipmentItemTable::getList(array(
@ -1058,13 +1066,13 @@ class RetailCrmHistory
$found = false; $found = false;
foreach ($arShipmentItems as $elShipmentItem) { foreach ($arShipmentItems as $elShipmentItem) {
if (!in_array($elShipmentItem['BASKET_ID'], $bItems)) { if (!in_array($elShipmentItem['BASKET_ID'], $bItems)) {
//удаляем элемент //delete the element
\Bitrix\Sale\Internals\ShipmentItemTable::delete($elShipmentItem['ID']); \Bitrix\Sale\Internals\ShipmentItemTable::delete($elShipmentItem['ID']);
} }
if ($elShipmentItem['BASKET_ID'] == $basketItem['ID']) { if ($elShipmentItem['BASKET_ID'] == $basketItem['ID']) {
//нашли //found
$found = true; $found = true;
//проверяем кол-во, если нужно, обновляем //update quantity
if ($elShipmentItem['QUANTITY'] != $basketItem['QUANTITY']) { if ($elShipmentItem['QUANTITY'] != $basketItem['QUANTITY']) {
\Bitrix\Sale\Internals\ShipmentItemTable::update($elShipmentItem['ID'], array('QUANTITY' => $basketItem['QUANTITY'])); \Bitrix\Sale\Internals\ShipmentItemTable::update($elShipmentItem['ID'], array('QUANTITY' => $basketItem['QUANTITY']));
} }
@ -1072,7 +1080,7 @@ class RetailCrmHistory
} }
} }
if (!$found) { if (!$found) {
//добавляем //create
\Bitrix\Sale\Internals\ShipmentItemTable::add(array( \Bitrix\Sale\Internals\ShipmentItemTable::add(array(
'ORDER_DELIVERY_ID' => $key, 'ORDER_DELIVERY_ID' => $key,
'BASKET_ID' => $basketItem['ID'], 'BASKET_ID' => $basketItem['ID'],
@ -1085,8 +1093,14 @@ class RetailCrmHistory
} }
} }
public static function paySystemUpdate($order, $optionsPayment) public static function paySystemUpdate($order, $optionsPayment, $accountNumber = '')
{ {
if (strlen($accountNumber) < 1) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'paySystemUpdate', 'ACCOUNT_NUMBER not found');
return false;
}
if (isset($order['paymentType'])) { if (isset($order['paymentType'])) {
if ($optionsPayment[$order['paymentType']]) { if ($optionsPayment[$order['paymentType']]) {
$paymentList = RCrmActions::PaymentList(); $paymentList = RCrmActions::PaymentList();
@ -1103,7 +1117,7 @@ class RetailCrmHistory
'filter' => array('ORDER_ID' => $order['externalId']), 'filter' => array('ORDER_ID' => $order['externalId']),
'order' => array('ID') 'order' => array('ID')
))->fetch(); ))->fetch();
if ($payment) {//если уже существует, update if ($payment) {//update payment
\Bitrix\Sale\Internals\PaymentTable::update($payment['ID'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']], 'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]], 'SUM' => $order['summ'])); \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 { } else {
\Bitrix\Sale\Internals\PaymentTable::add(array( \Bitrix\Sale\Internals\PaymentTable::add(array(
@ -1114,17 +1128,16 @@ class RetailCrmHistory
'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(),
'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]], 'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]],
'IS_RETURN' => 'N', 'IS_RETURN' => 'N',
'ACCOUNT_NUMBER' => $order['externalId'] . '/1', 'ACCOUNT_NUMBER' => $accountNumber . '/1',
'PRICE_COD' => '0.00', 'PRICE_COD' => '0.00',
'EXTERNAL_PAYMENT' => 'N', 'EXTERNAL_PAYMENT' => 'N',
'UPDATED_1C' => 'N' 'UPDATED_1C' => 'N'
)); ));
} }
//запись в историю } else {
} else {//ошибка, нет такой активной платежной системы
RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in order id=' . $order['externalId']); RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in order id=' . $order['externalId']);
} }
} else {//ошибка, возможно платежная система не сопоставлена } else {
RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in option in order id=' . $order['externalId']);; RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in option in order id=' . $order['externalId']);;
} }
} else { } else {
@ -1137,7 +1150,6 @@ class RetailCrmHistory
if ($payment['ID']) { if ($payment['ID']) {
\Bitrix\Sale\Internals\PaymentTable::delete($payment['ID']); \Bitrix\Sale\Internals\PaymentTable::delete($payment['ID']);
} }
//запись в историю
} }
} }
@ -1153,12 +1165,14 @@ class RetailCrmHistory
public static function removeEmpty($inputArray) public static function removeEmpty($inputArray)
{ {
$outputArray = array(); $outputArray = array();
if (!empty($inputArray)) { if (!empty($inputArray)) {
foreach ($inputArray as $key => $element) { foreach ($inputArray as $key => $element) {
if (!empty($element) || $element === 0 || $element === '0') { if (!empty($element) || $element === 0 || $element === '0') {
if (is_array($element)) { if (is_array($element)) {
$element = self::removeEmpty($element); $element = self::removeEmpty($element);
} }
$outputArray[$key] = $element; $outputArray[$key] = $element;
} }
} }
@ -1169,7 +1183,7 @@ class RetailCrmHistory
public static function setProp($obj, $value = '', $prop) public static function setProp($obj, $value = '', $prop)
{ {
if (!isset($obj)) { if (!isset($obj)) {
return false; return false;
} }
if ($prop) { if ($prop) {
@ -1185,21 +1199,22 @@ class RetailCrmHistory
public static function getExistsItem($basket, $moduleId, $productId) public static function getExistsItem($basket, $moduleId, $productId)
{ {
foreach ($basket as $basketItem) { foreach ($basket as $basketItem) {
$itemExists = ($basketItem->getField('PRODUCT_ID') == $productId && $basketItem->getField('MODULE') == $moduleId); $itemExists = ($basketItem->getField('PRODUCT_ID') == $productId && $basketItem->getField('MODULE') == $moduleId);
if ($itemExists) { if ($itemExists) {
return $basketItem; return $basketItem;
} }
} }
return false; return false;
} }
public static function getInfoElement($offerId) public static function getInfoElement($offerId)
{ {
$elementInfo = CIBlockElement::GetByID($offerId)->fetch(); $elementInfo = CIBlockElement::GetByID($offerId)->fetch();
$url = CAllIBlock::ReplaceDetailUrl($elementInfo['DETAIL_PAGE_URL'], $elementInfo, false, 'E'); $url = CAllIBlock::ReplaceDetailUrl($elementInfo['DETAIL_PAGE_URL'], $elementInfo, false, 'E');
$info = array( $info = array(
'NAME' => $elementInfo['NAME'], 'NAME' => $elementInfo['NAME'],
'URL' => $url, 'URL' => $url,
@ -1213,24 +1228,27 @@ class RetailUser extends CUser
{ {
public function GetID() public function GetID()
{ {
$rsUser = CUser::GetList(($by='ID'), ($order='DESC'), array('LOGIN' => 'retailcrm%')); $rsUser = CUser::GetList(($by = 'ID'), ($order = 'DESC'), array('LOGIN' => 'retailcrm%'));
if ($arUser = $rsUser->Fetch()) { if ($arUser = $rsUser->Fetch()) {
return $arUser['ID']; return $arUser['ID'];
} else { } else {
$retailUser = new CUser; $retailUser = new CUser;
$userPassword = uniqid(); $userPassword = uniqid();
$arFields = array( $arFields = array(
"NAME" => 'retailcrm', "NAME" => 'retailcrm',
"LAST_NAME" => 'retailcrm', "LAST_NAME" => 'retailcrm',
"EMAIL" => 'retailcrm@retailcrm.com', "EMAIL" => 'retailcrm@retailcrm.com',
"LOGIN" => 'retailcrm', "LOGIN" => 'retailcrm',
"LID" => "ru", "LID" => "ru",
"ACTIVE" => "Y", "ACTIVE" => "Y",
"GROUP_ID" => array(2), "GROUP_ID" => array(2),
"PASSWORD" => $userPassword, "PASSWORD" => $userPassword,
"CONFIRM_PASSWORD" => $userPassword "CONFIRM_PASSWORD" => $userPassword
); );
$id = $retailUser->Add($arFields); $id = $retailUser->Add($arFields);
if (!$id) { if (!$id) {
return null; return null;
} else { } else {

File diff suppressed because it is too large Load Diff

View File

@ -45,7 +45,7 @@ class RetailCrmICML
'g' => 'g', 'g' => 'g',
'kg' => 'g', 'kg' => 'g',
); );
protected $measure = array ( protected $measure = array (
'pc. 1' => 'pc', 'pc. 1' => 'pc',
'm' => 'm', 'm' => 'm',
@ -55,59 +55,59 @@ class RetailCrmICML
public function Load() public function Load()
{ {
global $USER; global $USER;
if (!isset($_SESSION["SESS_AUTH"]["USER_ID"]) || !$_SESSION["SESS_AUTH"]["USER_ID"]) { if (!isset($_SESSION["SESS_AUTH"]["USER_ID"]) || !$_SESSION["SESS_AUTH"]["USER_ID"]) {
$USER = new CUser; $USER = new CUser;
} }
$this->isLogged = true; $this->isLogged = true;
$defaultSite = CSite::GetList($by = "def", $order = "desc", array('DEF' => 'Y'))->Fetch(); $defaultSite = CSite::GetList($by = "def", $order = "desc", array('DEF' => 'Y'))->Fetch();
$this->encodingDefault = $defaultSite["CHARSET"]; $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'); $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://';
}
if ($this->isLogged) { $this->PrepareSettings();
$this->fpLog = $this->PrepareFile($this->logFile);
$this->WriteLog("Start Loading");
}
$this->PreWriteCatalog(); $this->fp = $this->PrepareFile($this->filename. '.tmp');
$categories = $this->GetCategories(); if ($this->isLogged) {
$this->fpLog = $this->PrepareFile($this->logFile);
$this->WriteLog("Start Loading");
}
$this->WriteCategories($categories); $this->PreWriteCatalog();
$this->PreWriteOffers(); $categories = $this->GetCategories();
$this->BuildOffers($categories);
$this->PostWriteOffers();
$this->PostWriteCatalog(); $this->WriteCategories($categories);
if ($this->isLogged) { $this->PreWriteOffers();
$this->WriteLog("Loading was ended successfully (peek memory usage: " . memory_get_peak_usage() . ")"); $this->BuildOffers($categories);
} $this->PostWriteOffers();
$this->CloseFile($this->fp); $this->PostWriteCatalog();
$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; 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;
} }
@ -136,49 +136,48 @@ class RetailCrmICML
protected function PrepareFile($filename) protected function PrepareFile($filename)
{ {
$fullFilename = $_SERVER["DOCUMENT_ROOT"] . $filename; $fullFilename = $_SERVER["DOCUMENT_ROOT"] . $filename;
CheckDirPath($fullFilename); CheckDirPath($fullFilename);
if ($fp = @fopen($fullFilename, "w")){ if ($fp = @fopen($fullFilename, "w")){
return $fp; return $fp;
} else { } else {
return false; return false;
} }
} }
protected function PreWriteCatalog() protected function PreWriteCatalog()
{ {
@fwrite($this->fp, "<yml_catalog date=\"" . $this->PrepareValue(Date("Y-m-d H:i:s")) . "\">\n @fwrite($this->fp, "<yml_catalog date=\"" . $this->PrepareValue(Date("Y-m-d H:i:s")) . "\">\n
<shop>\n <shop>\n
<name>" . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."</name>\n <name>" . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."</name>\n
<company>" . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."</company>\n" <company>" . $this->PrepareValue(COption::GetOptionString("main", "site_name", ""))."</company>\n"
); );
} }
protected function WriteCategories($categories) protected function WriteCategories($categories)
{ {
$stringCategories = ""; $stringCategories = "";
@fwrite($this->fp, "<categories>\n"); @fwrite($this->fp, "<categories>\n");
foreach ($categories as $category) { foreach ($categories as $category) {
$stringCategories .= $this->BuildCategory($category); $stringCategories .= $this->BuildCategory($category);
} }
@fwrite($this->fp, $stringCategories); @fwrite($this->fp, $stringCategories);
@fwrite($this->fp, "</categories>\n"); @fwrite($this->fp, "</categories>\n");
} }
protected function PreWriteOffers() protected function PreWriteOffers()
{ {
@fwrite($this->fp, "<offers>\n"); @fwrite($this->fp, "<offers>\n");
} }
protected function PostWriteOffers() protected function PostWriteOffers()
{ {
@fwrite($this->fp, "</offers>\n"); @fwrite($this->fp, "</offers>\n");
} }
protected function WriteOffers($offers) protected function WriteOffers($offers)
{ {
@fwrite($this->fp, $offers); @fwrite($this->fp, $offers);
} }
protected function WriteLog($text) protected function WriteLog($text)
@ -190,53 +189,51 @@ class RetailCrmICML
protected function PostWriteCatalog() protected function PostWriteCatalog()
{ {
@fwrite($this->fp, "</shop>\n @fwrite($this->fp, "</shop>\n
</yml_catalog>\n"); </yml_catalog>\n");
} }
protected function CloseFile($fp) protected function CloseFile($fp)
{ {
@fclose($fp); @fclose($fp);
} }
protected function GetCategories() protected function GetCategories()
{ {
$categories = array(); $categories = array();
foreach ($this->iblocks as $id) { foreach ($this->iblocks as $id) {
$filter = array("IBLOCK_ID" => $id); $filter = array("IBLOCK_ID" => $id);
$dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter); $dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter);
$hasCategories = false; $hasCategories = false;
while ($arRes = $dbRes->Fetch()) { while ($arRes = $dbRes->Fetch()) {
$categories[$arRes['ID']] = $arRes; $categories[$arRes['ID']] = $arRes;
$hasCategories = true; $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;
}
} }
if (!$hasCategories) {
return $categories; $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) protected function BuildCategory($arCategory)
{ {
return " return "
<category id=\"" . $this->PrepareValue($arCategory["ID"]) . "\"" <category id=\"" . $this->PrepareValue($arCategory["ID"]) . "\""
. ( intval($arCategory["IBLOCK_SECTION_ID"] ) > 0 ? . ( intval($arCategory["IBLOCK_SECTION_ID"] ) > 0 ?
" parentId=\"" . $this->PrepareValue($arCategory["IBLOCK_SECTION_ID"]) . "\"" " parentId=\"" . $this->PrepareValue($arCategory["IBLOCK_SECTION_ID"]) . "\""
:"") :"")
. ">" . ">"
. $this->PrepareValue($arCategory["NAME"]) . $this->PrepareValue($arCategory["NAME"])
. "</category>\n"; . "</category>\n";
} }
@ -276,7 +273,6 @@ class RetailCrmICML
$arSelectOffer = array( $arSelectOffer = array(
'ID', 'ID',
'ACTIVE',
"NAME", "NAME",
"DETAIL_PAGE_URL", "DETAIL_PAGE_URL",
"DETAIL_PICTURE", "DETAIL_PICTURE",
@ -417,7 +413,7 @@ class RetailCrmICML
$offer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"]; $offer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"];
$offer['PICTURE'] = $product["PICTURE"]; $offer['PICTURE'] = $product["PICTURE"];
$offer['PRODUCT_NAME'] = $product["NAME"]; $offer['PRODUCT_NAME'] = $product["NAME"];
$offer['PRODUCT_ACTIVE'] = $offer["ACTIVE"]; $offer['PRODUCT_ACTIVE'] = $product["ACTIVE"];
$offer['PRICE'] = $offer['CATALOG_PRICE_' . $basePriceId]; $offer['PRICE'] = $offer['CATALOG_PRICE_' . $basePriceId];
$offer['PURCHASE_PRICE'] = $offer['CATALOG_PURCHASING_PRICE']; $offer['PURCHASE_PRICE'] = $offer['CATALOG_PURCHASING_PRICE'];
$offer['QUANTITY'] = $offer["CATALOG_QUANTITY"]; $offer['QUANTITY'] = $offer["CATALOG_QUANTITY"];
@ -553,7 +549,7 @@ class RetailCrmICML
} else { } else {
$offer .= '<unit code="' . $this->PrepareValue($arOffer["MEASURE"]['SYMBOL_INTL']) . '" name="' . $this->PrepareValue($arOffer["MEASURE"]['MEASURE_TITLE']) . '" sym="' . $this->PrepareValue($arOffer["MEASURE"]['SYMBOL_RUS']) . '" />' . "\n"; $offer .= '<unit code="' . $this->PrepareValue($arOffer["MEASURE"]['SYMBOL_INTL']) . '" name="' . $this->PrepareValue($arOffer["MEASURE"]['MEASURE_TITLE']) . '" sym="' . $this->PrepareValue($arOffer["MEASURE"]['SYMBOL_RUS']) . '" />' . "\n";
} }
} }
$offer.= "</offer>\n"; $offer.= "</offer>\n";

View File

@ -0,0 +1,163 @@
<?php
IncludeModuleLangFile(__FILE__);
class RetailCrmInventories
{
public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_API_HOST_OPTION = 'api_host';
public static $CRM_API_KEY_OPTION = 'api_key';
public static $CRM_INVENTORIES_UPLOAD = 'inventories_upload';
public static $CRM_STORES = 'stores';
public static $CRM_SHOPS = 'shops';
public static $CRM_IBLOCKS_INVENTORIES = 'iblocks_inventories';
public static $pageSize = 500;
public static function inventoriesUpload()
{
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);
$api = new RetailCrm\ApiClient($api_host, $api_key);
$infoBlocks = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_IBLOCKS_INVENTORIES, 0));
$stores = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_STORES, 0));
$shops = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SHOPS, 0));
try {
$inventoriesList = $api->storesList()->stores;
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'RetailCrmInventories::inventoriesUpload()', 'RetailCrm\ApiClient::storesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
return false;
}
$inventoriesType = array();
if (count($inventoriesList) > 0) {
foreach ($inventoriesList as $inventory) {
$inventoriesType[$inventory['code']] = $inventory['inventoryType'];
}
} else {
RCrmActions::eventLog('RetailCrmInventories::inventoriesUpload()', '$inventoriesList', 'Stores in crm not found');
return false;
}
if (count($shops) == 0) {
RCrmActions::eventLog('RetailCrmInventories::inventoriesUpload()', '$shops', 'No stores selected for download');
return false;
}
if (count($infoBlocks) > 0) {
$log = new Logger();
foreach ($infoBlocks as $id) {
$iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id);
$arNavStatParams = array(
'iNumPage' => 1,
'nPageSize' => self::$pageSize,
);
do {
$dbResProductsIds = CIBlockElement::GetList(array('ID'), array('IBLOCK_ID' => $id), false, $arNavStatParams, array('ID'));
$products = array();
while ($product = $dbResProductsIds->fetch()) {
$products[$product['ID']] = $product;
$products[$product['ID']]['offers'] = array();
}
if (!empty($iblockOffer['IBLOCK_ID'])) {
$arFilterOffer = array(
'IBLOCK_ID' => $iblockOffer['IBLOCK_ID'],
'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] => array_keys($products),
);
$dbResOffers = CIBlockElement::GetList(array('ID'), $arFilterOffer, false, false, array('ID', 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID']));
while ($offer = $dbResOffers->fetch()) {
$products[$offer['PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] . '_VALUE']]['offers'][] = $offer['ID'];
}
}
$elems = array();
foreach ($products as $product) {
if (count($product['offers']) > 0) {
$elems = array_merge($elems, $product['offers']);
} else {
$elems[] = $product['ID'];
}
}
$invUpload = array();
$dbStoreProduct = CCatalogStoreProduct::GetList(
array(),
array('PRODUCT_ID' => $elems, 'STORE_ID' => array_keys($stores)),
false,
false,
array('PRODUCT_ID', 'STORE_ID', 'AMOUNT')
);
while ($arStoreProduct = $dbStoreProduct->Fetch()) {
if (!isset($invUpload[$arStoreProduct['PRODUCT_ID']])) {
$invUpload[$arStoreProduct['PRODUCT_ID']] = array(
'externalId' => $arStoreProduct['PRODUCT_ID']
);
}
$invUpload[$arStoreProduct['PRODUCT_ID']]['stores'][] = array(
'code' => $stores[$arStoreProduct['STORE_ID']],
'available' => self::switchCount($arStoreProduct['AMOUNT'], $inventoriesType[$stores[$arStoreProduct['STORE_ID']]]),
);
}
//for log
$splitedItems = array_chunk($invUpload, 200);
foreach ($splitedItems as $chunk) {
$log->write($chunk, 'inventoriesUpload');
foreach ($shops as $shop) {
RCrmActions::apiMethod($api, 'storeInventoriesUpload', __METHOD__, $chunk, $shop);
time_nanosleep(0, 250000000);
}
}
$arNavStatParams['iNumPage'] = $dbResProductsIds->NavPageNomer + 1;
} while($dbResProductsIds->NavPageNomer < $dbResProductsIds->NavPageCount);
}
} else {
RCrmActions::eventLog('RetailCrmInventories::inventoriesUpload()', '$infoBlocks', 'No iblocks selected');
return false;
}
return 'RetailCrmInventories::inventoriesUpload();';
}
public static function switchCount($val, $type)
{
if ($val < 0) {
$val = 0;
} elseif ($val > 999999) {
$val = 999999;
}
if ($type == 'available' && $val > 0) {
$val = 1;
}
return $val;
}
}

View File

@ -57,32 +57,31 @@ class RetailCrmOrder
$arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']] : '', $arParams['optionsOrderTypes'][$arFields['PERSON_TYPE_ID']] : '',
'status' => isset($arParams['optionsPayStatuses'][$arFields['STATUS_ID']]) ? 'status' => isset($arParams['optionsPayStatuses'][$arFields['STATUS_ID']]) ?
$arParams['optionsPayStatuses'][$arFields['STATUS_ID']] : '', $arParams['optionsPayStatuses'][$arFields['STATUS_ID']] : '',
'statusComment' => $arFields['REASON_CANCELED'],
'customerComment' => $arFields['USER_DESCRIPTION'], 'customerComment' => $arFields['USER_DESCRIPTION'],
'managerComment' => $arFields['COMMENTS'], 'managerComment' => $arFields['COMMENTS'],
'delivery' => array( 'delivery' => array(
'cost' => $arFields['PRICE_DELIVERY'] 'cost' => $arFields['PRICE_DELIVERY']
), ),
); );
if (isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') { if ($send && isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') {
$order['customer']['browserId'] = $_COOKIE['_rc']; $order['customer']['browserId'] = $_COOKIE['_rc'];
} }
$order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']]; $order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']];
//свойства //fields
foreach ($arFields['PROPS']['properties'] as $prop) { foreach ($arFields['PROPS']['properties'] as $prop) {
if ($search = array_search($prop['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) { if ($search = array_search($prop['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) {
$order['contragent'][$search] = $prop['VALUE'][0];//юр данные заказа $order['contragent'][$search] = $prop['VALUE'][0];//legal order data
} elseif ($search = array_search($prop['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) { } elseif ($search = array_search($prop['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) {
$order['customFields'][$search] = $prop['VALUE'][0];//кастомные свойства $order['customFields'][$search] = $prop['VALUE'][0];//custom properties
} elseif ($search = array_search($prop['CODE'], $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']])) {//остальное } elseif ($search = array_search($prop['CODE'], $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']])) {//other
if (in_array($search, array('fio', 'phone', 'email'))) {//фио, телефон, почта if (in_array($search, array('fio', 'phone', 'email'))) {//fio, phone, email
if ($search == 'fio') { if ($search == 'fio') {
$order = array_merge($order, RCrmActions::explodeFIO($prop['VALUE'][0]));//добавляем поля фио $order = array_merge($order, RCrmActions::explodeFIO($prop['VALUE'][0]));//add fio fields
} else { } else {
$order[$search] = $prop['VALUE'][0];//телефон и почта $order[$search] = $prop['VALUE'][0];//phone, email
} }
} else {//остальное - адрес } else {//address
if ($prop['TYPE'] == 'LOCATION' && isset($prop['VALUE'][0]) && $prop['VALUE'][0] != '') { if ($prop['TYPE'] == 'LOCATION' && isset($prop['VALUE'][0]) && $prop['VALUE'][0] != '') {
$arLoc = \Bitrix\Sale\Location\LocationTable::getByCode($prop['VALUE'][0])->fetch(); $arLoc = \Bitrix\Sale\Location\LocationTable::getByCode($prop['VALUE'][0])->fetch();
if ($arLoc) { if ($arLoc) {
@ -105,7 +104,6 @@ class RetailCrmOrder
$order['countryIso'] = $countrys[$countryOrder['NAME']]; $order['countryIso'] = $countrys[$countryOrder['NAME']];
} }
} }
} }
$prop['VALUE'][0] = $location['NAME']; $prop['VALUE'][0] = $location['NAME'];
} }
@ -115,7 +113,7 @@ class RetailCrmOrder
} }
} }
//доставки //deliverys
if (array_key_exists($arFields['DELIVERYS'][0]['id'], $arParams['optionsDelivTypes'])) { if (array_key_exists($arFields['DELIVERYS'][0]['id'], $arParams['optionsDelivTypes'])) {
$order['delivery']['code'] = $arParams['optionsDelivTypes'][$arFields['DELIVERYS'][0]['id']]; $order['delivery']['code'] = $arParams['optionsDelivTypes'][$arFields['DELIVERYS'][0]['id']];
if (isset($arFields['DELIVERYS'][0]['service']) && $arFields['DELIVERYS'][0]['service'] != '') { if (isset($arFields['DELIVERYS'][0]['service']) && $arFields['DELIVERYS'][0]['service'] != '') {
@ -123,7 +121,7 @@ class RetailCrmOrder
} }
} }
//корзина //basket
foreach ($arFields['BASKET'] as $product) { foreach ($arFields['BASKET'] as $product) {
$item = array( $item = array(
'quantity' => $product['QUANTITY'], 'quantity' => $product['QUANTITY'],
@ -144,22 +142,21 @@ class RetailCrmOrder
$order['items'][] = $item; $order['items'][] = $item;
} }
//отправка //send
if (function_exists('retailCrmBeforeOrderSend')) { if (function_exists('retailCrmBeforeOrderSend')) {
$newResOrder = retailCrmBeforeOrderSend($order, $arFields); $newResOrder = retailCrmBeforeOrderSend($order, $arFields);
if (is_array($newResOrder) && !empty($newResOrder)) { if (is_array($newResOrder) && !empty($newResOrder)) {
$order = $newResOrder; $order = $newResOrder;
} elseif ($newResOrder === false) {
RCrmActions::eventLog('RetailCrmOrder::orderSend', 'retailCrmBeforeOrderSend()', 'OrderID = ' . $arFields['ID'] . '. Sending canceled after retailCrmBeforeOrderSend');
return false;
} }
} }
$normalizer = new RestNormalizer(); $normalizer = new RestNormalizer();
$order = $normalizer->normalize($order, 'orders'); $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 = new Logger();
$log->write($order, 'order'); $log->write($order, 'order');

View File

@ -0,0 +1,420 @@
<?php
IncludeModuleLangFile(__FILE__);
class RetailCrmOrder
{
public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_API_HOST_OPTION = 'api_host';
public static $CRM_API_KEY_OPTION = 'api_key';
public static $CRM_ORDER_TYPES_ARR = 'order_types_arr';
public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr';
public static $CRM_PAYMENT_TYPES = 'pay_types_arr';
public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr';
public static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N
public static $CRM_ORDER_LAST_ID = 'order_last_id';
public static $CRM_SITES_LIST = 'sites_list';
public static $CRM_ORDER_PROPS = 'order_props';
public static $CRM_LEGAL_DETAILS = 'legal_details';
public static $CRM_CUSTOM_FIELDS = 'custom_fields';
public static $CRM_CONTRAGENT_TYPE = 'contragent_type';
public static $CRM_ORDER_FAILED_IDS = 'order_failed_ids';
public static $CRM_ORDER_HISTORY_DATE = 'order_history_date';
public static $CRM_CATALOG_BASE_PRICE = 'catalog_base_price';
public static $CRM_ORDER_NUMBERS = 'order_numbers';
const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
/**
*
* Creates order or returns order for mass upload
*
* @param array $arFields
* @param $api
* @param $arParams
* @param $send
* @return boolean
* @return array - array('order' = $order, 'customer' => $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']),
'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']] : '',
'customerComment' => $arFields['USER_DESCRIPTION'],
'managerComment' => $arFields['COMMENTS'],
'delivery' => array(
'cost' => $arFields['PRICE_DELIVERY']
),
);
if ($send && isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') {
$order['customer']['browserId'] = $_COOKIE['_rc'];
}
$order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']];
//fields
foreach ($arFields['PROPS']['properties'] as $prop) {
if ($search = array_search($prop['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) {
$order['contragent'][$search] = $prop['VALUE'][0];//legal order data
} elseif ($search = array_search($prop['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) {
$order['customFields'][$search] = $prop['VALUE'][0];//custom properties
} elseif ($search = array_search($prop['CODE'], $arParams['optionsOrderProps'][$arFields['PERSON_TYPE_ID']])) {//other
if (in_array($search, array('fio', 'phone', 'email'))) {//fio, phone, email
if ($search == 'fio') {
$order = array_merge($order, RCrmActions::explodeFIO($prop['VALUE'][0]));//add fio fields
} else {
$order[$search] = $prop['VALUE'][0];//phone, email
}
} else {//address
if ($prop['TYPE'] == 'LOCATION' && isset($prop['VALUE'][0]) && $prop['VALUE'][0] != '') {
$arLoc = \Bitrix\Sale\Location\LocationTable::getByCode($prop['VALUE'][0])->fetch();
if ($arLoc) {
$server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot();
$countrys = array();
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
$countrysFile = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/country.xml');
foreach ($countrysFile->country as $country) {
$countrys[RCrmActions::fromJSON((string) $country->name)] = (string) $country->alpha;
}
}
$location = \Bitrix\Sale\Location\Name\LocationTable::getList(array(
'filter' => array('=LOCATION_ID' => $arLoc['CITY_ID'], 'LANGUAGE_ID' => 'ru')
))->fetch();
if (count($countrys) > 0) {
$countryOrder = \Bitrix\Sale\Location\Name\LocationTable::getList(array(
'filter' => array('=LOCATION_ID' => $arLoc['COUNTRY_ID'], 'LANGUAGE_ID' => 'ru')
))->fetch();
if(isset($countrys[$countryOrder['NAME']])){
$order['countryIso'] = $countrys[$countryOrder['NAME']];
}
}
}
$prop['VALUE'][0] = $location['NAME'];
}
$order['delivery']['address'][$search] = $prop['VALUE'][0];
}
}
}
//deliverys
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']) && $arFields['DELIVERYS'][0]['service'] != '') {
$order['delivery']['service']['code'] = $arFields['DELIVERYS'][0]['service'];
}
}
//basket
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['discountManualAmount'] = (double) $product['DISCOUNT_PRICE'];
$item['discountManualPercent'] = 0;
$item['initialPrice'] = (double) $product['PRICE'] + (double) $product['DISCOUNT_PRICE'];
$order['items'][] = $item;
}
//payments
$payments = array();
foreach ($arFields['PAYMENTS'] as $payment) {
$pm = array(
'type' => isset($arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']]) ? $arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']] : '',
'amount' => $payment['SUM']
);
if (!empty($payment['ID'])) {
$pm['externalId'] = $payment['ID'];
}
if (!empty($payment['DATE_PAID'])) {
$pm['paidAt'] = new \DateTime($payment['DATE_PAID']);
}
if (!empty($arParams['optionsPayment'][$payment['PAID']])) {
$pm['status'] = $arParams['optionsPayment'][$payment['PAID']];
}
$payments[] = $pm;
}
if (count($payments) > 0) {
$order['payments'] = $payments;
}
//send
if (function_exists('retailCrmBeforeOrderSend')) {
$newResOrder = retailCrmBeforeOrderSend($order, $arFields);
if (is_array($newResOrder) && !empty($newResOrder)) {
$order = $newResOrder;
} elseif ($newResOrder === false) {
RCrmActions::eventLog('RetailCrmOrder::orderSend', 'retailCrmBeforeOrderSend()', 'OrderID = ' . $arFields['ID'] . '. Sending canceled after retailCrmBeforeOrderSend');
return false;
}
}
$normalizer = new RestNormalizer();
$order = $normalizer->normalize($order, 'orders');
$log = new Logger();
$log->write($order, 'order');
if($send) {
if (!RCrmActions::apiMethod($api, $methodApi, __METHOD__, $order, $site)) {
return false;
}
if ($methodApi == 'ordersEdit') {
$crmPayments = array();
if (!empty($arParams['crmOrder']['payments'])) {
foreach ($arParams['crmOrder']['payments'] as $crmPayment) {
if (isset($crmPayment['externalId'])) {
$crmPayments['externalIds'][$crmPayment['externalId']] = $crmPayment;
} else {
$crmPayments['ids'][$crmPayment['id']] = $crmPayment;
}
}
}
foreach ($order['payments'] as $payment) {
if (isset($crmPayments['externalIds'][$payment['externalId']])) {
//update payment
if(RCrmActions::apiMethod($api, 'ordersPaymentEdit', __METHOD__, $payment, $site)){
unset($crmPayments['externalIds'][$payment['externalId']]);
}
} else {
//create
$payment['order']['externalId'] = $order['externalId'];
RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $payment, $site);
}
}
//delete in crm
if (!empty($crmPayments['ids'])) {
foreach ($crmPayments['ids'] as $payment) {
//delete
RCrmActions::apiMethod($api, 'ordersPaymentDelete', __METHOD__, $payment['id']);
}
}
if (!empty($crmPayments['externalIds'])) {
foreach ($crmPayments['externalIds'] as $payment) {
//delete
RCrmActions::apiMethod($api, 'ordersPaymentDelete', __METHOD__, $payment['id']);
}
}
}
}
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\Internals\OrderTable::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();
if(array_key_exists($arOrder['LID'], $optionsSitesList)) {
$site = $optionsSitesList[$arOrder['LID']];
} else {
$site = 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) {
if(array_key_exists($key, $optionsSitesList)) {
$site = $optionsSitesList[$key];
} else {
$site = 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) {
if(array_key_exists($key, $optionsSitesList)) {
$site = $optionsSitesList[$key];
} else {
$site = 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' => array(),
'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'),
'REASON_CANCELED' => $obOrder->getField('REASON_CANCELED'),
);
$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;
}
}
$paymentList = $obOrder->getPaymentCollection();
foreach ($paymentList as $paymentData) {
$arOrder['PAYMENTS'][] = $paymentData->getFields()->getValues();
}
$basketItems = $obOrder->getBasket();
foreach ($basketItems as $item) {
$arOrder['BASKET'][] = $item->getFields();
}
return $arOrder;
}
}

View File

@ -0,0 +1,137 @@
<?php
IncludeModuleLangFile(__FILE__);
class RetailCrmPrices
{
public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_API_HOST_OPTION = 'api_host';
public static $CRM_API_KEY_OPTION = 'api_key';
public static $CRM_PRICES_UPLOAD = 'prices_upload';
public static $CRM_PRICES = 'prices';
public static $CRM_PRICE_SHOPS = 'price_shops';
public static $CRM_IBLOCKS_PRICES = 'iblock_prices';
public static $pageSize = 500;
public static function pricesUpload()
{
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);
$api = new RetailCrm\ApiClient($api_host, $api_key);
$infoBlocks = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_IBLOCKS_PRICES, 0));
$prices = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PRICES, 0));
$shops = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PRICE_SHOPS, 0));
if (count($shops) == 0) {
RCrmActions::eventLog('RetailCrmPrices::pricesUpload()', '$shops', 'No stores selected for download');
return false;
}
if (count($prices) == 0) {
RCrmActions::eventLog('RetailCrmPrices::pricesUpload()', '$prices', 'No prices selected for download');
return false;
}
if (count($infoBlocks) > 0) {
$log = new Logger();
foreach ($infoBlocks as $id) {
$iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id);
$arNavStatParams = array(
'iNumPage' => 1,
'nPageSize' => self::$pageSize,
);
do {
$dbResProductsIds = CIBlockElement::GetList(array('ID'), array('IBLOCK_ID' => $id), false, $arNavStatParams, array('ID'));
$products = array();
while ($product = $dbResProductsIds->fetch()) {
$products[$product['ID']] = $product;
$products[$product['ID']]['offers'] = array();
}
if (!empty($iblockOffer['IBLOCK_ID'])) {
$arFilterOffer = array(
'IBLOCK_ID' => $iblockOffer['IBLOCK_ID'],
'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] => array_keys($products),
);
$dbResOffers = CIBlockElement::GetList(array('ID'), $arFilterOffer, false, false, array('ID', 'PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID']));
while ($offer = $dbResOffers->fetch()) {
$products[$offer['PROPERTY_' . $iblockOffer['SKU_PROPERTY_ID'] . '_VALUE']]['offers'][] = $offer['ID'];
}
}
$elems = array();
foreach ($products as $product) {
if (count($product['offers']) > 0) {
$elems = array_merge($elems, $product['offers']);
} else {
$elems[] = $product['ID'];
}
}
$pricesUpload = array();
$dbPricesProduct = CPrice::GetList(
array(),
array('PRODUCT_ID' => $elems, 'CATALOG_GROUP_ID' => array_keys($prices)),
false,
false,
array('PRODUCT_ID', 'CATALOG_GROUP_ID', 'PRICE')
);
while ($arPricesProduct = $dbPricesProduct->Fetch()) {
foreach ($shops as $shop) {
if (!isset($pricesUpload[$arPricesProduct['PRODUCT_ID'] . '-' . $shop])) {
$pricesUpload[$arPricesProduct['PRODUCT_ID'] . '-' . $shop] = array(
'externalId' => $arPricesProduct['PRODUCT_ID'],
'site' => $shop
);
}
$pricesUpload[$arPricesProduct['PRODUCT_ID'] . '-' . $shop]['prices'][] = array(
'code' => $prices[$arPricesProduct['CATALOG_GROUP_ID']],
'price' => $arPricesProduct['PRICE'],
);
}
}
//for log
$splitedItems = array_chunk($pricesUpload, 200);
foreach ($splitedItems as $chunk) {
$log->write($chunk, 'storePricesUpload');
foreach ($shops as $shop) {
RCrmActions::apiMethod($api, 'storePricesUpload', __METHOD__, $chunk, $shop);
time_nanosleep(0, 250000000);
}
}
$arNavStatParams['iNumPage'] = $dbResProductsIds->NavPageNomer + 1;
} while($dbResProductsIds->NavPageNomer < $dbResProductsIds->NavPageCount);
}
} else {
RCrmActions::eventLog('RetailCrmPrices::pricesUpload()', '$infoBlocks', 'No iblocks selected');
return false;
}
return 'RetailCrmPrices::pricesUpload();';
}
}

View File

@ -0,0 +1,69 @@
<?php
class RetailCrmUa
{
public static $MODULE_ID = 'intaro.retailcrm';
public static $CRM_UA = 'ua';
public static $CRM_UA_KEYS = 'ua_keys';
public static function add()
{
$ua = COption::GetOptionString(self::$MODULE_ID, self::$CRM_UA, 0);
$uaKeys = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_UA_KEYS, 0));
if ($ua === 'Y' && !empty($uaKeys[SITE_ID]['ID']) && !empty($uaKeys[SITE_ID]['INDEX']) && ADMIN_SECTION !== true) {
global $APPLICATION;
$ua = "
<script type=\"text/javascript\">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '" . $uaKeys[SITE_ID]['ID'] . "', 'auto');
function getRetailCrmCookie(name) {
var matches = document.cookie.match(new RegExp(
'(?:^|; )' + name + '=([^;]*)'
));
return matches ? decodeURIComponent(matches[1]) : '';
}
ga('set', 'dimension" . $uaKeys[SITE_ID]['INDEX'] . "', getRetailCrmCookie('_ga'));
ga('send', 'pageview');
</script>";
if (isset($_GET['ORDER_ID'])) {
CModule::IncludeModule("sale");
$arOrder = CSaleOrder::GetByID($_GET['ORDER_ID']);
$ua .= "<script type=\"text/javascript\">
ga('require', 'ecommerce', 'ecommerce.js');
ga('ecommerce:addTransaction', {
'id': $arOrder[ID],
'affiliation': '$_SERVER[SERVER_NAME]',
'revenue': $arOrder[PRICE],
'tax': $arOrder[DISCOUNT_VALUE]
});
";
$arBasketItems = CsaleBasket::GetList(
array('id' => 'asc'),
array('ORDER_ID' => $_GET['ORDER_ID']),
false,
false,
array('PRODUCT_ID', 'NAME', 'PRICE', 'QUANTITY', 'ORDER_ID', 'ID')
);
while ($arItem = $arBasketItems->fetch()) {
$ua .= "
ga('ecommerce:addItem', {
'id': $arOrder[ID],
'sku': '$arItem[PRODUCT_ID]',
'name': '$arItem[NAME]',
'price': $arItem[PRICE],
'quantity': $arItem[QUANTITY]
});
";
}
$ua .= "ga('ecommerce:send');";
}
$ua .= "</script>";
$APPLICATION->AddHeadString($ua);
}
}
}

View File

@ -4,7 +4,7 @@ class RetailCrmUser
{ {
public static function customerSend($arFields, $api, $contragentType, $send = false, $site = null) public static function customerSend($arFields, $api, $contragentType, $send = false, $site = null)
{ {
if (!$api || empty($contragentType)) { // add cond to check $arParams if (!$api || empty($contragentType)) {
return false; return false;
} }
if (empty($arFields)) { if (empty($arFields)) {
@ -22,13 +22,13 @@ class RetailCrmUser
'createdAt' => new \DateTime($arFields['DATE_REGISTER']), 'createdAt' => new \DateTime($arFields['DATE_REGISTER']),
'contragentType' => $contragentType 'contragentType' => $contragentType
); );
if (isset($arFields['PERSONAL_PHONE'])) { if (!empty($arFields['PERSONAL_PHONE'])) {
$customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE'];
} }
if (isset($arUser['WORK_PHONE'])) { if (!empty($arFields['WORK_PHONE'])) {
$customer['phones'][]['number'] = $arFields['WORK_PHONE']; $customer['phones'][]['number'] = $arFields['WORK_PHONE'];
} }
if (isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') { if ($send && isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') {
$customer['browserId'] = $_COOKIE['_rc']; $customer['browserId'] = $_COOKIE['_rc'];
} }
@ -36,6 +36,10 @@ class RetailCrmUser
$newResCustomer = retailCrmBeforeCustomerSend($customer); $newResCustomer = retailCrmBeforeCustomerSend($customer);
if (is_array($newResCustomer) && !empty($newResCustomer)) { if (is_array($newResCustomer) && !empty($newResCustomer)) {
$customer = $newResCustomer; $customer = $newResCustomer;
} elseif ($newResCustomer === false) {
RCrmActions::eventLog('RetailCrmUser::customerSend', 'retailCrmBeforeCustomerSend()', 'UserID = ' . $arFields['ID'] . '. Sending canceled after retailCrmBeforeCustomerSend');
return false;
} }
} }
@ -68,15 +72,15 @@ class RetailCrmUser
'email' => $arFields['EMAIL'], 'email' => $arFields['EMAIL'],
'address' => array('city' => $arFields['PERSONAL_CITY'], 'text' => $arFields['PERSONAL_STREET'], 'index' => $arFields['PERSONAL_ZIP']), 'address' => array('city' => $arFields['PERSONAL_CITY'], 'text' => $arFields['PERSONAL_STREET'], 'index' => $arFields['PERSONAL_ZIP']),
); );
if (isset($arFields['PERSONAL_PHONE'])) { if (!empty($arFields['PERSONAL_PHONE'])) {
$customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE'];
} }
if (isset($arFields['WORK_PHONE'])) { if (!empty($arFields['WORK_PHONE'])) {
$customer['phones'][]['number'] = $arFields['WORK_PHONE']; $customer['phones'][]['number'] = $arFields['WORK_PHONE'];
} }
$found = false; $found = false;
if (count($optionsSitesList) > 1) { if (count($optionsSitesList) > 0) {
foreach ($optionsSitesList as $site) { foreach ($optionsSitesList as $site) {
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site); $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site);
if (isset($userCrm['customer'])) { if (isset($userCrm['customer'])) {
@ -91,7 +95,7 @@ class RetailCrmUser
$found = true; $found = true;
} }
} }
if ($found) { if ($found) {
$normalizer = new RestNormalizer(); $normalizer = new RestNormalizer();
$customer = $normalizer->normalize($customer, 'customers'); $customer = $normalizer->normalize($customer, 'customers');
@ -99,12 +103,17 @@ class RetailCrmUser
$log = new Logger(); $log = new Logger();
$log->write($customer, 'customer'); $log->write($customer, 'customer');
if (function_exists('retailcrmBeforeCustomerSend')) { if (function_exists('retailCrmBeforeCustomerSend')) {
$newResCustomer = intarocrm_before_customer_send($customer); $newResCustomer = retailCrmBeforeCustomerSend($customer);
if (is_array($newResCustomer) && !empty($newResCustomer)) { if (is_array($newResCustomer) && !empty($newResCustomer)) {
$customer = $newResCustomer; $customer = $newResCustomer;
} elseif ($newResCustomer === false) {
RCrmActions::eventLog('RetailCrmUser::customerEdit', 'retailCrmBeforeCustomerSend()', 'UserID = ' . $arFields['ID'] . '. Sending canceled after retailCrmBeforeCustomerSend');
return false;
} }
} }
RCrmActions::apiMethod($api, 'customersEdit', __METHOD__, $customer, $site); RCrmActions::apiMethod($api, 'customersEdit', __METHOD__, $customer, $site);
} }

View File

@ -1,6 +1,3 @@
- Добавлены единицы измерения в экспорте каталога - Добавлена встроенная функция retailCrmApiResult
- Исправлены пути в include - Добавлен триггерный вариант истории изменений
- Добавлено время нового формата в валидатор - Исправлены ошибки
- Исправлено неверное изменение типа заказа по истории
- Исправлена ошибка с некорректным разбиением ФИО
- Небольшие исправления по коду

View File

@ -96,10 +96,7 @@ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/expor
echo ShowError(implode('<br />', $arSetupErrors)); echo ShowError(implode('<br />', $arSetupErrors));
if ($STEP==1) if ($STEP==1) {
{
?> ?>
<style type="text/css"> <style type="text/css">
@ -179,86 +176,84 @@ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/expor
while ($iblock = $db_res->Fetch()) while ($iblock = $db_res->Fetch())
{ {
if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"]))
{
if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P")
{ {
if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") $propertiesSKU = null;
{ if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P")
$propertiesSKU = null; {
if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]);
{
$iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]);
$db_properties = CIBlock::GetProperties($iblockOffer['IBLOCK_ID'], Array()); $db_properties = CIBlock::GetProperties($iblockOffer['IBLOCK_ID'], Array());
while($prop = $db_properties->Fetch()) while($prop = $db_properties->Fetch())
$propertiesSKU[] = $prop; $propertiesSKU[] = $prop;
$oldPropertySKU = null; $oldPropertySKU = null;
if (isset($IBLOCK_PROPERTY_SKU[$iblock['ID']])) { if (isset($IBLOCK_PROPERTY_SKU[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) { foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertySKU[$key] = $IBLOCK_PROPERTY_SKU[$iblock['ID']][$key]; $oldPropertySKU[$key] = $IBLOCK_PROPERTY_SKU[$iblock['ID']][$key];
}
}
$oldPropertyUnitSKU = null;
if (isset($IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertyUnitSKU[$key] = $IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']][$key];
}
}
} }
$propertiesProduct = null;
$db_properties = CIBlock::GetProperties($iblock['ID'], Array());
while($prop = $db_properties->Fetch())
$propertiesProduct[] = $prop;
$oldPropertyProduct = null;
if (isset($IBLOCK_PROPERTY_PRODUCT[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertyProduct[$key] = $IBLOCK_PROPERTY_PRODUCT[$iblock['ID']][$key];
}
}
$oldPropertyUnitProduct = null;
if (isset($IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertyUnitProduct[$key] = $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']][$key];
}
}
$arSiteList = array();
$rsSites = CIBlock::GetSite($iblock["ID"]);
while ($arSite = $rsSites->Fetch())
{
$arSiteList[] = $arSite["SITE_ID"];
}
if (count($IBLOCK_EXPORT) != 0)
$boolExport = (in_array($iblock['ID'], $IBLOCK_EXPORT));
else
$boolExport = true;
$arIBlockList[] = array(
'ID' => $iblock['ID'],
'NAME' => $iblock['NAME'],
'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'],
'IBLOCK_EXPORT' => $boolExport,
'PROPERTIES_SKU' => $propertiesSKU,
'PROPERTIES_PRODUCT' => $propertiesProduct,
'OLD_PROPERTY_SKU_SELECT' => $oldPropertySKU,
'OLD_PROPERTY_UNIT_SKU_SELECT' => $oldPropertyUnitSKU,
'OLD_PROPERTY_PRODUCT_SELECT' => $oldPropertyProduct,
'OLD_PROPERTY_UNIT_PRODUCT_SELECT' => $oldPropertyUnitProduct,
'SITE_LIST' => '('.implode(' ',$arSiteList).')',
);
if ($boolExport)
$intCountChecked++;
$intCountAvailIBlock++;
} }
$oldPropertyUnitSKU = null;
if (isset($IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertyUnitSKU[$key] = $IBLOCK_PROPERTY_UNIT_SKU[$iblock['ID']][$key];
}
}
}
$propertiesProduct = null;
$db_properties = CIBlock::GetProperties($iblock['ID'], Array());
while($prop = $db_properties->Fetch())
$propertiesProduct[] = $prop;
$oldPropertyProduct = null;
if (isset($IBLOCK_PROPERTY_PRODUCT[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertyProduct[$key] = $IBLOCK_PROPERTY_PRODUCT[$iblock['ID']][$key];
}
}
$oldPropertyUnitProduct = null;
if (isset($IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']])) {
foreach ($iblockPropertiesName as $key => $prop) {
$oldPropertyUnitProduct[$key] = $IBLOCK_PROPERTY_UNIT_PRODUCT[$iblock['ID']][$key];
}
}
$arSiteList = array();
$rsSites = CIBlock::GetSite($iblock["ID"]);
while ($arSite = $rsSites->Fetch())
{
$arSiteList[] = $arSite["SITE_ID"];
}
if (count($IBLOCK_EXPORT) != 0)
$boolExport = (in_array($iblock['ID'], $IBLOCK_EXPORT));
else
$boolExport = true;
$arIBlockList[] = array(
'ID' => $iblock['ID'],
'NAME' => $iblock['NAME'],
'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'],
'IBLOCK_EXPORT' => $boolExport,
'PROPERTIES_SKU' => $propertiesSKU,
'PROPERTIES_PRODUCT' => $propertiesProduct,
'OLD_PROPERTY_SKU_SELECT' => $oldPropertySKU,
'OLD_PROPERTY_UNIT_SKU_SELECT' => $oldPropertyUnitSKU,
'OLD_PROPERTY_PRODUCT_SELECT' => $oldPropertyProduct,
'OLD_PROPERTY_UNIT_PRODUCT_SELECT' => $oldPropertyUnitProduct,
'SITE_LIST' => '('.implode(' ',$arSiteList).')',
);
if ($boolExport)
$intCountChecked++;
$intCountAvailIBlock++;
} }
}
} }
if (count($IBLOCK_EXPORT) != 0) { if (count($IBLOCK_EXPORT) != 0) {
if ($intCountChecked == $intCountAvailIBlock) if ($intCountChecked == $intCountAvailIBlock)
@ -267,7 +262,6 @@ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/expor
$intCountChecked = $intCountAvailIBlock; $intCountChecked = $intCountAvailIBlock;
$boolAll = true; $boolAll = true;
} }
?> ?>
<font class="text" style="font-weight: bold;"><?=GetMessage("CHECK_ALL_INFOBLOCKS");?></font> <font class="text" style="font-weight: bold;"><?=GetMessage("CHECK_ALL_INFOBLOCKS");?></font>
@ -317,7 +311,6 @@ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/expor
<tbody> <tbody>
<? foreach ($iblockPropertiesName as $key => $property): ?> <? foreach ($iblockPropertiesName as $key => $property): ?>
<? $productSelected = false;?> <? $productSelected = false;?>
<tr class="adm-list-table-row"> <tr class="adm-list-table-row">
@ -696,7 +689,6 @@ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/expor
elseif ($STEP==2) elseif ($STEP==2)
{ {
COption::SetOptionString($MODULE_ID, $CRM_CATALOG_BASE_PRICE . '_' . $_REQUEST['PROFILE_ID'], htmlspecialchars(trim($_POST['price-types']))); COption::SetOptionString($MODULE_ID, $CRM_CATALOG_BASE_PRICE . '_' . $_REQUEST['PROFILE_ID'], htmlspecialchars(trim($_POST['price-types'])));
COption::SetOptionString($MODULE_ID, 'catalog_base_iblocks', serialize($IBLOCK_EXPORT));
$FINITE = true; $FINITE = true;
} }
} }

View File

@ -1,19 +1,24 @@
<?php <?php
$server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); $server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot();
$version = COption::GetOptionString('intaro.retailcrm', 'api_version');
CModule::AddAutoloadClasses( CModule::AddAutoloadClasses(
'intaro.retailcrm', // module name 'intaro.retailcrm', // module name
array ( array (
'RestNormalizer' => file_exists($server . '/bitrix/php_interface/retailcrm/RestNormalizer.php') ? '../../php_interface/retailcrm/RestNormalizer.php' : 'classes/general/RestNormalizer.php', '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') ? '../../php_interface/retailcrm/Logger.php' : 'classes/general/Logger.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') ? '../../php_interface/retailcrm/ApiClient.php' : 'classes/general/ApiClient.php', 'RetailCrm\ApiClient' => file_exists($server . '/bitrix/php_interface/retailcrm/ApiClient.php') ? $server . '/bitrix/php_interface/retailcrm/ApiClient.php' : 'classes/general/ApiClient_' . $version . '.php',
'RetailCrm\Http\Client' => file_exists($server . '/bitrix/php_interface/retailcrm/Client.php') ? '../../php_interface/retailcrm/Client.php' : 'classes/general/Http/Client.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') ? '../../php_interface/retailcrm/RCrmActions.php' : 'classes/general/RCrmActions.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') ? '../../php_interface/retailcrm/RetailCrmUser.php' : 'classes/general/user/RetailCrmUser.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') ? '../../php_interface/retailcrm/RetailCrmOrder.php' : 'classes/general/order/RetailCrmOrder.php', 'RetailCrmOrder' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmOrder.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmOrder.php' : 'classes/general/order/RetailCrmOrder_' . $version . '.php',
'RetailCrmHistory' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmHistory.php') ? '../../php_interface/retailcrm/RetailCrmHistory.php' : 'classes/general/history/RetailCrmHistory.php', 'RetailCrmHistory' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmHistory.php') ? $server . '/bitrix/php_interface/retailcrm/RetailCrmHistory.php' : 'classes/general/history/RetailCrmHistory_' . $version . '.php',
'RetailCrmICML' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmICML.php') ? '../../php_interface/retailcrm/RetailCrmICML.php' : 'classes/general/icml/RetailCrmICML.php', 'RetailCrmICML' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmICML.php') ? '../../php_interface/retailcrm/RetailCrmICML.php' : 'classes/general/icml/RetailCrmICML.php',
'RetailCrmEvent' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmEvent.php') ? '../../php_interface/retailcrm/RetailCrmEvent.php' : 'classes/general/events/RetailCrmEvent.php', 'RetailCrmInventories' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmInventories.php') ? '../../php_interface/retailcrm/RetailCrmInventories.php' : 'classes/general/inventories/RetailCrmInventories.php',
'RetailCrmPrices' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmPrices.php') ? '../../php_interface/retailcrm/RetailCrmPrices.php' : 'classes/general/prices/RetailCrmPrices.php',
'RetailCrmCollector' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmCollector.php') ? '../../php_interface/retailcrm/RetailCrmCollector.php' : 'classes/general/collector/RetailCrmCollector.php',
'RetailCrmUa' => file_exists($server . '/bitrix/php_interface/retailcrm/RetailCrmUa.php') ? '../../php_interface/retailcrm/RetailCrmUa.php' : 'classes/general/ua/RetailCrmUa.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\Response\ApiResponse' => 'classes/general/Response/ApiResponse.php',
'RetailCrm\Exception\InvalidJsonException' => 'classes/general/Exception/InvalidJsonException.php', 'RetailCrm\Exception\InvalidJsonException' => 'classes/general/Exception/InvalidJsonException.php',
'RetailCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php', 'RetailCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php',

View File

@ -44,9 +44,29 @@ class intaro_retailcrm extends CModule
var $CRM_ORDER_HISTORY = 'order_history'; var $CRM_ORDER_HISTORY = 'order_history';
var $CRM_CUSTOMER_HISTORY = 'customer_history'; var $CRM_CUSTOMER_HISTORY = 'customer_history';
var $CRM_CATALOG_BASE_PRICE = 'catalog_base_price'; var $CRM_CATALOG_BASE_PRICE = 'catalog_base_price';
var $CRM_CATALOG_IBLOCKS = 'catalog_base_iblocks'; //var $CRM_CATALOG_IBLOCKS = 'catalog_base_iblocks';
var $CRM_ORDER_NUMBERS = 'order_numbers'; var $CRM_ORDER_NUMBERS = 'order_numbers';
var $CRM_CANSEL_ORDER = 'cansel_order'; var $CRM_CANSEL_ORDER = 'cansel_order';
var $CRM_INVENTORIES_UPLOAD = 'inventories_upload';
var $CRM_STORES = 'stores';
var $CRM_SHOPS = 'shops';
var $CRM_IBLOCKS_INVENTORIES = 'iblocks_inventories';
var $CRM_PRICES_UPLOAD = 'prices_upload';
var $CRM_PRICES = 'prices';
var $CRM_PRICE_SHOPS = 'price_shops';
var $CRM_IBLOCKS_PRICES = 'iblock_prices';
var $CRM_COLLECTOR = 'collector';
var $CRM_COLL_KEY = 'coll_key';
var $CRM_UA = 'ua';
var $CRM_UA_KEYS = 'ua_keys';
var $CRM_API_VERSION = 'api_version';
var $HISTORY_TIME = 'history_time';
var $INSTALL_PATH; var $INSTALL_PATH;
function intaro_retailcrm() function intaro_retailcrm()
@ -92,19 +112,27 @@ class intaro_retailcrm extends CModule
} }
} }
include($this->INSTALL_PATH . '/../classes/general/ApiClient.php');
include($this->INSTALL_PATH . '/../classes/general/Http/Client.php'); include($this->INSTALL_PATH . '/../classes/general/Http/Client.php');
include($this->INSTALL_PATH . '/../classes/general/Response/ApiResponse.php'); include($this->INSTALL_PATH . '/../classes/general/Response/ApiResponse.php');
include($this->INSTALL_PATH . '/../classes/general/RCrmActions.php'); include($this->INSTALL_PATH . '/../classes/general/RCrmActions.php');
include($this->INSTALL_PATH . '/../classes/general/user/RetailCrmUser.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/events/RetailCrmEvent.php');
include($this->INSTALL_PATH . '/../classes/general/icml/RetailCrmICML.php'); include($this->INSTALL_PATH . '/../classes/general/icml/RetailCrmICML.php');
include($this->INSTALL_PATH . '/../classes/general/Exception/InvalidJsonException.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/Exception/CurlException.php');
include($this->INSTALL_PATH . '/../classes/general/RestNormalizer.php'); include($this->INSTALL_PATH . '/../classes/general/RestNormalizer.php');
include($this->INSTALL_PATH . '/../classes/general/Logger.php'); include($this->INSTALL_PATH . '/../classes/general/Logger.php');
$version = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_VERSION, 0);
if ($version == 'v4') {
include($this->INSTALL_PATH . '/../classes/general/ApiClient_v4.php');
include($this->INSTALL_PATH . '/../classes/general/order/RetailCrmOrder_v4.php');
include($this->INSTALL_PATH . '/../classes/general/history/RetailCrmHistory_v4.php');
} elseif ($version == 'v5') {
include($this->INSTALL_PATH . '/../classes/general/ApiClient_v5.php');
include($this->INSTALL_PATH . '/../classes/general/order/RetailCrmOrder_v5.php');
include($this->INSTALL_PATH . '/../classes/general/history/RetailCrmHistory_v5.php');
}
$step = intval($_REQUEST['step']); $step = intval($_REQUEST['step']);
@ -205,19 +233,12 @@ class intaro_retailcrm extends CModule
return; return;
} }
$this->RETAIL_CRM_API = new RetailCrm\ApiClient($api_host, $api_key); $ping = self::ping($api_host, $api_key);
//api key ok and sites list if (isset($ping['sitesList'])) {
try { $arResult['sitesList'] = $ping['sitesList'];
$arResult['sitesList'] = $APPLICATION->ConvertCharsetArray($this->RETAIL_CRM_API->sitesList()->sites, 'utf-8', SITE_CHARSET); } elseif (isset($ping['errCode'])) {
} catch (\RetailCrm\Exception\CurlException $e) { $arResult['errCode'] = $ping['errCode'];
RCrmActions::eventLog(
'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::sitesList',
$e->getCode() . ': ' . $e->getMessage()
);
$arResult['errCode'] = 'ERR_' . $e->getCode();
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
); );
@ -255,287 +276,6 @@ class intaro_retailcrm extends CModule
} }
$arResult['arSites'] = RCrmActions::SitesList(); $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->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key);
//prepare crm lists
try {
$arResult['orderTypesList'] = $this->RETAIL_CRM_API->orderTypesList()->orderTypes;
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::orderTypesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$APPLICATION->RestartBuffer();
header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
die(json_encode(array("success" => false)));
}
try {
$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) {
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()
);
//form order types ids arr
$orderTypesArr = array();
if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
do {
$arResult['bitrixOrderTypesList'][] = $arOrderTypesList;
$orderTypesArr[$arOrderTypesList['ID']] = htmlspecialchars(trim($_POST['order-type-' . $arOrderTypesList['ID']]));
} while ($arOrderTypesList = $dbOrderTypesList->Fetch());
}
//bitrix deliveryTypesList
$dbDeliveryTypesList = CSaleDelivery::GetList(
array(
"SORT" => "ASC",
"NAME" => "ASC"
), array(
"ACTIVE" => "Y",
), false, false, array()
);
//form delivery types ids arr
$deliveryTypesArr = array();
if ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch()) {
do {
$arResult['bitrixDeliveryTypesList'][] = $arDeliveryTypesList;
$deliveryTypesArr[$arDeliveryTypesList['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryTypesList['ID']]));
} while ($arDeliveryTypesList = $dbDeliveryTypesList->Fetch());
}
//bitrix deliveryServicesList
$dbDeliveryServicesList = CSaleDeliveryHandler::GetList(
array(
'SORT' => 'ASC',
'NAME' => 'ASC'
),
array(
'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
)
);
//form delivery services ids arr
if ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch()) {
do {
//auto delivery types
$deliveryTypesArr[$arDeliveryServicesList['SID']] = htmlspecialchars(trim($_POST['delivery-type-' . $arDeliveryServicesList['SID']]));
} while ($arDeliveryServicesList = $dbDeliveryServicesList->Fetch());
}
//bitrix paymentTypesList
$dbPaymentTypesList = CSalePaySystem::GetList(
array(
"SORT" => "ASC",
"NAME" => "ASC"
), array(
"ACTIVE" => "Y"
)
);
//form payment types ids arr
$paymentTypesArr = array();
if ($arPaymentTypesList = $dbPaymentTypesList->Fetch()) {
do {
$arResult['bitrixPaymentTypesList'][] = $arPaymentTypesList;
$paymentTypesArr[$arPaymentTypesList['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $arPaymentTypesList['ID']]));
} while ($arPaymentTypesList = $dbPaymentTypesList->Fetch());
}
//bitrix paymentStatusesList
$dbPaymentStatusesList = CSaleStatus::GetList(
array(
"SORT" => "ASC",
"NAME" => "ASC"
), array(
"LID" => "ru", //ru
"ACTIVE" => "Y"
)
);
//form payment statuses ids arr
$paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY']));
if ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch()) {
do {
$arResult['bitrixPaymentStatusesList'][$arPaymentStatusesList['ID']] = $arPaymentStatusesList;
$paymentStatusesArr[$arPaymentStatusesList['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $arPaymentStatusesList['ID']]));
} while ($arPaymentStatusesList = $dbPaymentStatusesList->Fetch());
}
$arResult['bitrixPaymentStatusesList'][] = array(
'ID' => 'YY',
'NAME' => GetMessage('CANCELED')
);
//form payment ids arr
$paymentArr = array();
$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(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();
foreach ($arResult['bitrixDeliveryTypesList'] as $bitrixDeliveryType) {
$input['delivery-type-' . $bitrixDeliveryType['ID']] =
'<select name="delivery-type-' . $bitrixDeliveryType['ID'] . '" class="typeselect">';
$input['delivery-type-' . $bitrixDeliveryType['ID']] .= '<option value=""></option>';
foreach ($arResult['deliveryTypesList'] as $deliveryType) {
if ($deliveryTypesArr[$bitrixDeliveryType['ID']] == $deliveryType['code']) {
$input['delivery-type-' . $bitrixDeliveryType['ID']] .=
'<option value="' . $deliveryType['code'] . '" selected>';
} else {
$input['delivery-type-' . $bitrixDeliveryType['ID']] .=
'<option value="' . $deliveryType['code'] . '">';
}
$input['delivery-type-' . $bitrixDeliveryType['ID']] .=
$APPLICATION->ConvertCharset($deliveryType['name'], 'utf-8', SITE_CHARSET);
$input['delivery-type-' . $bitrixDeliveryType['ID']] .= '</option>';
}
$input['delivery-type-' . $bitrixDeliveryType['ID']] .= '</select>';
}
foreach ($arResult['bitrixPaymentTypesList'] as $bitrixPaymentType) {
$input['payment-type-' . $bitrixPaymentType['ID']] =
'<select name="payment-type-' . $bitrixPaymentType['ID'] . '" class="typeselect">';
$input['payment-type-' . $bitrixPaymentType['ID']] .= '<option value=""></option>';
foreach ($arResult['paymentTypesList'] as $paymentType) {
if ($paymentTypesArr[$bitrixPaymentType['ID']] == $paymentType['code']) {
$input['payment-type-' . $bitrixPaymentType['ID']] .=
'<option value="' . $paymentType['code'] . '" selected>';
} else {
$input['payment-type-' . $bitrixPaymentType['ID']] .=
'<option value="' . $paymentType['code'] . '">';
}
$input['payment-type-' . $bitrixPaymentType['ID']] .=
$APPLICATION->ConvertCharset($paymentType['name'], 'utf-8', SITE_CHARSET);
$input['payment-type-' . $bitrixPaymentType['ID']] .= '</option>';
}
$input['payment-type-' . $bitrixPaymentType['ID']] .= '</select>';
}
foreach ($arResult['bitrixPaymentStatusesList'] as $bitrixPaymentStatus) {
$input['payment-status-' . $bitrixPaymentStatus['ID']] =
'<select name="payment-status-' . $bitrixPaymentStatus['ID'] . '" class="typeselect">';
$input['payment-status-' . $bitrixPaymentStatus['ID']] .= '<option value=""></option>';
foreach ($arResult['paymentGroupList'] as $orderStatusGroup) {
if (empty($orderStatusGroup['statuses']))
continue;
$input['payment-status-' . $bitrixPaymentStatus['ID']].=
'<optgroup label="' . $orderStatusGroup['name'] . '">';
foreach ($orderStatusGroup['statuses'] as $payment) {
if(!isset($arResult['paymentList'][$payment])) continue;
if ($paymentStatusesArr[$bitrixPaymentStatus['ID']] == $arResult['paymentList'][$payment]['code']) {
$input['payment-status-' . $bitrixPaymentStatus['ID']] .=
'<option value="' . $arResult['paymentList'][$payment]['code'] . '" selected>';
} else {
$input['payment-status-' . $bitrixPaymentStatus['ID']] .=
'<option value="' . $arResult['paymentList'][$payment]['code'] . '">';
}
$input['payment-status-' . $bitrixPaymentStatus['ID']] .=
$APPLICATION->ConvertCharset($arResult['paymentList'][$payment]['name'], 'utf-8', SITE_CHARSET);
$input['payment-status-' . $bitrixPaymentStatus['ID']] .= '</option>';
}
$input['payment-status-' . $bitrixPaymentStatus['ID']] .= '</optgroup>';
}
$input['payment-status-' . $bitrixPaymentStatus['ID']] .= '</select>';
}
foreach ($arResult['bitrixPaymentList'] as $bitrixPayment) {
$input['payment-' . $bitrixPayment['ID']] =
'<select name="payment-' . $bitrixPayment['ID'] . '" class="typeselect">';
$input['payment-' . $bitrixPayment['ID']] .= '<option value=""></option>';
foreach ($arResult['paymentStatusesList'] as $paymentStatus) {
if ($paymentArr[$bitrixPayment['ID']] == $paymentStatus['code']) {
$input['payment-' . $bitrixPayment['ID']] .=
'<option value="' . $paymentStatus['code'] . '" selected>';
} else {
$input['payment-' . $bitrixPayment['ID']] .=
'<option value="' . $paymentStatus['code'] . '">';
}
$input['payment-' . $bitrixPayment['ID']] .=
$APPLICATION->ConvertCharset($paymentStatus['name'], 'utf-8', SITE_CHARSET);
$input['payment-' . $bitrixPayment['ID']] .= '</option>';
}
$input['payment-' . $bitrixPayment['ID']] .= '</select>';
}
foreach ($arResult['bitrixOrderTypesList'] as $bitrixOrderType) {
$input['order-type-' . $bitrixOrderType['ID']] =
'<select name="order-type-' . $bitrixOrderType['ID'] . '" class="typeselect">';
$input['order-type-' . $bitrixOrderType['ID']] .= '<option value=""></option>';
foreach ($arResult['orderTypesList'] as $orderType) {
if ($orderTypesArr[$bitrixOrderType['ID']] == $orderType['code']) {
$input['order-type-' . $bitrixOrderType['ID']] .=
'<option value="' . $orderType['code'] . '" selected>';
} else {
$input['order-type-' . $bitrixOrderType['ID']] .=
'<option value="' . $orderType['code'] . '">';
}
$input['order-type-' . $bitrixOrderType['ID']] .=
$APPLICATION->ConvertCharset($orderType['name'], 'utf-8', SITE_CHARSET);
$input['order-type-' . $bitrixOrderType['ID']] .= '</option>';
}
$input['order-type-' . $bitrixOrderType['ID']] .= '</select>';
}
$APPLICATION->RestartBuffer();
header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
die(json_encode(array("success" => true, "result" => $input)));
}*/
if (count($arResult['arSites']) > 1) { if (count($arResult['arSites']) > 1) {
@ -543,8 +283,8 @@ class intaro_retailcrm extends CModule
$api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
foreach ($arResult['arSites'] as $site) { foreach ($arResult['arSites'] as $site) {
if ($_POST['sites-id-'.$site['LID']] && !empty($_POST['sites-id-'.$site['LID']])) { if ($_POST['sites-id-' . $site['LID']] && !empty($_POST['sites-id-' . $site['LID']])) {
$siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-'.$site['LID']])); $siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-' . $site['LID']]));
} }
} }
if (count($arResult['arSites']) != count($siteCode)) { if (count($arResult['arSites']) != count($siteCode)) {
@ -552,12 +292,13 @@ class intaro_retailcrm extends CModule
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php'
); );
return; return;
} }
$this->RETAIL_CRM_API = new \RetailCrm\ApiClient($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)); COption::SetOptionString($this->MODULE_ID, $this->CRM_SITES_LIST, serialize($siteCode));
} else {//если 1 сайт } else {
$api_host = htmlspecialchars(trim($_POST[$this->CRM_API_HOST_OPTION])); $api_host = htmlspecialchars(trim($_POST[$this->CRM_API_HOST_OPTION]));
$api_key = htmlspecialchars(trim($_POST[$this->CRM_API_KEY_OPTION])); $api_key = htmlspecialchars(trim($_POST[$this->CRM_API_KEY_OPTION]));
@ -571,29 +312,24 @@ class intaro_retailcrm extends CModule
if (!$api_host || !$api_key) { if (!$api_host || !$api_key) {
$arResult['errCode'] = 'ERR_FIELDS_API_HOST'; $arResult['errCode'] = 'ERR_FIELDS_API_HOST';
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
); );
return; return;
} }
$this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); $ping = self::ping($api_host, $api_key);
if (isset($ping['sitesList'])) {
try { $arResult['sitesList'] = $ping['sitesList'];
$this->RETAIL_CRM_API->paymentStatusesList()->paymentStatuses; } elseif (isset($ping['errCode'])) {
} catch (\RetailCrm\Exception\CurlException $e) { $arResult['errCode'] = $ping['errCode'];
RCrmActions::eventLog(
'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$arResult['errCode'] = 'ERR_' . $e->getCode();
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
); );
return; return;
} }
COption::SetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, $api_host); COption::SetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, $api_host);
COption::SetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, $api_key); COption::SetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, $api_key);
} }
@ -896,7 +632,8 @@ class intaro_retailcrm extends CModule
$customerH = self::historyLoad($api, 'customersHistory'); $customerH = self::historyLoad($api, 'customersHistory');
COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY, $customerH); COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY, $customerH);
//если есть старое значение, переделываем его на новый лад, иначе вычисляем
//new data
if ($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)) { if ($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)) {
try { try {
$history = $api->ordersHistory(array('startDate' => $historyDate)); $history = $api->ordersHistory(array('startDate' => $historyDate));
@ -922,12 +659,25 @@ class intaro_retailcrm extends CModule
} else { } else {
$orderH = self::historyLoad($api, 'ordersHistory'); $orderH = self::historyLoad($api, 'ordersHistory');
} }
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY, $orderH); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY, $orderH);
if ($orderLastId = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_LAST_ID, 0)) { 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); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, $orderLastId);
} else {
$dbOrder = \Bitrix\Sale\Internals\OrderTable::GetList(array(
'order' => array("ID" => "DESC"),
'limit' => 1,
'select' => array('ID')
));
$arOrder = $dbOrder->fetch();
if (!empty($arOrder['ID'])) {
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, $arOrder['ID']);
} else {
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0);
}
} }
if ($orderFailedIds = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_FAILED_IDS, 0)) { 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); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, $orderFailedIds);
} }
@ -1060,7 +810,12 @@ class intaro_retailcrm extends CModule
RegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete"); 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_BASE_PRICE, htmlspecialchars(trim($_POST['price-types'])));
COption::SetOptionString($this->MODULE_ID, $this->CRM_CATALOG_IBLOCKS, $iblocks); //COption::SetOptionString($this->MODULE_ID, $this->CRM_CATALOG_IBLOCKS, $iblocks);
COption::SetOptionString($this->MODULE_ID, $this->CRM_INVENTORIES_UPLOAD, 'N');
COption::SetOptionString($this->MODULE_ID, $this->CRM_PRICES_UPLOAD, 'N');
COption::SetOptionString($this->MODULE_ID, $this->CRM_COLLECTOR, 'N');
COption::SetOptionString($this->MODULE_ID, $this->CRM_UA, 'N');
$this->CopyFiles(); $this->CopyFiles();
if (isset($_POST['LOAD_NOW'])) { if (isset($_POST['LOAD_NOW'])) {
@ -1209,6 +964,8 @@ class intaro_retailcrm extends CModule
global $APPLICATION; global $APPLICATION;
CAgent::RemoveAgent("RCrmActions::orderAgent();", $this->MODULE_ID); CAgent::RemoveAgent("RCrmActions::orderAgent();", $this->MODULE_ID);
CAgent::RemoveAgent("RetailCrmInventories::inventoriesUpload();", $this->MODULE_ID);
CAgent::RemoveAgent("RetailCrmPrices::pricesUpload();", $this->MODULE_ID);
COption::RemoveOption($this->MODULE_ID, $this->CRM_API_HOST_OPTION); COption::RemoveOption($this->MODULE_ID, $this->CRM_API_HOST_OPTION);
COption::RemoveOption($this->MODULE_ID, $this->CRM_API_KEY_OPTION); COption::RemoveOption($this->MODULE_ID, $this->CRM_API_KEY_OPTION);
@ -1228,9 +985,28 @@ class intaro_retailcrm extends CModule
COption::RemoveOption($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY); 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_ORDER_HISTORY);
COption::RemoveOption($this->MODULE_ID, $this->CRM_CATALOG_BASE_PRICE); 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_CATALOG_IBLOCKS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_NUMBERS); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_NUMBERS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_CANSEL_ORDER); COption::RemoveOption($this->MODULE_ID, $this->CRM_CANSEL_ORDER);
COption::RemoveOption($this->MODULE_ID, $this->CRM_INVENTORIES_UPLOAD);
COption::RemoveOption($this->MODULE_ID, $this->CRM_STORES);
COption::RemoveOption($this->MODULE_ID, $this->CRM_SHOPS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_IBLOCKS_INVENTORIES);
COption::RemoveOption($this->MODULE_ID, $this->CRM_PRICES_UPLOAD);
COption::RemoveOption($this->MODULE_ID, $this->CRM_PRICES);
COption::RemoveOption($this->MODULE_ID, $this->CRM_PRICE_SHOPS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_IBLOCKS_PRICES);
COption::RemoveOption($this->MODULE_ID, $this->CRM_COLLECTOR);
COption::RemoveOption($this->MODULE_ID, $this->CRM_COLL_KEY);
COption::RemoveOption($this->MODULE_ID, $this->CRM_UA);
COption::RemoveOption($this->MODULE_ID, $this->CRM_UA_KEYS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_API_VERSION);
COption::RemoveOption($this->MODULE_ID, $this->HISTORY_TIME);
UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder"); UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder");
UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd"); UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd");
@ -1238,6 +1014,8 @@ class intaro_retailcrm extends CModule
UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate"); UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
UnRegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave"); UnRegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave");
UnRegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete"); UnRegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
UnRegisterModuleDependences("main", "OnBeforeProlog", $this->MODULE_ID, "RetailCrmCollector", "add");
UnRegisterModuleDependences("main", "OnBeforeProlog", $this->MODULE_ID, "RetailCrmUa", "add");
if (CModule::IncludeModule("catalog")) { if (CModule::IncludeModule("catalog")) {
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->RETAIL_CRM_EXPORT . '_run.php')) { if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/' . $this->RETAIL_CRM_EXPORT . '_run.php')) {
@ -1308,43 +1086,93 @@ class intaro_retailcrm extends CModule
function historyLoad($api, $method) function historyLoad($api, $method)
{ {
$page = null; $page = null;
$i = 0; $end['id'] = 0;
while (true) {
$i++;
try {
$history = $api->$method(array(), $page);
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$end['id'] = 0;
return $end['id']; try {
} catch (InvalidArgumentException $e) { $history = $api->$method(array(), $page);
RCrmActions::eventLog( } catch (\RetailCrm\Exception\CurlException $e) {
'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::InvalidArgumentException', RCrmActions::eventLog(
$e->getCode() . ': ' . $e->getMessage() 'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::CurlException',
); $e->getCode() . ': ' . $e->getMessage()
$end['id'] = 0; );
return $end['id']; return $end['id'];
} catch (InvalidArgumentException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::InvalidArgumentException',
$e->getCode() . ': ' . $e->getMessage()
);
return $end['id'];
}
if ($history['pagination']['totalPageCount'] > $history['pagination']['currentPage']) {
$page = $history['pagination']['totalPageCount'];
while (true) {
try {
$history = $api->$method(array(), $page);
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
return $end['id'];
} catch (InvalidArgumentException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::' . $method, 'RetailCrm\RestApi::' . $method . '::InvalidArgumentException',
$e->getCode() . ': ' . $e->getMessage()
);
return $end['id'];
}
if (isset($history['history'])) {
$end = array_pop($history['history']);
break;
} else {
$page--;
}
} }
} else {
if (isset($history['history'])) { if (isset($history['history']) && count($history['history']) > 0) {
$end = array_pop($history['history']); $end = array_pop($history['history']);
} else { } else {
$end['id'] = 0; $end['id'] = 0;
break;
}
if ($history['pagination']['totalPageCount'] == $history['pagination']['currentPage']) {
break;
} }
$page = $history['pagination']['totalPageCount'];
} }
return $end['id']; return $end['id'];
} }
function ping($api_host, $api_key)
{
global $APPLICATION;
$versions = array('v5', 'v4');
foreach ($versions as $version) {
$client = new RetailCrm\Http\Client($api_host . '/api/' . $version, array('apiKey' => $api_key));
try {
$result = $client->makeRequest('/reference/sites', 'GET');
} catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog(
'intaro.retailcrm/install/index.php', 'RetailCrm\ApiClient::sitesList',
$e->getCode() . ': ' . $e->getMessage()
);
$res['errCode'] = 'ERR_' . $e->getCode();
}
if ($result->getStatusCode() == 200) {
COption::SetOptionString($this->MODULE_ID, $this->CRM_API_VERSION, $version);
$res['sitesList'] = $APPLICATION->ConvertCharsetArray($result->sites, 'utf-8', SITE_CHARSET);
return $res;
} else {
$res['errCode'] = 'ERR_METHOD_NOT_FOUND';
}
}
return $res;
}
} }

View File

@ -1,6 +1,6 @@
<? <?
$arModuleVersion = array( $arModuleVersion = array(
"VERSION" => "2.1.2", "VERSION" => "2.2.1",
"VERSION_DATE" => "2016-12-09 17:00:00" "VERSION_DATE" => "2017-09-01 12:00:00"
); );

View File

@ -0,0 +1,3 @@
<?php
$MESS["NO_DELIVERY"] = "Без доставки";
$MESS["PRICE_TYPE"] = "Цена retailCRM";

View File

@ -0,0 +1,3 @@
<?php
$MESS["NO_DELIVERY"] = "Без доставки";
$MESS["PRICE_TYPE"] = "Цена retailCRM";

View File

@ -9,6 +9,7 @@ $MESS ['ERR_6'] = 'Возможно неверно введен адрес retai
$MESS ['ERR_403'] = 'Неверный apiKey.'; $MESS ['ERR_403'] = 'Неверный apiKey.';
$MESS ['ERR_0'] = 'Превышено время ожидания ответа от сервера.'; $MESS ['ERR_0'] = 'Превышено время ожидания ответа от сервера.';
$MESS ['ERR_FIELDS_API_HOST'] = 'Неверно заполнены поля.'; $MESS ['ERR_FIELDS_API_HOST'] = 'Неверно заполнены поля.';
$MESS ['ERR_METHOD_NOT_FOUND'] = 'Проверьте доступность медодов API по текущему ключу.';
//$MESS ['URL_NOT_FOUND'] = 'В настройках одного или нескольких сайтов не заполнено поле "URL сервера".'; //$MESS ['URL_NOT_FOUND'] = 'В настройках одного или нескольких сайтов не заполнено поле "URL сервера".';
$MESS ['INFO_1'] = 'Введите адрес экземпляра retailCRM (например, https://demo.retailcrm.ru) и API-ключ.'; $MESS ['INFO_1'] = 'Введите адрес экземпляра retailCRM (например, https://demo.retailcrm.ru) и API-ключ.';
$MESS ['INFO_2'] = 'API-ключ можно сгенерировать при регистрации магазина в retailCRM (Администрирование > Интеграция).'; $MESS ['INFO_2'] = 'API-ключ можно сгенерировать при регистрации магазина в retailCRM (Администрирование > Интеграция).';

View File

@ -13,7 +13,7 @@ $MESS ['CANCELED'] = 'Является флагом «Отменен»';
$MESS ['INFO_1'] = 'Задайте соответствие между справочниками 1C-Битрикс и справочниками retailCRM.'; $MESS ['INFO_1'] = 'Задайте соответствие между справочниками 1C-Битрикс и справочниками retailCRM.';
$MESS ['INFO_2'] = 'В случае, если вы не нашли подходящих значений в справочниках retailCRM, вы можете внести их в разделе'; $MESS ['INFO_2'] = 'В случае, если вы не нашли подходящих значений в справочниках retailCRM, вы можете внести их в разделе';
$MESS ['URL_1'] = 'Администрирование'; $MESS ['URL_1'] = 'Администрирование';
$MESS ['INFO_3'] = 'После этого подгрузите новые значения обновив страницу';//, нажав кнопку «Обновить справочники»'; $MESS ['INFO_3'] = 'После этого подгрузите новые значения обновив страницу';
$MESS ['UPDATE_CATS'] = 'Обновить справочники'; $MESS ['UPDATE_CATS'] = 'Обновить справочники';
$MESS ['MESS_5'] = 'Произошла ошибка сервера, обратитесь в Интаро Софт.'; $MESS ['MESS_5'] = 'Произошла ошибка сервера, обратитесь в Интаро Софт.';
$MESS ['DELIV_TYPES_EXPORT'] = 'Выгрузить список доставок из 1С-Битрикс'; $MESS ['DELIV_TYPES_EXPORT'] = 'Выгрузить список доставок из 1С-Битрикс';

View File

@ -1,12 +1,12 @@
<?php <?php
$MESS ['INTAROCRM_INFO'] = ' $MESS ['INTAROCRM_INFO'] = '
<h2>Дальнейшие действия<h2> <h2>Дальнейшие действия</h2>
<p> <p>
Если вы произвели выгрузку заказов на шаге 3, то эти заказы уже доступны в вашей CRM и Если вы произвели выгрузку заказов на шаге 3, то эти заказы уже доступны в вашей CRM и
через некоторое время по этим заказам будет подготовлены аналитические отчеты в Панели KPI. через некоторое время по этим заказам будет подготовлены аналитические отчеты в Панели KPI.
</p> </p>
<p> <p>
Новые заказы будут отправляться агентом <span style="font-family: Courier New;">ICrmOrderActions::uploadOrdersAgent();</span> Новые заказы будут отправляться агентом <span style="font-family: Courier New;">RCrmActions::uploadOrdersAgent();</span>
в retailCRM каждые 10 минут (интервал можно изменить в разделе <a href="/bitrix/admin/agent_list.php">Агенты</a>). в retailCRM каждые 10 минут (интервал можно изменить в разделе <a href="/bitrix/admin/agent_list.php">Агенты</a>).
</p> </p>
<p> <p>

View File

@ -69,3 +69,24 @@ $MESS ['ORDER_UPL_START'] = 'Начать выгрузку';
$MESS ['OTHER_OPTIONS'] = 'Прочие настройки'; $MESS ['OTHER_OPTIONS'] = 'Прочие настройки';
$MESS ['ORDERS_OPTIONS'] = 'Настройки заказов'; $MESS ['ORDERS_OPTIONS'] = 'Настройки заказов';
$MESS ['ORDER_NUMBERS'] = 'Транслировать номера заказов созданных в црм в магазин'; $MESS ['ORDER_NUMBERS'] = 'Транслировать номера заказов созданных в црм в магазин';
$MESS ['CRM_API_VERSION'] = 'Версия API клиента';
$MESS ['INVENTORIES_UPLOAD'] = 'Включить выгрузку остатков в разрезе складов';
$MESS ['INVENTORIES'] = 'Склады';
$MESS ['SHOPS_INVENTORIES_UPLOAD'] = 'Магазины в которые будут грузиться остатки';
$MESS ['IBLOCKS_UPLOAD'] = 'Инфоблоки товаров';
$MESS ['PRICES_UPLOAD'] = 'Включить выгрузку типов цен для товаров';
$MESS ['PRICE_TYPES'] = 'Выгружаемые типы цен';
$MESS ['SHOPS_PRICES_UPLOAD'] = 'Магазины в которые будут грузиться дополнительные типы цен';
$MESS ['DEMON_COLLECTOR'] = 'Активировать Демон Collector';
$MESS ['DEMON_KEY'] = 'Ключ для';
$MESS ['UNIVERSAL_ANALYTICS'] = 'Включить интеграцию с UA';
$MESS ['ID_UA'] = 'Идентификатор отслеживания:';
$MESS ['INDEX_UA'] = 'Индекс пользовательского параметра:';
$MESS ['API_NOT_FOUND'] = 'Неверная версия API';
$MESS ['API_NOT_WORK'] = 'Выбранная версия API не поддерживается';

View File

@ -22,7 +22,25 @@ $CRM_SITES_LIST= 'sites_list';
$CRM_ORDER_NUMBERS = 'order_numbers'; $CRM_ORDER_NUMBERS = 'order_numbers';
$CRM_CANSEL_ORDER = 'cansel_order'; $CRM_CANSEL_ORDER = 'cansel_order';
if(!CModule::IncludeModule('intaro.retailcrm') || !CModule::IncludeModule('sale')) $CRM_INVENTORIES_UPLOAD = 'inventories_upload';
$CRM_STORES = 'stores';
$CRM_SHOPS = 'shops';
$CRM_IBLOCKS_INVENTORIES = 'iblocks_inventories';
$CRM_PRICES_UPLOAD = 'prices_upload';
$CRM_PRICES = 'prices';
$CRM_PRICE_SHOPS = 'price_shops';
$CRM_IBLOCKS_PRICES = 'iblock_prices';
$CRM_COLLECTOR = 'collector';
$CRM_COLL_KEY = 'coll_key';
$CRM_UA = 'ua';
$CRM_UA_KEYS = 'ua_keys';
$CRM_API_VERSION = 'api_version';
if(!CModule::IncludeModule('intaro.retailcrm') || !CModule::IncludeModule('sale') || !CModule::IncludeModule('iblock') || !CModule::IncludeModule('catalog'))
return; return;
$_GET['errc'] = htmlspecialchars(trim($_GET['errc'])); $_GET['errc'] = htmlspecialchars(trim($_GET['errc']));
@ -300,6 +318,150 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
} }
//order numbers //order numbers
$orderNumbers = htmlspecialchars(trim($_POST['order-numbers'])) ? htmlspecialchars(trim($_POST['order-numbers'])) : 'N'; $orderNumbers = htmlspecialchars(trim($_POST['order-numbers'])) ? htmlspecialchars(trim($_POST['order-numbers'])) : 'N';
//stores
$bitrixStoresArr = array();
$bitrixShopsArr = array();
$bitrixIblocksInventories = array();
if(htmlspecialchars(trim($_POST['inventories-upload'])) == 'Y'){
$inventoriesUpload = 'Y';
$dateAgent = new DateTime();
$intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
$dateAgent->add($intAgent);
CAgent::AddAgent(
"RetailCrmInventories::inventoriesUpload();", $mid, "N", 3600, // interval - 1 час
$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
30
);
$arResult['bitrixStoresExportList'] = RCrmActions::StoresExportList();
foreach($arResult['bitrixStoresExportList'] as $bitrixStores){
$bitrixStoresArr[$bitrixStores['ID']] = htmlspecialchars(trim($_POST['stores-export-' . $bitrixStores['ID']]));
}
function maskInv($var){
return preg_match("/^shops-exoprt/", $var);
}
$bitrixShopsArr = str_replace('shops-exoprt-', '', array_filter(array_keys($_POST), 'maskInv'));
$arResult['bitrixIblocksExportList'] = RCrmActions::IblocksExportList();
foreach($arResult['bitrixIblocksExportList'] as $bitrixIblocks){
if(htmlspecialchars(trim($_POST['iblocks-stores-' . $bitrixIblocks['ID']])) === 'Y'){
$bitrixIblocksInventories[] = $bitrixIblocks['ID'];
}
}
} else {
$inventoriesUpload = 'N';
CAgent::RemoveAgent("RetailCrmInventories::inventoriesUpload();", $mid);
}
//prices
$bitrixPricesArr = array();
$bitrixIblocksPrices = array();
$bitrixPriceShopsArr = array();
if(htmlspecialchars(trim($_POST['prices-upload'])) == 'Y'){
$pricesUpload = 'Y';
$dateAgent = new DateTime();
$intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
$dateAgent->add($intAgent);
CAgent::AddAgent(
"RetailCrmPrices::pricesUpload();", $mid, "N", 86400, // interval - 24 часа
$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
30
);
$arResult['bitrixPricesExportList'] = RCrmActions::PricesExportList();
foreach($arResult['bitrixPricesExportList'] as $bitrixPrices){
$bitrixPricesArr[$bitrixPrices['ID']] = htmlspecialchars(trim($_POST['price-type-export-' . $bitrixPrices['ID']]));
}
function maskPrice($var){
return preg_match("/^shops-price/", $var);
}
$bitrixPriceShopsArr = str_replace('shops-price-', '', array_filter(array_keys($_POST), 'maskPrice'));
$arResult['bitrixIblocksExportList'] = RCrmActions::IblocksExportList();
foreach($arResult['bitrixIblocksExportList'] as $bitrixIblocks){
if(htmlspecialchars(trim($_POST['iblocks-prices-' . $bitrixIblocks['ID']])) === 'Y'){
$bitrixIblocksPrices[] = $bitrixIblocks['ID'];
}
}
} else {
$pricesUpload = 'N';
CAgent::RemoveAgent("RetailCrmPrices::pricesUpload();", $mid);
}
//demon
$collectorKeys = array();
if (htmlspecialchars(trim($_POST['collector'])) == 'Y') {
$collector = 'Y';
foreach ($arResult['arSites'] as $site) {
$collectorKeys[$site['LID']] = trim($_POST['collector-id-' . $site['LID']]);
}
RegisterModuleDependences("main", "OnBeforeProlog", $mid, "RetailCrmCollector", "add");
} else {
$collector = 'N';
UnRegisterModuleDependences("main", "OnBeforeProlog", $mid, "RetailCrmCollector", "add");
}
//UA
$uaKeys = array();
if (htmlspecialchars(trim($_POST['ua-integration'])) == 'Y') {
$ua = 'Y';
foreach ($arResult['arSites'] as $site) {
$uaKeys[$site['LID']]['ID'] = trim($_POST['ua-id-' . $site['LID']]);
$uaKeys[$site['LID']]['INDEX'] = trim($_POST['ua-index-' . $site['LID']]);
}
RegisterModuleDependences("main", "OnBeforeProlog", $mid, "RetailCrmUa", "add");
} else {
$ua = 'N';
UnRegisterModuleDependences("main", "OnBeforeProlog", $mid, "RetailCrmUa", "add");
}
//version
$version = COption::GetOptionString($mid, $CRM_API_VERSION);
if (htmlspecialchars(trim($_POST['api_version'])) != $version) {
if (htmlspecialchars(trim($_POST['api_version'])) == 'v4') {
$version = 'v4';
} elseif (htmlspecialchars(trim($_POST['api_version'])) == 'v5') {
$version = 'v5';
} else {
LocalRedirect($uri);
echo CAdminMessage::ShowMessage(GetMessage('API_NOT_FOUND'));
}
//запрос к апи с $version
$crmUrl = htmlspecialchars(trim($_POST['api_host']));
$apiKey = htmlspecialchars(trim($_POST['api_key']));
if ('/' !== $crmUrl[strlen($crmUrl) - 1]) {
$crmUrl .= '/';
}
$crmUrl = $crmUrl . 'api/' . $version;
$client = new RetailCrm\Http\Client($crmUrl, array('apiKey' => $apiKey));
$result = $client->makeRequest(
'/reference/payment-statuses',
'GET'
);
if ($result->getStatusCode() == 200) {
COption::SetOptionString($mid, $CRM_API_VERSION, $version);
} else {
LocalRedirect($uri);
echo CAdminMessage::ShowMessage(GetMessage('API_NOT_WORK'));
}
}
COption::SetOptionString($mid, $CRM_SITES_LIST, serialize(RCrmActions::clearArr($siteListArr))); COption::SetOptionString($mid, $CRM_SITES_LIST, serialize(RCrmActions::clearArr($siteListArr)));
COption::SetOptionString($mid, $CRM_ORDER_TYPES_ARR, serialize(RCrmActions::clearArr($orderTypesArr))); COption::SetOptionString($mid, $CRM_ORDER_TYPES_ARR, serialize(RCrmActions::clearArr($orderTypesArr)));
@ -314,6 +476,22 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
COption::SetOptionString($mid, $CRM_CUSTOM_FIELDS, serialize(RCrmActions::clearArr($customFieldsArr))); COption::SetOptionString($mid, $CRM_CUSTOM_FIELDS, serialize(RCrmActions::clearArr($customFieldsArr)));
COption::SetOptionString($mid, $CRM_ORDER_NUMBERS, $orderNumbers); COption::SetOptionString($mid, $CRM_ORDER_NUMBERS, $orderNumbers);
COption::SetOptionString($mid, $CRM_CANSEL_ORDER, serialize(RCrmActions::clearArr($canselOrderArr))); COption::SetOptionString($mid, $CRM_CANSEL_ORDER, serialize(RCrmActions::clearArr($canselOrderArr)));
COption::SetOptionString($mid, $CRM_INVENTORIES_UPLOAD, $inventoriesUpload);
COption::SetOptionString($mid, $CRM_STORES, serialize(RCrmActions::clearArr($bitrixStoresArr)));
COption::SetOptionString($mid, $CRM_SHOPS, serialize(RCrmActions::clearArr($bitrixShopsArr)));
COption::SetOptionString($mid, $CRM_IBLOCKS_INVENTORIES, serialize(RCrmActions::clearArr($bitrixIblocksInventories)));
COption::SetOptionString($mid, $CRM_PRICES_UPLOAD, $pricesUpload);
COption::SetOptionString($mid, $CRM_PRICES, serialize(RCrmActions::clearArr($bitrixPricesArr)));
COption::SetOptionString($mid, $CRM_PRICE_SHOPS, serialize(RCrmActions::clearArr($bitrixPriceShopsArr)));
COption::SetOptionString($mid, $CRM_IBLOCKS_PRICES, serialize(RCrmActions::clearArr($bitrixIblocksPrices)));
COption::SetOptionString($mid, $CRM_COLLECTOR, $collector);
COption::SetOptionString($mid, $CRM_COLL_KEY, serialize(RCrmActions::clearArr($collectorKeys)));
COption::SetOptionString($mid, $CRM_UA, $ua);
COption::SetOptionString($mid, $CRM_UA_KEYS, serialize(RCrmActions::clearArr($uaKeys)));
$uri .= '&ok=Y'; $uri .= '&ok=Y';
LocalRedirect($uri); LocalRedirect($uri);
@ -332,6 +510,8 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$arResult['paymentList'] = $api->statusesList()->statuses; $arResult['paymentList'] = $api->statusesList()->statuses;
$arResult['paymentGroupList'] = $api->statusGroupsList()->statusGroups; // -- statuses groups $arResult['paymentGroupList'] = $api->statusGroupsList()->statusGroups; // -- statuses groups
$arResult['sitesList'] = $APPLICATION->ConvertCharsetArray($api->sitesList()->sites, 'utf-8', SITE_CHARSET); $arResult['sitesList'] = $APPLICATION->ConvertCharsetArray($api->sitesList()->sites, 'utf-8', SITE_CHARSET);
$arResult['inventoriesList'] = $APPLICATION->ConvertCharsetArray($api->storesList()->stores, 'utf-8', SITE_CHARSET);
$arResult['priceTypeList'] = $APPLICATION->ConvertCharsetArray($api->pricesTypes()->priceTypes, 'utf-8', SITE_CHARSET);
} catch (\RetailCrm\Exception\CurlException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
RCrmActions::eventLog( RCrmActions::eventLog(
'intaro.retailcrm/options.php', 'RetailCrm\ApiClient::*List::CurlException', 'intaro.retailcrm/options.php', 'RetailCrm\ApiClient::*List::CurlException',
@ -372,6 +552,10 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
//bitrix orderPropsList //bitrix orderPropsList
$arResult['arProp'] = RCrmActions::OrderPropsList(); $arResult['arProp'] = RCrmActions::OrderPropsList();
$arResult['bitrixIblocksExportList'] = RCrmActions::IblocksExportList();
$arResult['bitrixStoresExportList'] = RCrmActions::StoresExportList();
$arResult['bitrixPricesExportList'] = RCrmActions::PricesExportList();
//saved cat params //saved cat params
$optionsOrderTypes = unserialize(COption::GetOptionString($mid, $CRM_ORDER_TYPES_ARR, 0)); $optionsOrderTypes = unserialize(COption::GetOptionString($mid, $CRM_ORDER_TYPES_ARR, 0));
$optionsDelivTypes = unserialize(COption::GetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, 0)); $optionsDelivTypes = unserialize(COption::GetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, 0));
@ -386,8 +570,24 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$optionsCustomFields = unserialize(COption::GetOptionString($mid, $CRM_CUSTOM_FIELDS, 0)); $optionsCustomFields = unserialize(COption::GetOptionString($mid, $CRM_CUSTOM_FIELDS, 0));
$optionsOrderNumbers = COption::GetOptionString($mid, $CRM_ORDER_NUMBERS, 0); $optionsOrderNumbers = COption::GetOptionString($mid, $CRM_ORDER_NUMBERS, 0);
$canselOrderArr = unserialize(COption::GetOptionString($mid, $CRM_CANSEL_ORDER, 0)); $canselOrderArr = unserialize(COption::GetOptionString($mid, $CRM_CANSEL_ORDER, 0));
//$isCustomOrderType = function_exists('intarocrm_set_order_type') || function_exists('intarocrm_get_order_type'); $optionInventotiesUpload = COption::GetOptionString($mid, $CRM_INVENTORIES_UPLOAD, 0);
$optionStores = unserialize(COption::GetOptionString($mid, $CRM_STORES, 0));
$optionShops = unserialize(COption::GetOptionString($mid, $CRM_SHOPS, 0));
$optionIblocksInventories = unserialize(COption::GetOptionString($mid, $CRM_IBLOCKS_INVENTORIES, 0));
$optionPricesUpload = COption::GetOptionString($mid, $CRM_PRICES_UPLOAD, 0);
$optionPrices = unserialize(COption::GetOptionString($mid, $CRM_PRICES, 0));
$optionPriceShops = unserialize(COption::GetOptionString($mid, $CRM_PRICE_SHOPS, 0));
$optionIblocksPrices = unserialize(COption::GetOptionString($mid, $CRM_IBLOCKS_PRICES, 0));
$optionCollector = COption::GetOptionString($mid, $CRM_COLLECTOR, 0);
$optionCollectorKeys = unserialize(COption::GetOptionString($mid, $CRM_COLL_KEY));
$optionUa = COption::GetOptionString($mid, $CRM_UA, 0);
$optionUaKeys = unserialize(COption::GetOptionString($mid, $CRM_UA_KEYS));
$version = COption::GetOptionString($mid, $CRM_API_VERSION, 0);
$aTabs = array( $aTabs = array(
array( array(
@ -446,6 +646,46 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
} }
}); });
}); });
$('.inventories-batton label').change(function(){
if($(this).find('input').is(':checked') === true){
$('tr.inventories').show('slow');
} else if($(this).find('input').is(':checked') === false){
$('tr.inventories').hide('slow');
}
return true;
});
$('.prices-batton label').change(function(){
if($(this).find('input').is(':checked') === true){
$('tr.prices').show('slow');
} else if($(this).find('input').is(':checked') === false){
$('tr.prices').hide('slow');
}
return true;
});
$('.r-ua-button label').change(function(){
if($(this).find('input').is(':checked') === true){
$('tr.r-ua').show('slow');
} else if($(this).find('input').is(':checked') === false){
$('tr.r-ua').hide('slow');
}
return true;
});
$('.r-coll-button label').change(function(){
if($(this).find('input').is(':checked') === true){
$('tr.r-coll').show('slow');
} else if($(this).find('input').is(':checked') === false){
$('tr.r-coll').hide('slow');
}
return true;
});
}); });
$('input[name="update-delivery-services"]').live('click', function() { $('input[name="update-delivery-services"]').live('click', function() {
@ -480,7 +720,32 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
return false; return false;
}); });
</script> </script>
<style type="text/css">
.option-other-bottom {
border-bottom: 0px !important;
}
.option-other-top{
border-top: 1px solid #f5f9f9 !important;
}
.option-other-center{
border-top: 5px solid #f5f9f9 !important;
border-bottom: 5px solid #f5f9f9 !important;
}
.option-other-heading{
border-top: 25px solid #f5f9f9 !important;
border-bottom: 0px solid #f5f9f9 !important;
}
.option-other-empty{
border-bottom: 15px solid #f5f9f9 !important;
}
.option-head{
text-align: center;
padding: 10px;
font-size: 14px;
color: #4b6267;
}
</style>
<form method="POST" action="<?php echo $uri; ?>" id="FORMACTION"> <form method="POST" action="<?php echo $uri; ?>" id="FORMACTION">
<?php <?php
echo bitrix_sessid_post(); echo bitrix_sessid_post();
@ -523,7 +788,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
<?php if(!$badKey):?> <?php if(!$badKey):?>
<?php $tabControl->BeginNextTab(); ?> <?php $tabControl->BeginNextTab(); ?>
<input type="hidden" name="tab" value="catalog"> <input type="hidden" name="tab" value="catalog">
<tr align="center"> <tr class="option-head">
<td colspan="2"><b><?php echo GetMessage('INFO_1'); ?></b></td> <td colspan="2"><b><?php echo GetMessage('INFO_1'); ?></b></td>
</tr> </tr>
<tr class="heading"> <tr class="heading">
@ -538,9 +803,11 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
<select name="delivery-type-<?php echo $bitrixDeliveryType['ID']; ?>" class="typeselect"> <select name="delivery-type-<?php echo $bitrixDeliveryType['ID']; ?>" class="typeselect">
<option value=""></option> <option value=""></option>
<?php foreach($arResult['deliveryTypesList'] as $deliveryType): ?> <?php foreach($arResult['deliveryTypesList'] as $deliveryType): ?>
<?php if($deliveryType['active'] == true){?>
<option value="<?php echo $deliveryType['code']; ?>" <?php if ($optionsDelivTypes[$bitrixDeliveryType['ID']] == $deliveryType['code']) echo 'selected'; ?>> <option value="<?php echo $deliveryType['code']; ?>" <?php if ($optionsDelivTypes[$bitrixDeliveryType['ID']] == $deliveryType['code']) echo 'selected'; ?>>
<?php echo $APPLICATION->ConvertCharset($deliveryType['name'], 'utf-8', SITE_CHARSET); ?> <?php echo $APPLICATION->ConvertCharset($deliveryType['name'], 'utf-8', SITE_CHARSET); ?>
</option> </option>
<?php }?>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</td> </td>
@ -664,10 +931,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
<?php endforeach; ?> <?php endforeach; ?>
<?php $tabControl->BeginNextTab(); ?> <?php $tabControl->BeginNextTab(); ?>
<input type="hidden" name="tab" value="catalog"> <input type="hidden" name="tab" value="catalog">
<tr class="heading"> <tr class="option-head">
<td colspan="2"><b><?php echo GetMessage('ORDER_PROPS'); ?></b></td>
</tr>
<tr align="center">
<td colspan="2"><b><?php echo GetMessage('INFO_2'); ?></b></td> <td colspan="2"><b><?php echo GetMessage('INFO_2'); ?></b></td>
</tr> </tr>
<?php foreach($arResult['bitrixOrderTypesList'] as $bitrixOrderType): ?> <?php foreach($arResult['bitrixOrderTypesList'] as $bitrixOrderType): ?>
@ -770,26 +1034,197 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
<?php $tabControl->BeginNextTab(); ?> <?php $tabControl->BeginNextTab(); ?>
<input type="hidden" name="tab" value="catalog"> <input type="hidden" name="tab" value="catalog">
<tr class="heading"> <tr class="heading">
<td colspan="2"><b><?php echo GetMessage('ORDER_DISCH'); ?></b></td> <td colspan="2" class="option-other-bottom"><b><?php echo GetMessage('ORDERS_OPTIONS'); ?></b></td>
</tr> </tr>
<tr class="heading"> <tr>
<td colspan="2"> <td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><input class="addr" type="radio" name="order-discharge" value="0" <?php if($optionsDischarge == 0) echo "checked"; ?>><?php echo GetMessage('DISCHARGE_AGENT'); ?></label>
<label><input class="addr" type="radio" name="order-discharge" value="1" <?php if($optionsDischarge == 1) echo "checked"; ?>><?php echo GetMessage('DISCHARGE_EVENTS'); ?></label>
</b>
</td>
</tr>
<tr class="heading">
<td colspan="2"><b><?php echo GetMessage('ORDERS_OPTIONS'); ?></b></td>
</tr>
<tr class="heading">
<td colspan="2">
<b> <b>
<label><input class="addr" type="checkbox" name="order-numbers" value="Y" <?php if($optionsOrderNumbers == 'Y') echo "checked"; ?>> <?php echo GetMessage('ORDER_NUMBERS'); ?></label> <label><input class="addr" type="checkbox" name="order-numbers" value="Y" <?php if($optionsOrderNumbers == 'Y') echo "checked"; ?>> <?php echo GetMessage('ORDER_NUMBERS'); ?></label>
</b> </b>
</td> </td>
</tr> </tr>
<tr>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><input class="addr" type="radio" name="order-discharge" value="1" <?php if($optionsDischarge == 1) echo "checked"; ?>><?php echo GetMessage('DISCHARGE_EVENTS'); ?></label>
<label><input class="addr" type="radio" name="order-discharge" value="0" <?php if($optionsDischarge == 0) echo "checked"; ?>><?php echo GetMessage('DISCHARGE_AGENT'); ?></label>
</b>
</td>
</tr>
<tr class="heading" >
<td colspan="2" class="option-other-heading"><b><?php echo GetMessage('CRM_API_VERSION'); ?></b></td>
</tr>
<tr>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<select name="api_version" class="typeselect">
<?php for($v = 4; $v <= 5; $v++) {
$ver = 'v' . $v; ?>
<option value="<?php echo $ver; ?>" <?php if ($ver == $version) echo 'selected'; ?>>
API V<?php echo $v; ?>
</option>
<?php } ?>
</select>
</td>
</tr>
<?php if ($optionInventotiesUpload === 'Y' || count($arResult['bitrixStoresExportList']) > 0) :?>
<tr class="heading inventories-batton">
<td colspan="2" class="option-other-heading">
<b>
<label><input class="addr" type="checkbox" name="inventories-upload" value="Y" <?php if($optionInventotiesUpload === 'Y') echo "checked"; ?>><?php echo GetMessage('INVENTORIES_UPLOAD'); ?></label>
</b>
</td>
</tr>
<tr class="inventories" <?php if($optionInventotiesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b><label><?php echo GetMessage('INVENTORIES'); ?></label></b>
</td>
</tr>
<?php foreach ($arResult['bitrixStoresExportList'] as $catalogExportStore): ?>
<tr class="inventories" <?php if($optionInventotiesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td width="50%" class="adm-detail-content-cell-l"><?php echo $catalogExportStore['TITLE'] ?></td>
<td width="50%" class="adm-detail-content-cell-r">
<select class="typeselect" name="stores-export-<?php echo $catalogExportStore['ID']?>">
<option value=""></option>
<?php foreach ($arResult['inventoriesList'] as $inventoriesList): ?>
<option value="<?php echo $inventoriesList['code'] ?>" <?php if($optionStores[$catalogExportStore['ID']] == $inventoriesList['code']) echo 'selected="selected"'; ?>><?php echo $inventoriesList['name']?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php endforeach; ?>
<tr class="inventories" <?php if($optionInventotiesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><?php echo GetMessage('SHOPS_INVENTORIES_UPLOAD'); ?></label>
</b>
</td>
</tr>
<?php foreach ($arResult['sitesList'] as $sitesList): ?>
<tr class="inventories" align="center" <?php if($optionInventotiesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-other-center">
<label><input class="addr" type="checkbox" name="shops-exoprt-<?echo $sitesList['code'];?>" value="Y" <?php if(in_array($sitesList['code'], $optionShops)) echo "checked"; ?>> <?php echo $sitesList['name'].' ('.$sitesList['code'].')'; ?></label>
</td>
</tr>
<?php endforeach;?>
<tr class="inventories" <?php if($optionInventotiesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><?php echo GetMessage('IBLOCKS_UPLOAD'); ?></label>
</b>
</td>
</tr>
<?php foreach ($arResult['bitrixIblocksExportList'] as $catalogExportIblock) :?>
<tr class="inventories" align="center" <?php if($optionInventotiesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-other-center">
<label><input class="addr" type="checkbox" name="iblocks-stores-<?echo $catalogExportIblock['ID'];?>" value="Y" <?php if(in_array($catalogExportIblock['ID'], $optionIblocksInventories)) echo "checked"; ?>> <?php echo '['. $catalogExportIblock['CODE']. '] ' . $catalogExportIblock['NAME'] . ' (' . $catalogExportIblock['LID'] . ')'; ?></label>
</td>
</tr>
<?php endforeach;?>
<?php endif;?>
<?php if ($optionPricesUpload === 'Y' || count($arResult['bitrixPricesExportList']) > 0) :?>
<tr class="heading prices-batton">
<td colspan="2" class="option-other-heading">
<b>
<label><input class="addr" type="checkbox" name="prices-upload" value="Y" <?php if($optionPricesUpload === 'Y') echo "checked"; ?>><?php echo GetMessage('PRICES_UPLOAD'); ?></label>
</b>
</td>
</tr>
<tr class="prices" <?php if($optionPricesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><?php echo GetMessage('PRICE_TYPES'); ?></label>
</b>
</td>
</tr>
<?php foreach ($arResult['bitrixPricesExportList'] as $catalogExportPrice) :?>
<tr class="prices" <?php if($optionPricesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td width="50%" class="adm-detail-content-cell-l"><?php echo $catalogExportPrice['NAME_LANG'] . ' (' . $catalogExportPrice['NAME'] . ')'; ?></td>
<td width="50%" class="adm-detail-content-cell-r">
<select class="typeselect" name="price-type-export-<?php echo $catalogExportPrice['ID'];?>">
<option value=""></option>
<?php foreach ($arResult['priceTypeList'] as $priceTypeList): ?>
<option value="<?php echo $priceTypeList['code'] ?>" <?php if($optionPrices[$catalogExportPrice['ID']] == $priceTypeList['code']) echo 'selected="selected"'; ?>><?php echo $priceTypeList['name']?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php endforeach;?>
<tr class="prices" <?php if($optionPricesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><?php echo GetMessage('SHOPS_PRICES_UPLOAD'); ?></label>
</b>
</td>
</tr>
<?php foreach ($arResult['sitesList'] as $sitesList): ?>
<tr class="prices" align="center" <?php if($optionPricesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-other-center">
<label><input class="addr" type="checkbox" name="shops-price-<?echo $sitesList['code'];?>" value="Y" <?php if(in_array($sitesList['code'], $optionPriceShops)) echo "checked"; ?>> <?php echo $sitesList['name'].' ('.$sitesList['code'].')'; ?></label>
</td>
</tr>
<?php endforeach;?>
<tr class="prices" <?php if($optionPricesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-head option-other-top option-other-bottom">
<b>
<label><?php echo GetMessage('IBLOCKS_UPLOAD'); ?></label>
</b>
</td>
</tr>
<?php foreach ($arResult['bitrixIblocksExportList'] as $catalogExportIblock) :?>
<tr class="prices" align="center" <?php if($optionPricesUpload !== 'Y') echo 'style="display: none;"'; ?>>
<td colspan="2" class="option-other-center">
<label><input class="addr" type="checkbox" name="iblocks-prices-<?echo $catalogExportIblock['ID'];?>" value="Y" <?php if(in_array($catalogExportIblock['ID'], $optionIblocksPrices)) echo "checked"; ?>> <?php echo '['. $catalogExportIblock['CODE']. '] ' . $catalogExportIblock['NAME'] . ' (' . $catalogExportIblock['LID'] . ')'; ?></label>
</td>
</tr>
<?php endforeach;?>
<?php endif;?>
<tr class="heading r-coll-button">
<td colspan="2" class="option-other-heading">
<b>
<label><input class="addr" type="checkbox" name="collector" value="Y" <?php if($optionCollector === 'Y') echo "checked"; ?>><?php echo GetMessage('DEMON_COLLECTOR'); ?></label>
</b>
</td>
</tr>
<tr class="r-coll" <?php if($optionCollector !== 'Y') echo 'style="display: none;"'; ?>>
<td class="option-head" colspan="2">
<b><?php echo GetMessage('ICRM_SITES'); ?></b>
</td>
</tr>
<?php foreach ($arResult['arSites'] as $sitesList): ?>
<tr class="r-coll" <?php if($optionCollector !== 'Y') echo 'style="display: none;"'; ?>>
<td class="adm-detail-content-cell-l" width="50%"><?php echo GetMessage('DEMON_KEY'); ?> <?php echo $sitesList['NAME']; ?> (<?php echo $sitesList['LID']; ?>)</td>
<td class="adm-detail-content-cell-r" width="50%">
<input name="collector-id-<?echo $sitesList['LID'];?>" value="<?php echo $optionCollectorKeys[$sitesList['LID']]; ?>" type="text">
</td>
</tr>
<?php endforeach;?>
<tr class="heading r-ua-button">
<td colspan="2" class="option-other-heading">
<b>
<label><input class="addr" type="checkbox" name="ua-integration" value="Y" <?php if($optionUa === 'Y') echo "checked"; ?>><?php echo GetMessage('UNIVERSAL_ANALYTICS'); ?></label>
</b>
</td>
</tr>
<?php foreach ($arResult['arSites'] as $sitesList): ?>
<tr class="r-ua" <?php if($optionUa !== 'Y') echo 'style="display: none;"'; ?>>
<td class="option-head" colspan="2">
<b><?php echo $sitesList['NAME']; ?> (<?php echo $sitesList['LID']; ?>)</b>
</td>
</tr>
<tr class="r-ua" <?php if($optionUa !== 'Y') echo 'style="display: none;"'; ?>>
<td class="adm-detail-content-cell-l" width="50%"><?php echo GetMessage('ID_UA'); ?></td>
<td class="adm-detail-content-cell-r" width="50%">
<input name="ua-id-<?echo $sitesList['LID'];?>" value="<?php echo $optionUaKeys[$sitesList['LID']]['ID']; ?>" type="text">
</td>
</tr>
<tr class="r-ua" <?php if($optionUa !== 'Y') echo 'style="display: none;"'; ?>>
<td class="adm-detail-content-cell-l" width="50%"><?php echo GetMessage('INDEX_UA'); ?></td>
<td class="adm-detail-content-cell-r" width="50%">
<input name="ua-index-<?echo $sitesList['LID'];?>" value="<?php echo $optionUaKeys[$sitesList['LID']]['INDEX']; ?>" type="text">
</td>
</tr>
<?php endforeach;?>
<?php endif;?> <?php endif;?>
<?php $tabControl->Buttons(); ?> <?php $tabControl->Buttons(); ?>
<input type="hidden" name="Update" value="Y" /> <input type="hidden" name="Update" value="Y" />
@ -920,7 +1355,8 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$('input[name="start"]').live('click', function() { $('input[name="start"]').live('click', function() {
BX.showWait(); BX.showWait();
$('#indicator').css('width', 0);
$('#percent2').html('0%');
orderUpload(); orderUpload();
return false; return false;