1
0
mirror of synced 2024-11-29 08:46:09 +03:00

Merge pull request #4 from ghostrainman/master

update module
This commit is contained in:
Alex Lushpai 2015-03-10 12:39:47 +03:00
commit 7fb059d21d
34 changed files with 2916 additions and 1709 deletions

View File

@ -1,3 +1,16 @@
## 2015-02-20 v.1.1.0
* Модуль переведен на новую версию API
* Добавлена поддержка реквизитов юр. лиц
* Добавлена многосайтовость
* Добавлена выборочная загрузка заказов из настроек модуля
* Оптимизирована загрузка старых заказов
* Исправлена ошибка с удалением id товара в заказе
* Исправлена ошибка пустого $_SERVER['SERVER_NAME'] при экспорте каталога
* Исправлена ошибка с неправильной скидкой у товара при наличии копеек
* Исправлена ошибка с пропаданием автоматических служб доставок из настроек модуля
* Исправлена неправильная выгрузка сервисов для служб доставок
* Исправлено не правильное определение местоположения
* Рефакторинг модуля
## 2015-02-13 v.1.0.16 ## 2015-02-13 v.1.0.16
* Все действия агента происходят от имени retailcrm * Все действия агента происходят от имени retailcrm
## 2015-02-12 v.1.0.16 ## 2015-02-12 v.1.0.16

View File

@ -1,6 +0,0 @@
<?php
namespace IntaroCrm\Exception;
class ApiException extends \Exception
{
}

View File

@ -1,6 +1,7 @@
<?php <?php
namespace IntaroCrm\Exception;
class CurlException extends \Exception namespace RetailCrm\Exception;
class CurlException extends \RuntimeException
{ {
} }

View File

@ -0,0 +1,7 @@
<?php
namespace RetailCrm\Exception;
class InvalidJsonException extends \DomainException
{
}

View File

@ -7,6 +7,7 @@ class ICMLLoader {
public $iblocks; public $iblocks;
public $filename; public $filename;
public $serverName;
public $propertiesSKU; public $propertiesSKU;
public $propertiesUnitSKU; public $propertiesUnitSKU;
public $propertiesProduct; public $propertiesProduct;
@ -321,7 +322,7 @@ class ICMLLoader {
// Link picture to product // Link picture to product
$products[$pictures[$file['ID']]]['PICTURE'] = ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . $products[$pictures[$file['ID']]]['PICTURE'] = ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") .
$_SERVER['SERVER_NAME'] . $this->serverName .
'/upload/' . $file['SUBDIR'] . '/upload/' . $file['SUBDIR'] .
'/' . $file['FILE_NAME'] ; '/' . $file['FILE_NAME'] ;
} }
@ -500,7 +501,7 @@ class ICMLLoader {
} }
$offer .= "<picture>" . $this->PrepareValue($arOffer["PICTURE"]) . "</picture>\n"; $offer .= "<picture>" . $this->PrepareValue($arOffer["PICTURE"]) . "</picture>\n";
$offer .= "<url>" . ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . $_SERVER['SERVER_NAME'] . $this->PrepareValue($arOffer['DETAIL_PAGE_URL']) . "</url>\n"; $offer .= "<url>" . ($_SERVER["HTTPS"] == 'on' ? "https://" : "http://") . $this->serverName . $this->PrepareValue($arOffer['DETAIL_PAGE_URL']) . "</url>\n";
$offer .= "<price>" . $this->PrepareValue($arOffer['PRICE']) . "</price>\n"; $offer .= "<price>" . $this->PrepareValue($arOffer['PRICE']) . "</price>\n";
if ($arOffer['PURCHASE_PRICE'] && $this->loadPurchasePrice) { if ($arOffer['PURCHASE_PRICE'] && $this->loadPurchasePrice) {

1435
intaro.intarocrm/classes/general/ICrmOrderActions.php Executable file → Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,127 @@
<?php
namespace RetailCrm\Response;
use RetailCrm\Exception\InvalidJsonException;
/**
* Response from retailCRM API
*/
class ApiResponse implements \ArrayAccess
{
// HTTP response status code
protected $statusCode;
// response assoc array
protected $response;
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = (int) $statusCode;
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new InvalidJsonException(
"Invalid JSON in the API response body. Error code #$error",
$error
);
}
$this->response = $response;
}
}
/**
* Return HTTP response status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* HTTP request was successful
*
* @return bool
*/
public function isSuccessful()
{
return $this->statusCode < 400;
}
/**
* Allow to access for the property throw class method
*
* @param string $name
* @return mixed
*/
public function __call($name, $arguments)
{
// convert getSomeProperty to someProperty
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
if (!isset($this->response[$propertyName])) {
throw new \InvalidArgumentException("Method \"$name\" not found");
}
return $this->response[$propertyName];
}
/**
* Allow to access for the property throw object property
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new \InvalidArgumentException("Property \"$name\" not found");
}
return $this->response[$name];
}
/**
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException('This activity not allowed');
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
throw new \BadMethodCallException('This call not allowed');
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->response[$offset]);
}
/**
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new \InvalidArgumentException("Property \"$offset\" not found");
}
return $this->response[$offset];
}
}

View File

@ -1,25 +1,52 @@
<?php <?php
namespace IntaroCrm; namespace RetailCrm;
use RetailCrm\Response\ApiResponse;
use RetailCrm\Exception\CurlException;
/**
* retailCRM API client class
*/
class RestApi class RestApi
{ {
protected $apiUrl; const VERSION = 'v3';
protected $apiKey; const METHOD_GET = 'GET';
protected $apiVersion = '3'; const METHOD_POST = 'POST';
protected $client;
protected $url;
protected $defaultParameters;
protected $generatedAt; protected $generatedAt;
protected $parameters; /**
* Site code
*/
protected $siteCode;
/** /**
* @param string $crmUrl - адрес CRM * Client creating
* @param string $apiKey - ключ для работы с api *
* @param string $url - url сайта
* @param string $apiKey - ключ API
* @param string $site - символьный код сайта
* @return mixed
*/ */
public function __construct($crmUrl, $apiKey) public function __construct($url, $apiKey, $site = null)
{ {
$this->apiUrl = $crmUrl.'/api/v'.$this->apiVersion.'/'; if ('/' != substr($url, strlen($url) - 1, 1)) {
$this->apiKey = $apiKey; $url .= '/';
$this->parameters = array('apiKey' => $this->apiKey); }
$url = $url . 'api/' . self::VERSION;
if (false === stripos($url, 'https://')) {
throw new \InvalidArgumentException('API schema requires HTTPS protocol');
}
$this->url = $url;
$this->defaultParameters = array('apiKey' => $apiKey);
$this->siteCode = $site;
} }
/* Методы для работы с заказами */ /* Методы для работы с заказами */
@ -28,82 +55,99 @@ class RestApi
* *
* @param string $id - идентификатор заказа * @param string $id - идентификатор заказа
* @param string $by - поиск заказа по id или externalId * @param string $by - поиск заказа по id или externalId
* @return array - информация о заказе * @param string $site - символьный код сайта
* @return ApiResponse - информация о заказе
*/ */
public function orderGet($id, $by = 'externalId') public function ordersGet($id, $by = 'externalId', $site = null)
{ {
$url = $this->apiUrl.'orders/'.$id; $this->checkIdParameter($by);
if ($by != 'externalId') return $this->makeRequest("/orders/$id", self::METHOD_GET, $this->fillSite($site, array(
$this->parameters['by'] = $by; 'by' => $by
$result = $this->curlRequest($url); )));
return $result;
} }
/** /**
* Создание заказа * Создание заказа
* *
* @param array $order- информация о заказе * @param array $order - информация о заказе
* @return array * @param string $site - символьный код сайта
* @return ApiResponse
*/ */
public function orderCreate($order) public function ordersCreate($order, $site = null)
{ {
$dataJson = json_encode($order); if (!sizeof($order)) {
$this->parameters['order'] = $dataJson; throw new \InvalidArgumentException('Parameter `order` must contains a data');
}
$url = $this->apiUrl.'orders/create'; return $this->makeRequest("/orders/create", self::METHOD_POST, $this->fillSite($site, array(
$result = $this->curlRequest($url, 'POST'); 'order' => json_encode($order)
return $result; )));
} }
/** /**
* Изменение заказа * Изменение заказа
* *
* @param array $order- информация о заказе * @param array $order - информация о заказе
* @return array * @param string $by - изменение заказа по id или externalId
* @param string $site - символьный код сайта
* @return ApiResponse
*/ */
public function orderEdit($order) public function orderEdit($order, $by = 'externalId', $site = null)
{ {
$dataJson = json_encode($order); if (!sizeof($order)) {
$this->parameters['order'] = $dataJson; throw new \InvalidArgumentException('Parameter `order` must contains a data');
}
$url = $this->apiUrl.'orders/'.$order['externalId'].'/edit'; $this->checkIdParameter($by);
$result = $this->curlRequest($url, 'POST');
return $result; if (!isset($order[$by])) {
throw new \InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by));
}
return $this->makeRequest(
"/orders/" . $order[$by] . "/edit",
self::METHOD_POST,
$this->fillSite($site, array(
'order' => json_encode($order),
'by' => $by,
))
);
} }
/** /**
* Пакетная загрузка заказов * Пакетная загрузка заказов
* *
* @param array $orders - массив заказов * @param array $orders - массив заказов
* @return array * @param string $site - символьный код сайта
* @return ApiResponse
*/ */
public function orderUpload($orders) public function orderUpload($orders, $site = null)
{ {
$dataJson = json_encode($orders); if (!sizeof($orders)) {
$this->parameters['orders'] = $dataJson; throw new \InvalidArgumentException('Parameter `orders` must contains array of the orders');
}
$url = $this->apiUrl.'orders/upload'; return $this->makeRequest("/orders/upload", self::METHOD_POST, $this->fillSite($site, array(
$result = $this->curlRequest($url, 'POST'); 'orders' => json_encode($orders),
if (is_null($result) && isset($result['uploadedOrders'])) )));
return $result['uploadedOrders'];
return $result;
} }
/** /**
* Обновление externalId у заказов с переданными id * Обновление externalId у заказов с переданными id
* *
* @param array $orders- массив, содержащий id и externalId заказа * @param array $order - массив, содержащий id и externalId заказа
* @return array * @return ApiResponse
*/ */
public function orderFixExternalIds($order) public function orderFixExternalIds($order)
{ {
$dataJson = json_encode($order); if (!sizeof($order)) {
$this->parameters['orders'] = $dataJson; throw new \InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
$url = $this->apiUrl.'orders/fix-external-ids'; return $this->makeRequest("/orders/fix-external-ids", self::METHOD_POST, array(
$result = $this->curlRequest($url, 'POST'); 'orders' => json_encode($order),
return $result; ));
} }
/** /**
@ -113,18 +157,35 @@ class RestApi
* @param \DateTime|string|int $endDate - конечная дата и время выборки (Y-m-d H:i:s) * @param \DateTime|string|int $endDate - конечная дата и время выборки (Y-m-d H:i:s)
* @param int $limit - ограничение на размер выборки * @param int $limit - ограничение на размер выборки
* @param int $offset - сдвиг * @param int $offset - сдвиг
* @return array - массив заказов * @param bool $skipMyChanges
* @return ApiResponse
*/ */
public function orderHistory($startDate = null, $endDate = null, $limit = 100, $offset = 0) public function orderHistory(
{ $startDate = null,
$url = $this->apiUrl.'orders/history'; $endDate = null,
$this->parameters['startDate'] = $this->ensureDateTime($startDate); $limit = 100,
$this->parameters['endDate'] = $this->ensureDateTime($endDate); $offset = 0,
$this->parameters['limit'] = $limit; $skipMyChanges = true
$this->parameters['offset'] = $offset; ) {
$parameters = array();
$result = $this->curlRequest($url); if ($startDate) {
return $result; $parameters['startDate'] = $this->ensureDateTime($startDate);
}
if ($endDate) {
$parameters['endDate'] = $this->ensureDateTime($endDate);
}
if ($limit) {
$parameters['limit'] = (int) $limit;
}
if ($offset) {
$parameters['offset'] = (int) $offset;
}
if ($skipMyChanges) {
$parameters['skipMyChanges'] = (bool) $skipMyChanges;
}
return $this->makeRequest('/orders/history', self::METHOD_GET, $parameters);
} }
/* Методы для работы с клиентами */ /* Методы для работы с клиентами */
@ -133,356 +194,380 @@ class RestApi
* *
* @param string $id - идентификатор * @param string $id - идентификатор
* @param string $by - поиск заказа по id или externalId * @param string $by - поиск заказа по id или externalId
* @param string $site - символьный код сайта
* @return array - информация о клиенте * @return array - информация о клиенте
*/ */
public function customerGet($id, $by = 'externalId') public function customerGet($id, $by = 'externalId', $site = null)
{ {
$url = $this->apiUrl.'customers/'.$id; $this->checkIdParameter($by);
if ($by != 'externalId')
$this->parameters['by'] = $by; return $this->makeRequest("/customers/$id", self::METHOD_GET, $this->fillSite($site, array(
$result = $this->curlRequest($url); 'by' => $by
return $result; )));
} }
/** /**
* Получение списка клиентов в соответсвии с запросом * Получение списка клиентов в соответсвии с запросом
* *
* @param string $phone - телефон * @param array $filter - фильтры
* @param string $email - почтовый адрес * @param int $page - страница
* @param string $fio - фио пользователя
* @param int $limit - ограничение на размер выборки * @param int $limit - ограничение на размер выборки
* @param int $offset - сдвиг * @return ApiResponse
* @return array - массив клиентов
*/ */
public function customers($phone = null, $email = null, $fio = null, $limit = 200, $offset = 0) public function customersList(array $filter = array(), $page = null, $limit = null)
{ {
$url = $this->apiUrl.'customers'; $parameters = array();
if($phone) $this->parameters['phone'] = $phone;
if($email) $this->parameters['email'] = $email;
if($fio) $this->parameters['fio'] = $fio;
$this->parameters['limit'] = $limit;
$this->parameters['offset'] = $offset;
$result = $this->curlRequest($url); if (sizeof($filter)) {
return $result; $parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->makeRequest('/customers', self::METHOD_GET, $parameters);
} }
/** /**
* Создание клиента * Создание клиента
* *
* @param array $customer - информация о клиенте * @param array $customer - информация о клиенте
* @return array * @param string $site - символьный код сайта
* @return ApiResponse
*/ */
public function customerCreate($customer) public function customersCreate(array $customer, $site = null)
{ {
$dataJson = json_encode($customer); if (!sizeof($customer)) {
$this->parameters['customer'] = $dataJson; throw new \InvalidArgumentException('Parameter `customer` must contains a data');
}
$url = $this->apiUrl.'customers/create'; return $this->makeRequest("/customers/create", self::METHOD_POST, $this->fillSite($site, array(
$result = $this->curlRequest($url, 'POST'); 'customer' => json_encode($customer)
return $result; )));
} }
/** /**
* Редактирование клиента * Редактирование клиента
* *
* @param array $customer - информация о клиенте * @param array $customer - информация о клиенте
* @return array * @param string $by - изменение клиента по id или externalId
* @param string $site - символьный код сайта
* @return ApiResponse
*/ */
public function customerEdit($customer) public function customerEdit($customer, $by = 'externalId', $site = null)
{ {
$dataJson = json_encode($customer); if (!sizeof($customer)) {
$this->parameters['customer'] = $dataJson; throw new \InvalidArgumentException('Parameter `customer` must contains a data');
}
$url = $this->apiUrl.'customers/'.$customer['externalId'].'/edit'; $this->checkIdParameter($by);
$result = $this->curlRequest($url, 'POST');
return $result; if (!isset($customer[$by])) {
throw new \InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by));
}
return $this->makeRequest(
"/customers/" . $customer[$by] . "/edit",
self::METHOD_POST,
$this->fillSite($site, array(
'customer' => json_encode($customer),
'by' => $by,
)
));
} }
/** /**
* Пакетная загрузка клиентов * Пакетная загрузка клиентов
* *
* @param array $customers - массив клиентов * @param array $customers - массив клиентов
* @return array * @param string $site - символьный код сайта
* @return ApiResponse
*/ */
public function customerUpload($customers) public function customerUpload($customers, $site = null)
{ {
$dataJson = json_encode($customers); if (!sizeof($customers)) {
$this->parameters['customers'] = $dataJson; throw new \InvalidArgumentException('Parameter `customers` must contains array of the customers');
}
$url = $this->apiUrl.'customers/upload'; return $this->makeRequest("/customers/upload", self::METHOD_POST, $this->fillSite($site, array(
$result = $this->curlRequest($url, 'POST'); 'customers' => json_encode($customers),
if (is_null($result) && isset($result['uploaded'])) )));
return $result['uploaded'];
return $result;
} }
/** /**
* Обновление externalId у клиентов с переданными id * Обновление externalId у клиентов с переданными id
* *
* @param array $customers- массив, содержащий id и externalId заказа * @param array $customers - массив, содержащий id и externalId заказа
* @return array * @return array
*/ */
public function customerFixExternalIds($customers) public function customerFixExternalIds($customers)
{ {
$dataJson = json_encode($customers); if (!sizeof($customers)) {
$this->parameters['customers'] = $dataJson; throw new \InvalidArgumentException('Method parameter must contains at least one IDs pair');
$url = $this->apiUrl.'customers/fix-external-ids';
$result = $this->curlRequest($url, 'POST');
return $result;
} }
/** return $this->makeRequest("/customers/fix-external-ids", self::METHOD_POST, array(
* Получение списка заказов клиента 'customers' => json_encode($customers),
* ));
* @param string $id - идентификатор клиента
* @param string $by - поиск заказа по id или externalId
* @param \DateTime|string|int $startDate - начальная дата выборки (Y-m-d H:i:s)
* @param \DateTime|string|int $endDate - конечная дата выборки (Y-m-d H:i:s)
* @param int $limit - ограничение на размер выборки
* @param int $offset - сдвиг
* @return array - массив заказов
*/
public function customerOrdersList($id, $startDate = null, $endDate = null,
$limit = 100, $offset = 0, $by = 'externalId')
{
$url = $this->apiUrl.'customers/'.$id.'/orders';
if ($by != 'externalId')
$this->parameters['by'] = $by;
$this->parameters['startDate'] = $this->ensureDateTime($startDate);
$this->parameters['endDate'] = $this->ensureDateTime($endDate);
$this->parameters['limit'] = $limit;
$this->parameters['offset'] = $offset;
$result = $this->curlRequest($url);
return $result;
} }
/* Методы для работы со справочниками */ /* Методы для работы со справочниками */
/** /**
* Получение списка типов доставки * Получение списка типов доставки
* *
* @return array - массив типов доставки * @return ApiResponse
*/ */
public function deliveryTypesList() public function deliveryTypesList()
{ {
$url = $this->apiUrl.'reference/delivery-types'; return $this->makeRequest('/reference/delivery-types', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Редактирование типа доставки * Редактирование типа доставки
* *
* @param array $deliveryType - информация о типе доставки * @param array $delivery - информация о типе доставки
* @return array * @return ApiResponse
*/ */
public function deliveryTypeEdit($deliveryType) public function deliveryTypeEdit($delivery)
{ {
$dataJson = json_encode($deliveryType); if (!isset($delivery['code'])) {
$this->parameters['deliveryType'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/delivery-types/'.$deliveryType['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/delivery-types/' . $delivery['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'deliveryType' => json_encode($delivery)
)
);
} }
/** /**
* Получение списка служб доставки * Получение списка служб доставки
* *
* @return array - массив типов доставки * @return ApiResponse
*/ */
public function deliveryServicesList() public function deliveryServicesList()
{ {
$url = $this->apiUrl.'reference/delivery-services'; return $this->makeRequest('/reference/delivery-services', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Редактирование службы доставки * Редактирование службы доставки
* *
* @param array $deliveryService - информация о типе доставки * @param array $delivery - информация о типе доставки
* @return array * @return ApiResponse
*/ */
public function deliveryServiceEdit($deliveryService) public function deliveryServiceEdit($delivery)
{ {
$dataJson = json_encode($deliveryService); if (!isset($delivery['code'])) {
$this->parameters['deliveryService'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/delivery-services/'.$deliveryService['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/delivery-services/' . $delivery['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'deliveryService' => json_encode($delivery)
)
);
} }
/** /**
* Получение списка типов оплаты * Получение списка типов оплаты
* *
* @return array - массив типов оплаты * @return ApiResponse
*/ */
public function paymentTypesList() public function paymentTypesList()
{ {
$url = $this->apiUrl.'reference/payment-types'; return $this->makeRequest('/reference/payment-types', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Редактирование типа оплаты * Редактирование типа оплаты
* *
* @param array $paymentType - информация о типе оплаты * @param array $paymentType - информация о типе оплаты
* @return array * @return ApiResponse
*/ */
public function paymentTypesEdit($paymentType) public function paymentTypesEdit($paymentType)
{ {
$dataJson = json_encode($paymentType); if (!isset($paymentType['code'])) {
$this->parameters['paymentType'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/payment-types/'.$paymentType['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/payment-types/' . $paymentType['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'paymentType' => json_encode($paymentType)
)
);
} }
/** /**
* Получение списка статусов оплаты * Получение списка статусов оплаты
* *
* @return array - массив статусов оплаты * @return ApiResponse
*/ */
public function paymentStatusesList() public function paymentStatusesList()
{ {
$url = $this->apiUrl.'reference/payment-statuses'; return $this->makeRequest('/reference/payment-statuses', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Редактирование статуса оплаты * Редактирование статуса оплаты
* *
* @param array $paymentStatus - информация о статусе оплаты * @param array $paymentStatus - информация о статусе оплаты
* @return array * @return ApiResponse
*/ */
public function paymentStatusesEdit($paymentStatus) public function paymentStatusesEdit($paymentStatus)
{ {
$dataJson = json_encode($paymentStatus); if (!isset($paymentStatus['code'])) {
$this->parameters['paymentStatus'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/payment-statuses/'.$paymentStatus['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/payment-statuses/' . $paymentStatus['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'paymentStatus' => json_encode($paymentStatus)
)
);
} }
/** /**
* Получение списка типов заказа * Получение списка типов заказа
* *
* @return array - массив типов заказа * @return ApiResponse
*/ */
public function orderTypesList() public function orderTypesList()
{ {
$url = $this->apiUrl.'reference/order-types'; return $this->makeRequest('/reference/order-types', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Редактирование типа заказа * Редактирование типа заказа
* *
* @param array $orderType - информация о типе заказа * @param array $orderType - информация о типе заказа
* @return array * @return ApiResponse
*/ */
public function orderTypesEdit($orderType) public function orderTypesEdit($orderType)
{ {
$dataJson = json_encode($orderType); if (!isset($orderType['code'])) {
$this->parameters['orderType'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/order-types/'.$orderType['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/order-types/' . $orderType['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'orderType' => json_encode($orderType)
)
);
} }
/** /**
* Получение списка способов оформления заказа * Получение списка способов оформления заказа
* *
* @return array - массив способов оформления заказа * @return ApiResponse
*/ */
public function orderMethodsList() public function orderMethodsList()
{ {
$url = $this->apiUrl.'reference/order-methods'; return $this->makeRequest('/reference/order-methods', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Редактирование способа оформления заказа * Редактирование способа оформления заказа
* *
* @param array $orderMethod - информация о способе оформления заказа * @param array $orderMethod - информация о способе оформления заказа
* @return array * @return ApiResponse
*/ */
public function orderMethodsEdit($orderMethod) public function orderMethodsEdit($orderMethod)
{ {
$dataJson = json_encode($orderMethod); if (!isset($orderMethod['code'])) {
$this->parameters['orderMethod'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/order-methods/'.$orderMethod['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/order-methods/' . $orderMethod['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'orderMethod' => json_encode($orderMethod)
)
);
} }
/** /**
* Получение списка статусов заказа * Получение списка статусов заказа
* *
* @return array - массив статусов заказа * @return ApiResponse
*/ */
public function orderStatusesList() public function orderStatusesList()
{ {
$url = $this->apiUrl.'reference/statuses'; return $this->makeRequest('/reference/statuses', self::METHOD_GET);
$result = $this->curlRequest($url); }
return $result;
/**
* Получение списка сайтов
*
* @return ApiResponse
*/
public function sitesList()
{
return $this->makeRequest('/reference/sites', self::METHOD_GET);
} }
/** /**
* Редактирование статуса заказа * Редактирование статуса заказа
* *
* @param array $status - информация о статусе заказа * @param array $status - информация о статусе заказа
* @return array * @return ApiResponse
*/ */
public function orderStatusEdit($status) public function orderStatusEdit($status)
{ {
$dataJson = json_encode($status); if (!isset($status['code'])) {
$this->parameters['status'] = $dataJson; throw new \InvalidArgumentException('Data must contain "code" parameter.');
}
$url = $this->apiUrl.'reference/statuses/'.$status['code'].'/edit'; return $this->makeRequest(
$result = $this->curlRequest($url, 'POST'); '/reference/statuses/' . $status['code'] . '/edit',
return $result; self::METHOD_POST,
array(
'status' => json_encode($status)
)
);
} }
/** /**
* Получение списка групп статусов заказа * Получение списка групп статусов заказа
* *
* @return array - массив групп статусов заказа * @return ApiResponse
*/ */
public function orderStatusGroupsList() public function orderStatusGroupsList()
{ {
$url = $this->apiUrl.'reference/status-groups'; return $this->makeRequest('/reference/status-groups', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
* Обновление статистики * Обновление статистики
* *
* @return array - статус вып обновления * @return ApiResponse
*/ */
public function statisticUpdate() public function statisticUpdate()
{ {
$url = $this->apiUrl.'statistic/update'; return $this->makeRequest('/statistic/update', self::METHOD_GET);
$result = $this->curlRequest($url);
return $result;
} }
/** /**
@ -504,78 +589,101 @@ class RestApi
return $value; return $value;
} }
protected function getErrorMessage($response) /**
* Check ID parameter
*
* @param string $by
* @return bool
*/
protected function checkIdParameter($by)
{ {
$str = ''; $allowedForBy = array('externalId', 'id');
if (isset($response['message'])) if (!in_array($by, $allowedForBy)) {
$str = $response['message']; throw new \InvalidArgumentException(sprintf(
elseif (isset($response[0]['message'])) 'Value "%s" for parameter "by" is not valid. Allowed values are %s.',
$str = $response[0]['message']; $by,
elseif (isset($response['error']) && isset($response['error']['message'])) implode(', ', $allowedForBy)
$str = $response['error']['message']; ));
elseif (isset($response['errorMsg'])) }
$str = $response['errorMsg']; return true;
if (isset($response['errors']) && sizeof($response['errors'])) {
foreach ($response['errors'] as $error)
$str .= '. ' . $error;
} }
if (!strlen($str)) /**
return 'Application Error'; * Fill params by site value
*
return $str; * @param string $site
* @param array $params
* @return array
*/
protected function fillSite($site, array $params)
{
if ($site) {
$params['site'] = $site;
} elseif ($this->siteCode) {
$params['site'] = $this->siteCode;
} }
protected function curlRequest($url, $method = 'GET', $format = 'json') return $params;
}
/**
* Make HTTP request
*
* @param string $path
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
* @param int $timeout
* @return ApiResponse
*/
public function makeRequest($path, $method, $parameters = array(), $timeout = 30)
{ {
if ($method == 'GET' && !is_null($this->parameters)) $allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
$url .= '?'.http_build_query($this->parameters); if (!in_array($method, $allowedMethods)) {
throw new \InvalidArgumentException(sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
));
}
$parameters = array_merge($this->defaultParameters, $parameters);
$path = $this->url . $path;
if (self::METHOD_GET === $method && sizeof($parameters)) {
$path .= '?' . http_build_query($parameters);
}
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $path);
curl_setopt($ch, CURLOPT_FAILONERROR, FALSE); curl_setopt($ch, CURLOPT_FAILONERROR, false);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout); // times out after 30s
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
if (self::METHOD_POST === $method) {
if ($method == 'POST')
{
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->parameters); curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
} }
$response = curl_exec($ch); $responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
unset($this->parameters);
/* Сброс массива с параметрами */
$this->parameters = array('apiKey' => $this->apiKey);
$errno = curl_errno($ch); $errno = curl_errno($ch);
$error = curl_error($ch); $error = curl_error($ch);
curl_close($ch); curl_close($ch);
if ($errno) if ($errno) {
throw new Exception\CurlException($error, $errno); throw new CurlException($error, $errno);
$result = json_decode($response, true);
if ($statusCode >= 400 || isset($result['success']) && $result['success'] === false) {
throw new Exception\ApiException($this->getErrorMessage($result), $statusCode);
} }
$result = json_decode($responseBody, true);
if (isset($result['generatedAt'])) { if (isset($result['generatedAt'])) {
$this->generatedAt = new \DateTime($result['generatedAt']); $this->generatedAt = new \DateTime($result['generatedAt']);
unset($result['generatedAt']); unset($result['generatedAt']);
} }
unset($result['success']); return new ApiResponse($statusCode, $responseBody);
if (count($result) == 0)
return true;
return reset($result);
} }
} }

View File

@ -0,0 +1,412 @@
<?php
/**
* RestNormalizer
*
* Copyright (c) 2015, Dmitry Mamontov <d.slonyara@gmail.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Dmitry Mamontov nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package restnormalizer
* @author Dmitry Mamontov <d.slonyara@gmail.com>
* @copyright 2015 Dmitry Mamontov <d.slonyara@gmail.com>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @since File available since Release 1.0.0
*/
/**
* RestNormalizer - The main class
*
* @author Dmitry Mamontov <d.slonyara@gmail.com>
* @copyright 2015 Dmitry Mamontov <d.slonyara@gmail.com>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @version Release: 1.0.0
* @link https://github.com/dmamontov/restnormalizer/
* @since Class available since Release 1.0.0
*/
class RestNormalizer
{
/**
* Cleanup of null values
* @var boolean
* @access public
*/
public $clear = true;
/**
* Sorted file validation
* @var array
* @access private
*/
private $validation = array();
/**
* File validation
* @var array
* @access private
*/
private $originalValidation = array();
/**
* Class constructor
* @return void
* @access public
* @final
*/
final public function __construct()
{
if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
date_default_timezone_set(@date_default_timezone_get());
}
}
/**
* Installation file validation
* @param string $file The path to the file validation
* @return void
* @access public
* @final
*/
final public function setValidation($file)
{
if (is_null($file) || is_file($file) === false
|| json_decode(file_get_contents($file)) === null
|| $this->parseConfig($file) === false) {
ICrmOrderActions::eventLog('RestNormalizer', 'intaro.intarocrm', 'Incorrect file normalize.');
return false;
}
}
/**
* Parsing the file validation
* @param string $file The path to the file validation
* @return boolean
* @access private
* @final
*/
final private function parseConfig($file)
{
if (json_decode(file_get_contents($file)) !== null) {
$this->originalValidation = json_decode(file_get_contents($file), true);
return true;
} else {
return false;
}
}
/**
* Starting the process of normalization of the data
* @param array $data The key is to sort the data validation
* @param string $key Data normalization
* @return array
* @access public
* @final
*/
final public function normalize($data, $key = false)
{
if (is_string($data)) {
$data = json_decode($data, true);
}
if (is_string($key) && isset($this->originalValidation[ $key ])) {
$this->validation = $this->originalValidation[ $key ];
} else {
$this->validation = $this->originalValidation;
}
if (!is_array($data) || count($data) < 1) {
ICrmOrderActions::eventLog('RestNormalizer', 'intaro.intarocrm', 'Incorrect data array.');
return false;
}
return $this->formatting($data);
}
/**
* Data formatting
* @param array $data The key is to sort the data validation
* @param boolean $skip Skip perform methods intended for the first run
* @return array
* @access private
* @final
*/
final private function formatting($data, $skip = false)
{
$formatted = array();
foreach ($data as $code => $value) {
if (isset($this->validation[ $code ]) && $this->validation[ $code ]['type'] == 'skip') {
$formatted[ $code ] = $value;
}elseif (isset($this->validation[ $code ]) && is_array($value) === false) {
$formatted[ $code ] = $this->setFormat($value, $this->validation[ $code ]);
} elseif (is_array($value)) {
$formatted[ $code ] = $this->formatting($value, true);
}
if ($formatted[ $code ] === null || $formatted[ $code ] == '' || count($formatted[ $code ]) < 1) {
if ($this->clear === true) {
unset($formatted[ $code ]);
}
if (isset($this->validation[ $code ]['required']) && $this->validation[ $code ]['required'] === true) {
$formatted = array();
break;
}
}
}
if ($skip === false) {
foreach ($this->validation as $code => $valid) {
if (isset($valid['required']) && $valid['required'] === true && isset($formatted[ $code ]) === false) {
ICrmOrderActions::eventLog('RestNormalizer', 'intaro.intarocrm', "NOT VALID: $code");
}
}
$formatted = $this->multiConvert($formatted);
}
return count($formatted) < 1 ? false : $formatted;
}
/**
* Formatting data depending on the type
* @param mixed $data The value to be formatted
* @param array $validation The data for the current data type validation
* @return mixed
* @access private
* @final
*/
final private function setFormat($data, $validation)
{
$format = null;
switch ($validation['type']) {
case 'string':
$format = $this->setString($data, $validation);
break;
case 'int':
$format = $this->setInt($data, $validation);
break;
case 'double':
$format = $this->setDouble($data, $validation);
break;
case 'bool':
$format = $this->setBool($data, $validation);
break;
case 'datetime':
$format = $this->setDateTime($data, $validation);
break;
case 'enum':
$format = $this->setEnum($data, $validation);
break;
}
return $format;
}
/**
* Formatting data for strings
* @param string $data String to formatting
* @param array $validation The data for the current data type validation
* @return string
* @access private
* @final
*/
final private function setString($data, $validation)
{
$data = trim((string) $data);
if (isset($validation['default']) && is_string($validation['default']) && trim($validation['default']) != ''
&& ($data == '' || is_string($data) === false)) {
$data = trim($validation['default']);
} elseif ($data == '' || is_string($data) === false) {
return null;
} elseif (isset($validation['min']) && mb_strlen($data) < $validation['min']) {
$pad = isset($validation['pad']) && mb_strlen($validation['pad']) == 1 ? $validation['pad'] : ' ';
$data .= str_repeat($pad, $validation['min'] - mb_strlen($data));
}elseif (isset($validation['max']) && mb_strlen($data) > $validation['max']) {
$data = mb_substr($data, 0, $validation['max']);
}
return (string) $data;
}
/**
* Formatting data for integers
* @param integer $data Integer to formatting
* @param array $validation The data for the current data type validation
* @return integer
* @access private
* @final
*/
final private function setInt($data, $validation)
{
if (isset($validation['default']) && is_numeric($validation['default']) && is_numeric($data) === false) {
$data = $validation['default'];
} elseif (is_numeric($data) === false) {
return null;
} elseif (isset($validation['min']) && $data < $validation['min']) {
$data += $validation['min'] - $data;
} elseif (isset($validation['max']) && $data > $validation['max']) {
$data -= $data - $validation['max'];
}
return (int) $data;
}
/**
* Formatting data for floating-point numbers
* @param float $data Floating-point number to formatting
* @param array $validation The data for the current data type validation
* @return float
* @access private
* @final
*/
final private function setDouble($data, $validation)
{
if (isset($validation['default']) && is_numeric($validation['default']) && is_numeric($data) === false) {
$data = $validation['default'];
} elseif (is_numeric($data) === false) {
return null;
} elseif (isset($validation['min']) && $data < $validation['min']) {
$data += $validation['min'] - $data;
} elseif (isset($validation['max']) && $data > $validation['max']) {
$data -= $data - $validation['max'];
}
if (isset($validation['decimals'])) {
$data = number_format($data, $validation['decimals'], '.', '');
}
return (double) $data;
}
/**
* Formatting data for logical values
* @param boolean $data Boolean value to formatting
* @param array $validation The data for the current data type validation
* @return boolean
* @access private
* @final
*/
final private function setBool($data, $validation)
{
if (isset($validation['default']) && is_bool($validation['default']) && is_bool($data) === false) {
$data = $validation['default'];
} elseif (is_bool($data) === false) {
return null;
}
return (bool) $data;
}
/**
* Formatting data for date and time
* @param mixed $data Date and time of to formatting
* @param array $validation The data for the current data type validation
* @param boolean $skip Skip perform methods intended for the first run
* @return mixed
* @access private
* @final
*/
final private function setDateTime($data, $validation, $skip = false)
{
if (is_a($data, 'DateTime') && isset($validation['format'])) {
$data = (string) $data->format($validation['format']);
} elseif (is_string($data) && isset($validation['format']) && strtotime($data) !== false) {
$data = (string) date($validation['format'], strtotime($data));
} elseif (is_numeric($data) && isset($validation['format'])) {
$data = (string) date($validation['format'], (int) $data);
} elseif (is_numeric($data)) {
$data = (int) $data;
} elseif (isset($validation['format'])) {
$data = (string) date($validation['format']);
} elseif (isset($validation['default']) && $skip === false) {
$data = $this->setDateTime(time(), $validation, true);
} else {
return null;
}
return $data;
}
/**
* Formatting data for enum
* @param string $data Enum to formatting
* @param array $validation The data for the current data type validation
* @return string
* @access private
* @final
*/
final private function setEnum($data, $validation)
{
if (isset($validation['values']) === false || count($validation['values']) < 1) {
return null;
} elseif (isset($validation['default']) && in_array($validation['default'], $validation['values']) === false) {
return null;
} elseif (in_array($data, $validation['values']) === false
&& isset($validation['default']) && in_array($validation['default'], $validation['values'])) {
$data = $validation['default'];
} elseif (in_array($data, $validation['values']) === false) {
return null;
}
return $data;
}
/**
* Installing the specified encoding
* @param array $data The original dataset
* @return array
* @access private
* @final
*/
final private function multiConvert($data)
{
global $APPLICATION;
if (is_array($data)) {
foreach ($data as $code => $value) {
$data[$APPLICATION->ConvertCharset($code, SITE_CHARSET, 'utf-8')] = is_array($value)
? $this->multiConvert($value)
: $APPLICATION->ConvertCharset($value, SITE_CHARSET, 'utf-8');
}
return $data;
} else {
return $APPLICATION->ConvertCharset($data, SITE_CHARSET, 'utf-8');
}
return $data;
}
}
?>

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<options>
<contragents>
<contragent id="individual">Физ. лицо</contragent>
<contragent id="legal-entity">Юр. лицо</contragent>
<contragent id="enterpreneur">ИП</contragent>
</contragents>
<fields>
<field id="fio">Ф.И.О.</field>
<field id="phone">Телефон</field>
<field id="email">E-mail</field>
<field id="text">Адрес (строкой)</field>
<field id="city">Город</field>
<field id="index">Индекс</field>
<field id="street">Улица</field>
<field id="building">Строение</field>
<field id="flat">Квартира</field>
<field id="intercomcode">Домофон</field>
<field id="floor">Этаж</field>
<field id="block">Подъезд</field>
<field id="house">Строение / корпус</field>
<field id="legalName" group="legal-entity, enterpreneur">Полное наименование</field>
<field id="legalAddress" group="legal-entity, enterpreneur">Адрес регистрации (Юридический адрес)</field>
<field id="INN" group="legal-entity, enterpreneur">ИНН</field>
<field id="OKPO" group="legal-entity, enterpreneur">ОКПО</field>
<field id="BIK" group="legal-entity, enterpreneur">БИК</field>
<field id="bank" group="legal-entity, enterpreneur">Банк</field>
<field id="bankAddress" group="legal-entity, enterpreneur">Адрес банка</field>
<field id="corrAccount" group="legal-entity, enterpreneur">Корреспондентский счет</field>
<field id="bankAccount" group="legal-entity, enterpreneur">Расчетный счет</field>
<field id="KPP" group="legal-entity">КПП</field>
<field id="OGRN" group="legal-entity">ОГРН</field>
<field id="OGRNIP" group="enterpreneur">ОГРНИП</field>
<field id="certificateNumber" group="enterpreneur">Номер свидетельства</field>
<field id="certificateDate" group="enterpreneur">Дата свидетельства</field>
</fields>
</options>

View File

@ -0,0 +1,379 @@
{
"customers": {
"externalId": {
"type": "string",
"required": true
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"patronymic": {
"type": "string"
},
"email": {
"type": "string"
},
"number": {
"type": "string"
},
"site": {
"type": "string"
},
"index": {
"type": "string"
},
"country": {
"type": "string"
},
"region": {
"type": "string"
},
"city": {
"type": "string"
},
"street": {
"type": "string"
},
"building": {
"type": "string"
},
"flat": {
"type": "string"
},
"intercomCode": {
"type": "string"
},
"floor": {
"type": "int"
},
"block": {
"type": "int"
},
"house": {
"type": "string"
},
"metro": {
"type": "string"
},
"notes": {
"type": "string"
},
"text": {
"type": "string"
},
"createdAt": {
"type": "datetime",
"format": "Y-m-d H:i:s"
},
"vip": {
"type": "bool",
"default": false
},
"bad": {
"type": "bool",
"default": false
},
"commentary": {
"type": "string"
},
"customFields": {
"type": "skip"
},
"contragentType": {
"type": "enum",
"default": "individual",
"values": ["individual", "legal-entity", "enterpreneur"]
},
"legalName": {
"type": "string"
},
"legalAddress": {
"type": "string"
},
"INN": {
"type": "string"
},
"OKPO": {
"type": "string"
},
"KPP": {
"type": "string"
},
"OGRN": {
"type": "string"
},
"OGRNIP": {
"type": "string"
},
"certificateNumber": {
"type": "string"
},
"certificateDate": {
"type": "datetime",
"format": "Y-m-d"
},
"BIK": {
"type": "string"
},
"bank": {
"type": "string"
},
"bankAddress": {
"type": "string"
},
"corrAccount": {
"type": "string"
},
"bankAccount": {
"type": "string"
},
"managerId": {
"type": "int"
}
},
"orders": {
"number": {
"type": "string"
},
"externalId": {
"type": "string",
"required": true
},
"createdAt": {
"type": "datetime",
"format": "Y-m-d H:i:s"
},
"discount": {
"type": "double",
"default": 0,
"min": 0,
"decimals": 2
},
"discountPercent": {
"type": "double",
"default": 0,
"max": 100,
"min": 0,
"decimals": 2
},
"mark": {
"type": "int",
"max": 10,
"min": 0
},
"markDatetime": {
"type": "datetime",
"format": "Y-m-d H:i:s"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"patronymic": {
"type": "string"
},
"phone": {
"type": "string"
},
"additionalPhone": {
"type": "string"
},
"email": {
"type": "string"
},
"site": {
"type": "string"
},
"call": {
"type": "bool",
"default": false
},
"expired": {
"type": "bool",
"default": false
},
"customerComment": {
"type": "string"
},
"managerComment": {
"type": "string"
},
"paymentDetail": {
"type": "string"
},
"statusComment": {
"type": "string"
},
"customFields": {
"type": "skip"
},
"contragentType": {
"type": "enum",
"default": "individual",
"values": ["individual", "legal-entity", "enterpreneur"]
},
"legalName": {
"type": "string"
},
"legalAddress": {
"type": "string"
},
"INN": {
"type": "string"
},
"OKPO": {
"type": "string"
},
"KPP": {
"type": "string"
},
"OGRN": {
"type": "string"
},
"OGRNIP": {
"type": "string"
},
"certificateNumber": {
"type": "string"
},
"certificateDate": {
"type": "datetime",
"format": "Y-m-d"
},
"BIK": {
"type": "string"
},
"bank": {
"type": "string"
},
"bankAddress": {
"type": "string"
},
"corrAccount": {
"type": "string"
},
"bankAccount": {
"type": "string"
},
"orderType": {
"type": "string"
},
"orderMethod": {
"type": "string"
},
"customerId": {
"type": "string"
},
"managerId": {
"type": "int"
},
"paymentType": {
"type": "string"
},
"paymentStatus": {
"type": "string"
},
"status": {
"type": "string"
},
"sourceId": {
"type": "string"
},
"initialPrice": {
"type": "double",
"default": 0,
"min": 0,
"decimals": 2
},
"quantity": {
"type": "double",
"default": 1,
"min": 1,
"decimals": 1
},
"properties": {
"type": "skip"
},
"productId": {
"type": "string"
},
"productName": {
"type": "string"
},
"comment": {
"type": "string"
},
"purchasePrice": {
"type": "double",
"default": 0,
"min": 0,
"decimals": 1
},
"code": {
"type": "string"
},
"integrationCode": {
"type": "string"
},
"data": {
"type": "skip"
},
"service": {
"type": "skip"
},
"cost": {
"type": "string"
},
"date": {
"type": "datetime",
"format": "Y-m-d"
},
"index": {
"type": "string"
},
"country": {
"type": "string"
},
"region": {
"type": "string"
},
"city": {
"type": "string"
},
"street": {
"type": "string"
},
"building": {
"type": "string"
},
"flat": {
"type": "string"
},
"intercomCode": {
"type": "string"
},
"floor": {
"type": "int"
},
"block": {
"type": "int"
},
"house": {
"type": "string"
},
"metro": {
"type": "string"
},
"notes": {
"type": "string"
},
"text": {
"type": "string"
}
}
}

View File

@ -14,7 +14,11 @@ class ICrmOrderEvent {
protected static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N protected static $CRM_PAYMENT = 'payment_arr'; //order payment Y/N
protected static $CRM_ORDER_LAST_ID = 'order_last_id'; protected static $CRM_ORDER_LAST_ID = 'order_last_id';
protected static $CRM_ORDER_PROPS = 'order_props'; protected static $CRM_ORDER_PROPS = 'order_props';
protected static $CRM_LEGAL_DETAILS = 'legal_details';
protected static $CRM_CUSTOM_FIELDS = 'custom_fields';
protected static $CRM_CONTRAGENT_TYPE = 'contragent_type';
protected static $CRM_ORDER_FAILED_IDS = 'order_failed_ids'; protected static $CRM_ORDER_FAILED_IDS = 'order_failed_ids';
protected static $CRM_SITES_LIST = 'sites_list';
/** /**
* onBeforeOrderAdd * onBeforeOrderAdd
@ -54,7 +58,6 @@ class ICrmOrderEvent {
* @param mixed $arFields - Order arFields * @param mixed $arFields - Order arFields
*/ */
function onUpdateOrder($ID, $arFields) { function onUpdateOrder($ID, $arFields) {
if(isset($GLOBALS['INTARO_CRM_ORDER_ADD']) && $GLOBALS['INTARO_CRM_ORDER_ADD']) if(isset($GLOBALS['INTARO_CRM_ORDER_ADD']) && $GLOBALS['INTARO_CRM_ORDER_ADD'])
return; return;
@ -126,7 +129,6 @@ class ICrmOrderEvent {
return true; return true;
} }
$GLOBALS['INTARO_CRM_ORDER_ADD'] = false;
$GLOBALS['INTARO_CRM_FROM_HISTORY'] = false; $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false;
$api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0); $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0);
@ -138,9 +140,13 @@ class ICrmOrderEvent {
$optionsPayTypes = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 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 $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses
$optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0));
$optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0));
$optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0)); $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 IntaroCrm\RestApi($api_host, $api_key); $api = new RetailCrm\RestApi($api_host, $api_key);
$arParams = ICrmOrderActions::clearArr(array( $arParams = ICrmOrderActions::clearArr(array(
'optionsOrderTypes' => $optionsOrderTypes, 'optionsOrderTypes' => $optionsOrderTypes,
@ -148,7 +154,11 @@ class ICrmOrderEvent {
'optionsPayTypes' => $optionsPayTypes, 'optionsPayTypes' => $optionsPayTypes,
'optionsPayStatuses' => $optionsPayStatuses, 'optionsPayStatuses' => $optionsPayStatuses,
'optionsPayment' => $optionsPayment, 'optionsPayment' => $optionsPayment,
'optionsOrderProps' => $optionsOrderProps 'optionsOrderProps' => $optionsOrderProps,
'optionsLegalDetails' => $optionsLegalDetails,
'optionsContragentType' => $optionsContragentType,
'optionsSitesList' => $optionsSitesList,
'optionsCustomFields' => $optionsCustomFields
)); ));
$arOrder = CSaleOrder::GetById($ID); $arOrder = CSaleOrder::GetById($ID);
@ -168,8 +178,12 @@ class ICrmOrderEvent {
$arFieldsNew = array_merge($arFieldsNew, $arFields); $arFieldsNew = array_merge($arFieldsNew, $arFields);
$arOrder = $arFieldsNew; $arOrder = $arFieldsNew;
} }
if(count($optionsSitesList)>1){
$result = ICrmOrderActions::orderCreate($arOrder, $api, $arParams, true, $optionsSitesList[$arOrder['LID']]);
}
else{
$result = ICrmOrderActions::orderCreate($arOrder, $api, $arParams, true); $result = ICrmOrderActions::orderCreate($arOrder, $api, $arParams, true);
}
if(!$result) { if(!$result) {
ICrmOrderActions::eventLog('ICrmOrderEvent::writeDataOnOrderCreate', 'ICrmOrderActions::orderCreate', 'error during creating order'); ICrmOrderActions::eventLog('ICrmOrderEvent::writeDataOnOrderCreate', 'ICrmOrderActions::orderCreate', 'error during creating order');
@ -217,7 +231,7 @@ class ICrmOrderEvent {
//saved cat params //saved cat params
$optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses $optionsPayStatuses = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)); // --statuses
$api = new IntaroCrm\RestApi($api_host, $api_key); $api = new RetailCrm\RestApi($api_host, $api_key);
$order = array(); $order = array();
@ -239,14 +253,9 @@ class ICrmOrderEvent {
try { try {
$api->orderEdit($order); $api->orderEdit($order);
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'ICrmOrderEvent::onSaleCancelOrder', 'IntaroCrm\RestApi::orderEdit', 'ICrmOrderEvent::onSaleCancelOrder', 'RetailCrm\RestApi::orderEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'ICrmOrderEvent::onSaleCancelOrder', 'IntaroCrm\RestApi::orderEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
@ -291,7 +300,7 @@ class ICrmOrderEvent {
//saved cat params //saved cat params
$optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)); $optionsPayment = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0));
$api = new IntaroCrm\RestApi($api_host, $api_key); $api = new RetailCrm\RestApi($api_host, $api_key);
$order = array( $order = array(
'externalId' => (int) $ID, 'externalId' => (int) $ID,
@ -302,14 +311,9 @@ class ICrmOrderEvent {
try { try {
$api->orderEdit($order); $api->orderEdit($order);
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'ICrmOrderEvent::onSalePayOrder', 'IntaroCrm\RestApi::orderEdit', 'ICrmOrderEvent::onSalePayOrder', 'RetailCrm\RestApi::orderEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'ICrmOrderEvent::onSalePayOrder', 'IntaroCrm\RestApi::orderEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }

View File

@ -0,0 +1,13 @@
- Модуль переведен на новую версию API
- Добавлена поддержка реквизитов юр. лиц
- Добавлена многосайтовость
- Добавлена выборочная загрузка заказов из настроек модуля
- Оптимизирована загрузка старых заказов
- Исправлена ошибка со скидками на заказ и товары
- Исправлена ошибка с удалением id товара в заказе
- Исправлена ошибка пустого $_SERVER['SERVER_NAME'] при экспорте каталога
- Исправлена ошибка с неправильной скидкой у товара при наличии копеек
- Исправлена ошибка с пропаданием автоматических служб доставок из настроек модуля
- Исправлена неправельная выгрузка сервисов для служб доставок
- Исправлено не правельное определение местоположения
- Рефакторинг модуля

View File

@ -10,6 +10,13 @@ if (!CModule::IncludeModule("catalog"))
if (!CModule::IncludeModule("intaro.intarocrm")) if (!CModule::IncludeModule("intaro.intarocrm"))
return; return;
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){
if($ar['DEF'] == 'Y'){
$SERVER_NAME = $ar['SERVER_NAME'];//разделить потом с учетом многосайтовости
}
}
$iblockProperties = Array( $iblockProperties = Array(
"article" => "article", "article" => "article",
"manufacturer" => "manufacturer", "manufacturer" => "manufacturer",
@ -69,6 +76,7 @@ $loader->propertiesUnitSKU = $IBLOCK_PROPERTY_UNIT_SKU;
$loader->propertiesProduct = $IBLOCK_PROPERTY_PRODUCT; $loader->propertiesProduct = $IBLOCK_PROPERTY_PRODUCT;
$loader->propertiesUnitProduct = $IBLOCK_PROPERTY_UNIT_PRODUCT; $loader->propertiesUnitProduct = $IBLOCK_PROPERTY_UNIT_PRODUCT;
$loader->filename = $SETUP_FILE_NAME; $loader->filename = $SETUP_FILE_NAME;
$loader->serverName = $SERVER_NAME;
$loader->application = $APPLICATION; $loader->application = $APPLICATION;
$loader->loadPurchasePrice = $LOAD_PURCHASE_PRICE == 'Y'; $loader->loadPurchasePrice = $LOAD_PURCHASE_PRICE == 'Y';
$loader->Load(); $loader->Load();

8
intaro.intarocrm/include.php Executable file → Normal file
View File

@ -2,11 +2,13 @@
CModule::AddAutoloadClasses( CModule::AddAutoloadClasses(
'intaro.intarocrm', // module name 'intaro.intarocrm', // module name
array ( array (
'IntaroCrm\RestApi' => 'classes/general/RestApi.php', 'RestNormalizer' => 'classes/general/RestNormalizer.php',
'RetailCrm\RestApi' => 'classes/general/RestApi.php',
'RetailCrm\Response\ApiResponse' => 'classes/general/Response/ApiResponse.php',
'ICrmOrderActions' => 'classes/general/ICrmOrderActions.php', 'ICrmOrderActions' => 'classes/general/ICrmOrderActions.php',
'ICMLLoader' => 'classes/general/ICMLLoader.php', 'ICMLLoader' => 'classes/general/ICMLLoader.php',
'ICrmOrderEvent' => 'classes/general/events/ICrmOrderEvent.php', 'ICrmOrderEvent' => 'classes/general/events/ICrmOrderEvent.php',
'IntaroCrm\Exception\ApiException' => 'classes/general/Exception/ApiException.php', 'RetailCrm\Exception\InvalidJsonException' => 'classes/general/Exception/InvalidJsonException.php',
'IntaroCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php' 'RetailCrm\Exception\CurlException' => 'classes/general/Exception/CurlException.php',
) )
); );

429
intaro.intarocrm/install/index.php Executable file → Normal file
View File

@ -24,6 +24,7 @@ class intaro_intarocrm extends CModule {
var $INTARO_CRM_EXPORT = 'intarocrm'; var $INTARO_CRM_EXPORT = 'intarocrm';
var $CRM_API_HOST_OPTION = 'api_host'; var $CRM_API_HOST_OPTION = 'api_host';
var $CRM_API_KEY_OPTION = 'api_key'; var $CRM_API_KEY_OPTION = 'api_key';
var $CRM_SITES_LIST= 'sites_list';
var $CRM_ORDER_TYPES_ARR = 'order_types_arr'; var $CRM_ORDER_TYPES_ARR = 'order_types_arr';
var $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr'; var $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr';
var $CRM_DELIVERY_SERVICES_ARR = 'deliv_services_arr'; var $CRM_DELIVERY_SERVICES_ARR = 'deliv_services_arr';
@ -31,8 +32,10 @@ class intaro_intarocrm extends CModule {
var $CRM_PAYMENT_STATUSES = 'pay_statuses_arr'; var $CRM_PAYMENT_STATUSES = 'pay_statuses_arr';
var $CRM_PAYMENT = 'payment_arr'; //order payment Y/N var $CRM_PAYMENT = 'payment_arr'; //order payment Y/N
var $CRM_ORDER_LAST_ID = 'order_last_id'; var $CRM_ORDER_LAST_ID = 'order_last_id';
var $CRM_ORDER_SITES = 'sites_ids';
var $CRM_ORDER_PROPS = 'order_props'; var $CRM_ORDER_PROPS = 'order_props';
var $CRM_LEGAL_DETAILS = 'legal_details';
var $CRM_CUSTOM_FIELDS = 'custom_fields';
var $CRM_CONTRAGENT_TYPE = 'contragent_type';
var $CRM_ORDER_DISCHARGE = 'order_discharge'; var $CRM_ORDER_DISCHARGE = 'order_discharge';
var $CRM_ORDER_FAILED_IDS = 'order_failed_ids'; var $CRM_ORDER_FAILED_IDS = 'order_failed_ids';
var $CRM_ORDER_HISTORY_DATE = 'order_history_date'; var $CRM_ORDER_HISTORY_DATE = 'order_history_date';
@ -47,7 +50,7 @@ class intaro_intarocrm extends CModule {
include($path . "/version.php"); include($path . "/version.php");
$this->MODULE_VERSION = $arModuleVersion["VERSION"]; $this->MODULE_VERSION = $arModuleVersion["VERSION"];
$this->MODULE_VERSION_DATE = $arModuleVersion["VERSION_DATE"]; $this->MODULE_VERSION_DATE = $arModuleVersion["VERSION_DATE"];
$this->MODULE_NAME = GetMessage('MODULE_NAME'); $this->MODULE_NAME = GetMessage('INTARO_MODULE_NAME');
$this->MODULE_DESCRIPTION = GetMessage('MODULE_DESCRIPTION'); $this->MODULE_DESCRIPTION = GetMessage('MODULE_DESCRIPTION');
$this->PARTNER_NAME = GetMessage('MODULE_PARTNER_NAME'); $this->PARTNER_NAME = GetMessage('MODULE_PARTNER_NAME');
$this->PARTNER_URI = GetMessage('MODULE_PARTNER_URI'); $this->PARTNER_URI = GetMessage('MODULE_PARTNER_URI');
@ -73,77 +76,55 @@ class intaro_intarocrm extends CModule {
} }
include($this->INSTALL_PATH . '/../classes/general/RestApi.php'); include($this->INSTALL_PATH . '/../classes/general/RestApi.php');
include($this->INSTALL_PATH . '/../classes/general/Response/ApiResponse.php');
include($this->INSTALL_PATH . '/../classes/general/ICrmOrderActions.php'); include($this->INSTALL_PATH . '/../classes/general/ICrmOrderActions.php');
include($this->INSTALL_PATH . '/../classes/general/ICMLLoader.php'); include($this->INSTALL_PATH . '/../classes/general/ICMLLoader.php');
include($this->INSTALL_PATH . '/../classes/general/Exception/ApiException.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');
$step = intval($_REQUEST['step']); $step = intval($_REQUEST['step']);
$arResult['orderProps'] = array( if (file_exists($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.intarocrm/classes/general/config/options.xml')) {
array( $options = simplexml_load_file($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.intarocrm/classes/general/config/options.xml');
'NAME' => GetMessage('FIO'),
'ID' => 'fio'
),
array(
'NAME' => GetMessage('PHONE'),
'ID' => 'phone'
),
array(
'NAME' => GetMessage('EMAIL'),
'ID' => 'email'
),
array(
'NAME' => GetMessage('ADDRESS'),
'ID' => 'text'
),
// address
/* array(
'NAME' => GetMessage('COUNTRY'),
'ID' => 'country'
),
array(
'NAME' => GetMessage('REGION'),
'ID' => 'region'
),
array(
'NAME' => GetMessage('CITY'),
'ID' => 'city'
), */
array(
'NAME' => GetMessage('ZIP'),
'ID' => 'index'
),
array(
'NAME' => GetMessage('STREET'),
'ID' => 'street'
),
array(
'NAME' => GetMessage('BUILDING'),
'ID' => 'building'
),
array(
'NAME' => GetMessage('FLAT'),
'ID' => 'flat'
),
array(
'NAME' => GetMessage('INTERCOMCODE'),
'ID' => 'intercomcode'
),
array(
'NAME' => GetMessage('FLOOR'),
'ID' => 'floor'
),
array(
'NAME' => GetMessage('BLOCK'),
'ID' => 'block'
),
array(
'NAME' => GetMessage('HOUSE'),
'ID' => 'house'
)
);
foreach($options->contragents->contragent as $contragent)
{
$type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$contragent["id"];
$arResult['contragentType'][] = $type;
unset ($type);
}
foreach($options->fields->field as $field)
{
$type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$field["id"];
if ($field["group"] == 'custom') {
$arResult['customFields'][] = $type;
} elseif(!$field["group"]){
$arResult['orderProps'][] = $type;
} else{
$groups = explode(",", (string)$field["group"]);
foreach($groups as $group){
$type["GROUP"][] = trim($group);
}
$arResult['legalDetails'][] = $type;
}
unset($type);
}
}
if($step == 11){
$arResult['arSites'] = array();
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){
$arResult['arSites'][] = $ar;
}
if(count($arResult['arSites'])<2){
$step = 2;
}
}
if ($step <= 1) { if ($step <= 1) {
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE'; $arResult['errCode'] = 'ERR_SALE';
@ -158,14 +139,80 @@ class intaro_intarocrm extends CModule {
} }
$arResult['arSites'] = array(); $arResult['arSites'] = array();
$rsSites = CSite::GetList($by, $sort, array()); $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()) while ($ar = $rsSites->Fetch())
$arResult['arSites'][] = $ar; $arResult['arSites'][] = $ar;
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php' GetMessage('MODULE_INSTALL_TITLE'), $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
); );
} else if ($step == 2) { } else if ($step == 11) {
//new page
if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE';
}
if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK';
}
if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG';
}
if (isset($arResult['errCode']) && $arResult['errCode']) {
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
);
return;
}
$api_host = htmlspecialchars(trim($_POST[$this->CRM_API_HOST_OPTION]));
$api_key = htmlspecialchars(trim($_POST[$this->CRM_API_KEY_OPTION]));
// form correct url
$api_host = parse_url($api_host);
if($api_host['scheme'] != 'https') $api_host['scheme'] = 'https';
$api_host = $api_host['scheme'] . '://' . $api_host['host'];
if (!$api_host || !$api_key) {
$arResult['errCode'] = 'ERR_FIELDS_API_HOST';
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
);
return;
}
$this->INTARO_CRM_API = new RetailCrm\RestApi($api_host, $api_key);
//api key ok and sites list
try {
$arResult['sitesList'] = $this->INTARO_CRM_API->sitesList()->sites;
} catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'RetailCrm\RestApi::sitesList',
$e->getCode() . ': ' . $e->getMessage()
);
$arResult['errCode'] = 'ERR_' . $e->getCode();
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
);
return;
}
COption::SetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, $api_host);
COption::SetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, $api_key);
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step11.php'
);
} else if ($step == 2) {//доставки, оплаты, типы заказов
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE'; $arResult['errCode'] = 'ERR_SALE';
@ -179,11 +226,6 @@ class intaro_intarocrm extends CModule {
$arResult['errCode'] = 'ERR_CATALOG'; $arResult['errCode'] = 'ERR_CATALOG';
} }
$arResult['arSites'] = array();
$rsSites = CSite::GetList($by, $sort, array());
while ($ar = $rsSites->Fetch())
$arResult['arSites'][] = $ar;
if (isset($arResult['errCode']) && $arResult['errCode']) { if (isset($arResult['errCode']) && $arResult['errCode']) {
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), GetMessage('MODULE_INSTALL_TITLE'),
@ -192,28 +234,34 @@ class intaro_intarocrm extends CModule {
return; return;
} }
$arResult['arSites'] = array();
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){
if(!$ar["SERVER_NAME"]){
$arResult['errCode'] = 'URL_NOT_FOUND';
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
);
return;
}
else{
$arResult['arSites'][] = $ar;
}
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) { 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_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
$this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key); $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key);
//prepare crm lists //prepare crm lists
try { try {
$arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList(); $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList()->orderTypes;
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::orderTypesList', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::orderTypesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$APPLICATION->RestartBuffer();
header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
die(json_encode(array("success" => false)));
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::orderTypesList::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
@ -223,21 +271,15 @@ class intaro_intarocrm extends CModule {
} }
try { try {
$arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList(); $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList()->deliveryTypes;
$arResult['deliveryServicesList'] = $this->INTARO_CRM_API->deliveryServicesList(); $arResult['deliveryServicesList'] = $this->INTARO_CRM_API->deliveryServicesList()->deliveryServices;
$arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList(); $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList()->paymentTypes;
$arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); // --statuses $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList()->paymentStatuses; // --statuses
$arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList(); $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList()->statuses;
$arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList(); // -- statuses groups $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList()->statusGroups; // -- statuses groups
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::*List', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::*List::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::*List::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
@ -287,7 +329,8 @@ class intaro_intarocrm extends CModule {
'NAME' => 'ASC' 'NAME' => 'ASC'
), ),
array( array(
'ACTIVE' => 'Y' 'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
) )
); );
@ -486,15 +529,32 @@ class intaro_intarocrm extends CModule {
die(json_encode(array("success" => true, "result" => $input))); die(json_encode(array("success" => true, "result" => $input)));
} }
if(count($arResult['arSites'])>1){
// api load
$api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
foreach($arResult['arSites'] as $site){
if($_POST['sites-id-'.$site['LID']] && !empty($_POST['sites-id-'.$site['LID']])){
$siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-'.$site['LID']]));
}
}
if (count($arResult['arSites'])!=count($siteCode)) {
$arResult['errCode'] = 'ERR_FIELDS_API_HOST';
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step11.php'
);
return;
}
$this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key);
COption::SetOptionString($this->MODULE_ID, $this->CRM_SITES_LIST, serialize($siteCode));
}
else{//если 1 сайт
$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]));
// empty == select all
$orderSites = array();
/* foreach ($_POST[$this->CRM_ORDER_SITES] as $site) {
$orderSites[] = htmlspecialchars(trim($site));
} */
// form correct url // form correct url
$api_host = parse_url($api_host); $api_host = parse_url($api_host);
if($api_host['scheme'] != 'https') $api_host['scheme'] = 'https'; if($api_host['scheme'] != 'https') $api_host['scheme'] = 'https';
@ -509,27 +569,13 @@ class intaro_intarocrm extends CModule {
return; return;
} }
$this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key); $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key);
try { try {
$this->INTARO_CRM_API->paymentStatusesList(); $this->INTARO_CRM_API->paymentStatusesList()->paymentStatuses;
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::paymentStatusesList', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$arResult['errCode'] = 'ERR_' . $e->getCode();
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step1.php'
);
return;
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
@ -542,29 +588,22 @@ class intaro_intarocrm extends CModule {
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);
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_SITES, serialize($orderSites)); }
//prepare crm lists //prepare crm lists
try { try {
$arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList(); $arResult['orderTypesList'] = $this->INTARO_CRM_API->orderTypesList()->orderTypes;
$arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList(); $arResult['deliveryTypesList'] = $this->INTARO_CRM_API->deliveryTypesList()->deliveryTypes;
$arResult['deliveryServicesList'] = $this->INTARO_CRM_API->deliveryServicesList(); $arResult['deliveryServicesList'] = $this->INTARO_CRM_API->deliveryServicesList()->deliveryServices;
$arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList(); $arResult['paymentTypesList'] = $this->INTARO_CRM_API->paymentTypesList()->paymentTypes;
$arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList(); // --statuses $arResult['paymentStatusesList'] = $this->INTARO_CRM_API->paymentStatusesList()->paymentStatuses; // --statuses
$arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList(); $arResult['paymentList'] = $this->INTARO_CRM_API->orderStatusesList()->statuses;
$arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList(); // -- statuses groups $arResult['paymentGroupList'] = $this->INTARO_CRM_API->orderStatusGroupsList()->statusGroups; // -- statuses groups
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::*List', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::*List::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::*List::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
@ -607,7 +646,8 @@ class intaro_intarocrm extends CModule {
'NAME' => 'ASC' 'NAME' => 'ASC'
), ),
array( array(
'ACTIVE' => 'Y' 'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
) )
); );
@ -659,7 +699,7 @@ class intaro_intarocrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php' $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step2.php'
); );
} else if ($step == 3) { } else if ($step == 3) {//сопостовление свойств заказа
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
//handler //handler
} }
@ -674,7 +714,7 @@ class intaro_intarocrm extends CModule {
// api load // api load
$api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
$this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key); $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key);
//bitrix orderTypesList -- personTypes //bitrix orderTypesList -- personTypes
$dbOrderTypesList = CSalePersonType::GetList( $dbOrderTypesList = CSalePersonType::GetList(
@ -707,13 +747,18 @@ class intaro_intarocrm extends CModule {
); );
//bitrix deliveryServicesList //bitrix deliveryServicesList
$rsSites = CSite::GetList($by, $sort, array());
while ($ar = $rsSites->Fetch()){
$arResult['arSites'][] = $ar;
}
$dbDeliveryServicesList = CSaleDeliveryHandler::GetList( $dbDeliveryServicesList = CSaleDeliveryHandler::GetList(
array( array(
'SORT' => 'ASC', 'SORT' => 'ASC',
'NAME' => 'ASC' 'NAME' => 'ASC'
), ),
array( array(
'ACTIVE' => 'Y' 'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
) )
); );
@ -760,15 +805,9 @@ class intaro_intarocrm extends CModule {
'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']), 'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']),
'paymentTypes' => '' 'paymentTypes' => ''
))); )));
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryTypeEdit', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::deliveryTypeEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryTypeEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
@ -790,21 +829,14 @@ class intaro_intarocrm extends CModule {
'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']), 'description' => ICrmOrderActions::toJSON($arDeliveryTypesList['DESCRIPTION']),
'paymentTypes' => '' 'paymentTypes' => ''
))); )));
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryTypeEdit', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::deliveryTypeEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryTypeEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
foreach($arDeliveryServicesList['PROFILES'] as $id => $profile) { foreach($arDeliveryServicesList['PROFILES'] as $id => $profile) {
// send to crm // send to crm
try { try {
$this->INTARO_CRM_API->deliveryServiceEdit(ICrmOrderActions::clearArr(array( $this->INTARO_CRM_API->deliveryServiceEdit(ICrmOrderActions::clearArr(array(
@ -812,13 +844,7 @@ class intaro_intarocrm extends CModule {
'name' => ICrmOrderActions::toJSON($profile['TITLE']), 'name' => ICrmOrderActions::toJSON($profile['TITLE']),
'deliveryType' => $arDeliveryServicesList['SID'] 'deliveryType' => $arDeliveryServicesList['SID']
))); )));
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryServiceEdit',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryServiceEdit::CurlException', 'intaro.crm/install/index.php', 'IntaroCrm\RestApi::deliveryServiceEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
@ -892,7 +918,7 @@ class intaro_intarocrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php' $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step3.php'
); );
} else if ($step == 4) { } else if ($step == 4) {//выгрузка старых заказов
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
//handler //handler
} }
@ -904,8 +930,7 @@ class intaro_intarocrm extends CModule {
); );
} }
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
&& isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
ICrmOrderActions::uploadOrders(); // each 50 ICrmOrderActions::uploadOrders(); // each 50
$lastUpOrderId = COption::GetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0); $lastUpOrderId = COption::GetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, 0);
@ -966,14 +991,43 @@ class intaro_intarocrm extends CModule {
$orderPropsArr[$orderType['ID']] = $_orderPropsArr; $orderPropsArr[$orderType['ID']] = $_orderPropsArr;
} }
//legal details props
$legalDetailsArr = array();
foreach ($orderTypesList as $orderType) {
$_legalDetailsArr = array();
foreach ($arResult['legalDetails'] as $legalDetails) {
$_legalDetailsArr[$legalDetails['ID']] = htmlspecialchars(trim($_POST['legal-detail-' . $legalDetails['ID'] . '-' . $orderType['ID']]));
}
$legalDetailsArr[$orderType['ID']] = $_legalDetailsArr;
}
$customFieldsArr = array();
foreach ($orderTypesList as $orderType) {
$_customFieldsArr = array();
foreach ($arResult['customFields'] as $custom) {
$_customFieldsArr[$custom['ID']] = htmlspecialchars(trim($_POST['custom-fields-' . $custom['ID'] . '-' . $orderType['ID']]));
}
$customFieldsArr[$orderType['ID']] = $_customFieldsArr;
}
//contragents type list
$contragentTypeArr = array();//сделать проверки
foreach ($orderTypesList as $orderType) {
$contragentTypeArr[$orderType['ID']] = htmlspecialchars(trim($_POST['contragent-type-' . $orderType['ID']]));
}
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_PROPS, serialize(ICrmOrderActions::clearArr($orderPropsArr))); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_PROPS, serialize(ICrmOrderActions::clearArr($orderPropsArr)));
COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOM_FIELDS, serialize(ICrmOrderActions::clearArr($customFieldsArr)));
COption::SetOptionString($this->MODULE_ID, $this->CRM_LEGAL_DETAILS, serialize(ICrmOrderActions::clearArr($legalDetailsArr)));
COption::SetOptionString($this->MODULE_ID, $this->CRM_CONTRAGENT_TYPE, serialize(ICrmOrderActions::clearArr($contragentTypeArr)));
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step4.php' $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step4.php'
); );
} else if ($step == 5) { } else if ($step == 5) {//экспорт каталога
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK'; $arResult['errCode'] = 'ERR_IBLOCK';
} }
@ -996,7 +1050,7 @@ class intaro_intarocrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), GetMessage('MODULE_INSTALL_TITLE'),
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php' $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/step5.php'
); );
} else if ($step == 6) { } else if ($step == 6) {//регистрация модуля
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK'; $arResult['errCode'] = 'ERR_IBLOCK';
@ -1114,6 +1168,12 @@ class intaro_intarocrm extends CModule {
$this->CopyFiles(); $this->CopyFiles();
if (isset($_POST['LOAD_NOW'])) { if (isset($_POST['LOAD_NOW'])) {
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){
if($ar['DEF'] == 'Y'){
$SERVER_NAME = $ar['SERVER_NAME'];//разделить потом с учетом многосайтовости
}
}
$loader = new ICMLLoader(); $loader = new ICMLLoader();
$loader->iblocks = $iblocks; $loader->iblocks = $iblocks;
@ -1122,6 +1182,7 @@ class intaro_intarocrm extends CModule {
$loader->propertiesUnitSKU = $propertiesUnitSKU; $loader->propertiesUnitSKU = $propertiesUnitSKU;
$loader->propertiesSKU = $propertiesSKU; $loader->propertiesSKU = $propertiesSKU;
$loader->filename = $filename; $loader->filename = $filename;
$loader->serverName = $SERVER_NAME;
$loader->application = $APPLICATION; $loader->application = $APPLICATION;
$loader->Load(); $loader->Load();
@ -1239,18 +1300,12 @@ class intaro_intarocrm extends CModule {
$api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0); $api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0); $api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
$this->INTARO_CRM_API = new \IntaroCrm\RestApi($api_host, $api_key); $this->INTARO_CRM_API = new \RetailCrm\RestApi($api_host, $api_key);
try { try {
$this->INTARO_CRM_API->statisticUpdate(); $this->INTARO_CRM_API->statisticUpdate();
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::statisticUpdate', 'intaro.crm/install/index.php', 'RetailCrm\RestApi::statisticUpdate::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/install/index.php', 'IntaroCrm\RestApi::statisticUpdate::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
@ -1280,6 +1335,10 @@ class intaro_intarocrm extends CModule {
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_LAST_ID); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_LAST_ID);
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_SITES); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_SITES);
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_PROPS); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_PROPS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_LEGAL_DETAILS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_CONTRAGENT_TYPE);
COption::RemoveOption($this->MODULE_ID, $this->CRM_CUSTOM_FIELDS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_SITES_LIST);
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_DISCHARGE);
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_HISTORY_DATE);

View File

@ -1,2 +0,0 @@
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/intaro.intarocrm/classes/general/agent.php');

15
intaro.intarocrm/install/step1.php Executable file → Normal file
View File

@ -11,7 +11,7 @@
<input type="hidden" name="lang" value="<?php echo LANGUAGE_ID ?>"> <input type="hidden" name="lang" value="<?php echo LANGUAGE_ID ?>">
<input type="hidden" name="id" value="intaro.intarocrm"> <input type="hidden" name="id" value="intaro.intarocrm">
<input type="hidden" name="install" value="Y"> <input type="hidden" name="install" value="Y">
<input type="hidden" name="step" value="2"> <input type="hidden" name="step" value="11">
<table class="adm-detail-content-table edit-table" id="edit1_edit_table"> <table class="adm-detail-content-table edit-table" id="edit1_edit_table">
<tbody> <tbody>
@ -26,9 +26,6 @@
<tr align="center"> <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>
<!--<tr align="center">
<td colspan="2"><b><?php echo GetMessage('INFO_3'); ?></b></td>
</tr>-->
<tr align="center"> <tr align="center">
<td colspan="2">&nbsp;</td> <td colspan="2">&nbsp;</td>
</tr> </tr>
@ -40,16 +37,6 @@
<td width="50%" class="adm-detail-content-cell-l"><?php echo GetMessage('ICRM_API_KEY'); ?></td> <td width="50%" class="adm-detail-content-cell-l"><?php echo GetMessage('ICRM_API_KEY'); ?></td>
<td width="50%" class="adm-detail-content-cell-r"><input type="text" id="api_key" name="api_key" value=""></td> <td width="50%" class="adm-detail-content-cell-r"><input type="text" id="api_key" name="api_key" value=""></td>
</tr> </tr>
<!--<tr>
<td width="50%" class="adm-detail-content-cell-l"><?php echo GetMessage('ICRM_SITES'); ?></td>
<td width="50%" class="adm-detail-content-cell-r">
<select id="sites_ids" name="sites_ids[]" multiple="multiple" size="3">
<?php foreach ($arResult['arSites'] as $site): ?>
<option value="<?php echo $site['LID'] ?>" selected="selected"><?php echo $site['NAME'] . ' (' . $site['LID'] . ')' ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>-->
</tbody> </tbody>
</table> </table>
<br /> <br />

View File

@ -0,0 +1,53 @@
<?php
IncludeModuleLangFile(__FILE__);
if(isset($arResult['errCode']) && $arResult['errCode'])
echo CAdminMessage::ShowMessage(GetMessage($arResult['errCode']));
?>
<div class="adm-detail-content-item-block">
<form action="<?php echo $APPLICATION->GetCurPage() ?>" method="POST">
<?php echo bitrix_sessid_post(); ?>
<input type="hidden" name="lang" value="<?php echo LANGUAGE_ID ?>">
<input type="hidden" name="id" value="intaro.intarocrm">
<input type="hidden" name="install" value="Y">
<input type="hidden" name="step" value="2">
<table class="adm-detail-content-table edit-table" id="edit1_edit_table">
<tbody>
<tr class="heading">
<td colspan="2">
<b><?php echo GetMessage('STEP_NAME'); ?></b>
</td>
</tr>
<tr align="center">
<td colspan="2"><b><?php echo GetMessage('INFO_1'); ?></b></td>
</tr>
<tr align="center">
<td colspan="2"><b><?php echo GetMessage('INFO_2'); ?></b></td>
</tr>
<tr align="center">
<td colspan="2">&nbsp;</td>
</tr>
<?php foreach ($arResult['arSites'] as $site): ?>
<tr>
<td width="50%" class="adm-detail-content-cell-l"><?php echo $site['NAME'] . ' (' . $site['LID'] . ')'; ?></td>
<td width="50%" class="adm-detail-content-cell-r">
<select class="typeselect" name="sites-id-<?php echo $site['LID']?>">
<?php foreach ($arResult['sitesList'] as $sitesList): ?>
<option value="<?php echo $sitesList['code'] ?>"><?php echo $sitesList['name']?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<br />
<div style="padding: 1px 13px 2px; height:28px;">
<div align="right" style="float:right; position:relative;">
<input type="submit" name="inst" value="<?php echo GetMessage("MOD_NEXT_STEP"); ?>" class="adm-btn-save">
</div>
</div>
</form>
</div>

0
intaro.intarocrm/install/step2.php Executable file → Normal file
View File

87
intaro.intarocrm/install/step3.php Executable file → Normal file
View File

@ -19,7 +19,6 @@ $defaultOrderProps = array(
'email' => 'EMAIL' 'email' => 'EMAIL'
) )
); );
?> ?>
<script type="text/javascript" src="/bitrix/js/main/jquery/jquery-1.7.min.js"></script> <script type="text/javascript" src="/bitrix/js/main/jquery/jquery-1.7.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
@ -33,6 +32,22 @@ $defaultOrderProps = array(
else if(parseInt($(this).val()) === 0) else if(parseInt($(this).val()) === 0)
$('tr.address-detail-' + orderType).hide('slow'); $('tr.address-detail-' + orderType).hide('slow');
}); });
$('tr.contragent-type select').change(function(){
splitName = $(this).attr('name').split('-');
contragentType = $(this).val();
orderType = splitName[2];
$('tr.legal-detail-' + orderType).hide();
$('.legal-detail-title-' + orderType).hide();
$('tr.legal-detail-' + orderType).each(function(){
if($(this).hasClass(contragentType)){
$(this).show();
$('.legal-detail-title-' + orderType).show();
}
});
});
}); });
</script> </script>
@ -60,6 +75,21 @@ $defaultOrderProps = array(
<tr class="heading"> <tr class="heading">
<td colspan="2"><b><?php echo GetMessage('ORDER_TYPE_INFO') . ' ' . $bitrixOrderType['NAME']; ?></b></td> <td colspan="2"><b><?php echo GetMessage('ORDER_TYPE_INFO') . ' ' . $bitrixOrderType['NAME']; ?></b></td>
</tr> </tr>
<tr class="contragent-type">
<td width="50%" class="adm-detail-content-cell-l">
<?php echo GetMessage('CONTRAGENT_TYPE'); ?>
</td>
<td width="50%" class="adm-detail-content-cell-r">
<select name="contragent-type-<?php echo $bitrixOrderType['ID']; ?>" class="typeselect">
<?php foreach ($arResult['contragentType'] as $contragentType): ?>
<option value="<?php echo $contragentType["ID"]; ?>" <?php if ($optionsContragentType[$bitrixOrderType['ID']] == $contragentType['ID']) echo 'selected'; ?>>
<?php echo $contragentType["NAME"]; ?>
</option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php $countProps = 0; foreach($arResult['orderProps'] as $orderProp): ?> <?php $countProps = 0; foreach($arResult['orderProps'] as $orderProp): ?>
<?php if($orderProp['ID'] == 'text'): ?> <?php if($orderProp['ID'] == 'text'): ?>
<tr class="heading"> <tr class="heading">
@ -71,6 +101,7 @@ $defaultOrderProps = array(
</td> </td>
</tr> </tr>
<?php endif; ?> <?php endif; ?>
<tr <?php if ($countProps > 3) echo 'class="address-detail-' . $bitrixOrderType['ID'] . '"'; if(($countProps > 3) && (count($defaultOrderProps[$bitrixOrderType['ID']]) < 6)) echo 'style="display:none;"';?>> <tr <?php if ($countProps > 3) echo 'class="address-detail-' . $bitrixOrderType['ID'] . '"'; if(($countProps > 3) && (count($defaultOrderProps[$bitrixOrderType['ID']]) < 6)) echo 'style="display:none;"';?>>
<td width="50%" class="adm-detail-content-cell-l" name="<?php echo $orderProp['ID']; ?>"> <td width="50%" class="adm-detail-content-cell-l" name="<?php echo $orderProp['ID']; ?>">
<?php echo $orderProp['NAME']; ?> <?php echo $orderProp['NAME']; ?>
@ -87,6 +118,60 @@ $defaultOrderProps = array(
</td> </td>
</tr> </tr>
<?php $countProps++; endforeach; ?> <?php $countProps++; endforeach; ?>
<?if (isset($arResult['customFields']) && count($arResult['customFields']) > 0):?>
<tr class="heading custom-detail-title">
<td colspan="2" style="background-color: transparent;">
<b>
<?=GetMessage("ORDER_CUSTOM"); ?>
</b>
</td>
</tr>
<?foreach($arResult['customFields'] as $customFields):?>
<tr class="custom-detail-<?=$customFields['ID'];?>">
<td width="50%" class="" name="">
<?=$customFields['NAME']; ?>
</td>
<td width="50%" class="">
<select name="custom-fields-<?=$customFields['ID'] . '-' . $bitrixOrderType['ID']; ?>" class="typeselect">
<option value=""></option>
<?foreach ($arResult['arProp'][$bitrixOrderType['ID']] as $arProp):?>
<option value="<?=$arProp['CODE']?>" <?php if ($optionsCustomFields[$bitrixOrderType['ID']][$customFields['ID']] == $arProp['CODE']) echo 'selected'; ?>>
<?=$arProp['NAME']; ?>
</option>
<?endforeach;?>
</select>
</td>
</tr>
<?endforeach;?>
<?endif;?>
<tr class="heading legal-detail-title-<?php echo $bitrixOrderType['ID'];?>" style="display:none">
<td colspan="2" style="background-color: transparent;">
<b>
<?php echo GetMessage("ORDER_LEGAL_INFO"); ?>
</b>
</td>
</tr>
<?php foreach($arResult['legalDetails'] as $legalDetails): ?>
<tr class="legal-detail-<?php echo $bitrixOrderType['ID'];?> <?php foreach($legalDetails['GROUP'] as $gr) echo $gr . ' ';?>" style="display:none">
<td width="50%" class="adm-detail-content-cell-l">
<?php echo $legalDetails['NAME']; ?>
</td>
<td width="50%" class="adm-detail-content-cell-r">
<select name="legal-detail-<?php echo $legalDetails['ID'] . '-' . $bitrixOrderType['ID']; ?>" class="typeselect">
<option value=""></option>
<?php foreach ($arResult['arProp'][$bitrixOrderType['ID']] as $arProp): ?>
<option value="<?php echo $arProp['CODE']; ?>" <?php if ($optionsLegalDetails[$bitrixOrderType['ID']][$legalDetails['ID']] == $arProp['CODE']) echo 'selected'; ?>>
<?php echo $arProp['NAME']; ?>
</option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>
</table> </table>

0
intaro.intarocrm/install/unstep1.php Executable file → Normal file
View File

View File

@ -1,5 +1,6 @@
<? <?
$arModuleVersion = array( $arModuleVersion = array(
"VERSION" => "1.0.15", "VERSION" => "1.1.0",
"VERSION_DATE" => "2014-11-27 16:00:00" "VERSION_DATE" => "2015-03-03 16:21:38"
); );

7
intaro.intarocrm/lang/ru/install/index.php Executable file → Normal file
View File

@ -1,15 +1,14 @@
<?php <?php
$MESS ['MODULE_NAME'] = 'retailCRM'; $MESS ['INTARO_MODULE_NAME'] = 'retailCRM';
$MESS ['MODULE_DESCRIPTION'] = 'Модуль интеграции с retailCRM специализированной CRM для e-commerce'; $MESS ['MODULE_DESCRIPTION'] = 'Модуль интеграции с retailCRM - специализированной CRM для e-commerce';
$MESS ['MODULE_PARTNER_NAME'] = 'Интаро Софт'; $MESS ['MODULE_PARTNER_NAME'] = 'Интаро Софт';
$MESS ['MODULE_PARTNER_URI'] = 'http://intaro.ru'; $MESS ['MODULE_PARTNER_URI'] = 'http://www.retailcrm.ru';
$MESS ['MODULE_INSTALL_TITLE'] = 'Установка модуля'; $MESS ['MODULE_INSTALL_TITLE'] = 'Установка модуля';
$MESS ['MODULE_UNINSTALL_TITLE'] = 'Удаление модуля'; $MESS ['MODULE_UNINSTALL_TITLE'] = 'Удаление модуля';
$MESS ['CANCELED'] = 'Флаг «Отменен»'; $MESS ['CANCELED'] = 'Флаг «Отменен»';
$MESS ['ERR_SALE'] = 'Отсутствует модуль sale! Дальнейшая установка невозможна.'; $MESS ['ERR_SALE'] = 'Отсутствует модуль sale! Дальнейшая установка невозможна.';
$MESS ['ERR_IBLOCK'] = 'Отсутствует модуль iblock! Дальнейшая установка невозможна.'; $MESS ['ERR_IBLOCK'] = 'Отсутствует модуль iblock! Дальнейшая установка невозможна.';
$MESS ['ERR_CATALOG'] = 'Отсутствует модуль catalog! Дальнейшая установка невозможна.'; $MESS ['ERR_CATALOG'] = 'Отсутствует модуль catalog! Дальнейшая установка невозможна.';
$MESS ['ERR_CATALOG'] = 'Отсутствует модуль catalog! Дальнейшая установка невозможна.';
$MESS ['INTAROCRM_CURL_ERR'] = 'Для работы модуля интеграции с retailCRM требуется PHP-расширение CURL.'; $MESS ['INTAROCRM_CURL_ERR'] = 'Для работы модуля интеграции с retailCRM требуется PHP-расширение CURL.';
$MESS ['ERR_ARTICLE_IBLOCK'] = 'Не установлены артикулы'; $MESS ['ERR_ARTICLE_IBLOCK'] = 'Не установлены артикулы';
$MESS ['DATE_TIMEZONE_ERR'] = 'Не указана временная зона в настройках php.'; $MESS ['DATE_TIMEZONE_ERR'] = 'Не указана временная зона в настройках php.';

3
intaro.intarocrm/lang/ru/install/step1.php Executable file → Normal file
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 ['INFO_1'] = 'Введите адрес экземпляра retailCRM (например, http://demo.intarocrm.ru) и API-ключ.'; $MESS ['URL_NOT_FOUND'] = 'В настройках одного или нескольких сайтов не заполнено поле "URL сервера".';
$MESS ['INFO_1'] = 'Введите адрес экземпляра retailCRM (например, https://demo.retailcrm.ru) и API-ключ.';
$MESS ['INFO_2'] = 'API-ключ можно сгенерировать при регистрации магазина в retailCRM (Администрирование > Интеграция).'; $MESS ['INFO_2'] = 'API-ключ можно сгенерировать при регистрации магазина в retailCRM (Администрирование > Интеграция).';
$MESS ['INFO_3'] = 'Код сайта в 1С-Битрикс должен совпадать с кодом сайта в retailCRM (Администрирование > Магазины).'; $MESS ['INFO_3'] = 'Код сайта в 1С-Битрикс должен совпадать с кодом сайта в retailCRM (Администрирование > Магазины).';

View File

@ -0,0 +1,11 @@
<?php
$MESS ['STEP_NAME'] = 'Шаг 1. Сайты';
$MESS ['MOD_NEXT_STEP'] = 'Следующий шаг';
$MESS ['ICRM_SITES'] = 'Активные сайты:';
$MESS ['ERR_404'] = 'Возможно неверно введен адрес retailCRM.';
$MESS ['ERR_6'] = 'Возможно неверно введен адрес retailCRM.';
$MESS ['ERR_403'] = 'Неверный apiKey.';
$MESS ['ERR_0'] = 'Превышено время ожидания ответа от сервера.';
$MESS ['ERR_FIELDS_API_HOST'] = 'Неверно заполнены поля.';
$MESS ['INFO_1'] = 'Задайте соответствия между Вашими магазинами в 1С-Битрикс и retailCRM.';
$MESS ['INFO_2'] = 'У всех Ваших магазинов в retailCRM должен быть общий API-ключ!';

0
intaro.intarocrm/lang/ru/install/step2.php Executable file → Normal file
View File

11
intaro.intarocrm/lang/ru/install/step3.php Executable file → Normal file
View File

@ -1,18 +1,13 @@
<?php <?php
$MESS ['STEP_NAME'] = 'Шаг 3'; $MESS ['STEP_NAME'] = 'Шаг 3';
$MESS ['MESS_1'] = 'На данном шаге вы можете выгрузить ранее оформленные заказы в retailCRM. Для запуска выгрузки нажмите кнопку «Начать выгрузку».';
$MESS ['MESS_2'] = 'Экспорт...';
$MESS ['MESS_3'] = 'Экспорт заказов успешно завершён.';
$MESS ['MESS_4'] = 'Экспорт заказов приостановлен.';
$MESS ['MESS_5'] = 'Произошла ошибка сервера, обратитесь в Интаро Софт.';
$MESS ['STOP'] = 'Приостановить выгрузку'; $MESS ['STOP'] = 'Приостановить выгрузку';
$MESS ['START_1'] = 'Начать выгрузку';
$MESS ['START_2'] = 'Приостановить выгрузку';
$MESS ['START_3'] = 'Возобновить выгрузку';
$MESS ['MOD_NEXT_STEP'] = 'Следующий шаг'; $MESS ['MOD_NEXT_STEP'] = 'Следующий шаг';
$MESS ['MOD_PREV_STEP'] = 'Предыдущий шаг'; $MESS ['MOD_PREV_STEP'] = 'Предыдущий шаг';
$MESS ['INFO_2'] = ' Задайте соответствие между полями заказа 1C-Битрикс и retailCRM.'; $MESS ['INFO_2'] = ' Задайте соответствие между полями заказа 1C-Битрикс и retailCRM.';
$MESS ['ORDER_TYPE_INFO'] = 'Тип заказа:'; $MESS ['ORDER_TYPE_INFO'] = 'Тип заказа:';
$MESS ['CONTRAGENT_TYPE'] = 'Тип контрагента';
$MESS ['ORDER_LEGAL_INFO'] = 'Юридические и банковские реквизиты';
$MESS ['ORDER_CUSTOM'] = 'Кастомные поля';
$MESS ['ORDER_PROPS'] = 'Настройки соответствия полей заказа retailCRM свойствам заказа 1С-Битрикс'; $MESS ['ORDER_PROPS'] = 'Настройки соответствия полей заказа retailCRM свойствам заказа 1С-Битрикс';
$MESS ['FIO'] = 'Ф.И.О.'; $MESS ['FIO'] = 'Ф.И.О.';

0
intaro.intarocrm/lang/ru/install/step5.php Executable file → Normal file
View File

0
intaro.intarocrm/lang/ru/install/step6.php Executable file → Normal file
View File

0
intaro.intarocrm/lang/ru/install/unstep1.php Executable file → Normal file
View File

8
intaro.intarocrm/lang/ru/options.php Executable file → Normal file
View File

@ -5,16 +5,22 @@ $MESS ['ICRM_OPTIONS_ORDER_PROPS_TAB'] = 'Cоответствия полей с
$MESS ['ICRM_CONN_SETTINGS'] = 'Настройка соединения'; $MESS ['ICRM_CONN_SETTINGS'] = 'Настройка соединения';
$MESS ['ICRM_API_HOST'] = 'Адрес retailCRM:'; $MESS ['ICRM_API_HOST'] = 'Адрес retailCRM:';
$MESS ['ICRM_API_KEY'] = 'Ключ авторизации:'; $MESS ['ICRM_API_KEY'] = 'Ключ авторизации:';
$MESS ['ICRM_SITES'] = 'Активные сайты:'; $MESS ['ICRM_SITES'] = 'Символьные коды магазинов';
$MESS ['ICRM_OPTIONS_CATALOG_TAB'] = 'Настройка справочников'; $MESS ['ICRM_OPTIONS_CATALOG_TAB'] = 'Настройка справочников';
$MESS ['DELIVERY_TYPES_LIST'] = 'Способы доставки'; $MESS ['DELIVERY_TYPES_LIST'] = 'Способы доставки';
$MESS ['PAYMENT_TYPES_LIST'] = 'Способы оплаты'; $MESS ['PAYMENT_TYPES_LIST'] = 'Способы оплаты';
$MESS ['PAYMENT_STATUS_LIST'] = 'Статусы'; $MESS ['PAYMENT_STATUS_LIST'] = 'Статусы';
$MESS ['ORDER_TYPES_LIST'] = 'Типы заказа'; $MESS ['ORDER_TYPES_LIST'] = 'Типы заказа';
$MESS ['CONTRAGENTS_TYPES_LIST'] = 'Тип контрагента';
$MESS ['PAYMENT_LIST'] = 'Оплата'; $MESS ['PAYMENT_LIST'] = 'Оплата';
$MESS ['PAYMENT_Y'] = 'Оплачен'; $MESS ['PAYMENT_Y'] = 'Оплачен';
$MESS ['PAYMENT_N'] = 'Не оплачен'; $MESS ['PAYMENT_N'] = 'Не оплачен';
$MESS ['LEGAL_DETAIL'] = 'Юридические и банковские реквизиты';
$MESS ['ORDER_CUSTOM'] = 'Кастомные поля';
$MESS ['ORDER_UPLOAD'] = 'Повторная выгрузка заказов';
$MESS ['ORDER_NUMBERS'] = 'Номера заказов: ';
$MESS ['ORDER_UPLOAD_INFO'] = 'Для загрузки всех заказов нажмите кнопку «Начать выгрузку». Или перечислите необходимые ID заказов через запятую, интервалы через тире. Например: 1, 3, 5-10, 12, 13... и т.д.';
$MESS ['ICRM_OPTIONS_SUBMIT_TITLE'] = 'Сохранить настройки'; $MESS ['ICRM_OPTIONS_SUBMIT_TITLE'] = 'Сохранить настройки';
$MESS ['ICRM_OPTIONS_SUBMIT_VALUE'] = 'Сохранить'; $MESS ['ICRM_OPTIONS_SUBMIT_VALUE'] = 'Сохранить';

570
intaro.intarocrm/options.php Executable file → Normal file
View File

@ -15,6 +15,10 @@ $CRM_ORDER_LAST_ID = 'order_last_id';
$CRM_ORDER_SITES = 'sites_ids'; $CRM_ORDER_SITES = 'sites_ids';
$CRM_ORDER_DISCHARGE = 'order_discharge'; $CRM_ORDER_DISCHARGE = 'order_discharge';
$CRM_ORDER_PROPS = 'order_props'; $CRM_ORDER_PROPS = 'order_props';
$CRM_LEGAL_DETAILS = 'legal_details';
$CRM_CUSTOM_FIELDS = 'custom_fields';
$CRM_CONTRAGENT_TYPE = 'contragent_type';
$CRM_SITES_LIST= 'sites_list';
if(!CModule::IncludeModule('intaro.intarocrm') if(!CModule::IncludeModule('intaro.intarocrm')
|| !CModule::IncludeModule('sale')) || !CModule::IncludeModule('sale'))
@ -28,69 +32,43 @@ if($_GET['ok'] && $_GET['ok'] == 'Y') echo CAdminMessage::ShowNote(GetMessage('I
$arResult = array(); $arResult = array();
$arResult['orderProps'] = array( if (file_exists($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.intarocrm/classes/general/config/options.xml')) {
array( $options = simplexml_load_file($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.intarocrm/classes/general/config/options.xml');
'NAME' => GetMessage('FIO'),
'ID' => 'fio' foreach($options->contragents->contragent as $contragent)
), {
array( $type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET);
'NAME' => GetMessage('PHONE'), $type["ID"] = (string)$contragent["id"];
'ID' => 'phone' $arResult['contragentType'][] = $type;
), unset ($type);
array( }
'NAME' => GetMessage('EMAIL'), foreach($options->fields->field as $field)
'ID' => 'email' {
), $type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET);
array( $type["ID"] = (string)$field["id"];
'NAME' => GetMessage('ADDRESS'),
'ID' => 'text' if ($field["group"] == 'custom') {
), $arResult['customFields'][] = $type;
// address } elseif(!$field["group"]){
/* array( $arResult['orderProps'][] = $type;
'NAME' => GetMessage('COUNTRY'), } else{
'ID' => 'country' $groups = explode(",", (string)$field["group"]);
), foreach ($groups as $group) {
array( $type["GROUP"][] = trim($group);
'NAME' => GetMessage('REGION'), }
'ID' => 'region' $arResult['legalDetails'][] = $type;
), }
array( unset($type);
'NAME' => GetMessage('CITY'), }
'ID' => 'city' }
),*/ //else error
array(
'NAME' => GetMessage('ZIP'), $arResult['arSites'] = array();
'ID' => 'index'
), $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
array( while ($ar = $rsSites->Fetch()){
'NAME' => GetMessage('STREET'), $arResult['arSites'][] = $ar;
'ID' => 'street' }
),
array(
'NAME' => GetMessage('BUILDING'),
'ID' => 'building'
),
array(
'NAME' => GetMessage('FLAT'),
'ID' => 'flat'
),
array(
'NAME' => GetMessage('INTERCOMCODE'),
'ID' => 'intercomcode'
),
array(
'NAME' => GetMessage('FLOOR'),
'ID' => 'floor'
),
array(
'NAME' => GetMessage('BLOCK'),
'ID' => 'block'
),
array(
'NAME' => GetMessage('HOUSE'),
'ID' => 'house'
)
);
//ajax update deliveryServices //ajax update deliveryServices
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) { if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && ($_POST['ajax'] == 1)) {
@ -99,23 +77,13 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
$api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0); $api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0); $api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0);
$api = new IntaroCrm\RestApi($api_host, $api_key); $api = new RetailCrm\RestApi($api_host, $api_key);
try { try {
$api->paymentStatusesList(); $api->paymentStatusesList();
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::paymentStatusesList', 'intaro.crm/options.php', 'RetailCrm\RestApi::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$APPLICATION->RestartBuffer();
header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
die(json_encode(array('success' => false, 'errMsg' => $e->getCode())));
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
@ -133,7 +101,8 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
'NAME' => 'ASC' 'NAME' => 'ASC'
), ),
array( array(
'ACTIVE' => 'Y' 'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
) )
); );
@ -154,15 +123,9 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
'name' => ICrmOrderActions::toJSON($profile['TITLE']), 'name' => ICrmOrderActions::toJSON($profile['TITLE']),
'deliveryType' => $arDeliveryServicesList['SID'] 'deliveryType' => $arDeliveryServicesList['SID']
))); )));
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::deliveryServiceEdit', 'intaro.crm/options.php', 'RetailCrm\RestApi::deliveryServiceEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::deliveryServiceEdit::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
@ -176,33 +139,83 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
die(json_encode(array('success' => true))); die(json_encode(array('success' => true)));
} }
//upload orders after install module
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && $_POST['ajax'] == 2){
$step = $_POST['step'];
$orders = $_POST['orders'];
$countStep = 50; // 50 orders on step
if($orders){
$ordersArr = explode(',', $orders);
$orders = array();
foreach($ordersArr as $_ordersArr){
$ordersList = explode('-', trim($_ordersArr));
if(count($ordersList) > 1){
for($i = (int)trim($ordersList[0]); $i <= (int)trim($ordersList[count($ordersList) - 1]); $i++){
$orders[] = $i;
}
} else{
$orders[] = (int)$ordersList[0];
}
}
$splitedOrders = array_chunk($orders, $countStep);
$stepOrders = $splitedOrders[$step];
ICrmOrderActions::uploadOrders($countStep, false, $stepOrders);
$percent = round((($step * $countStep + count($stepOrders)) * 100 / count($orders)), 1);
$step++;
if(!$splitedOrders[$step]){
$step='end';
}
$res = array("step" => $step, "percent" => $percent, 'stepOrders' => $stepOrders);
} else{
$orders = array();
for($i = 1; $i <= $countStep; $i++){
$orders[] = $i + $step * $countStep;
}
ICrmOrderActions::uploadOrders($countStep, false, $orders);
$step++;
$countLeft = (int) CSaleOrder::GetList(array("ID" => "ASC"), array('>ID' => $step * $countStep), array());
$countAll = (int) CSaleOrder::GetList(array("ID" => "ASC"), array(), array());
$percent = round(100 - ($countLeft * 100 / $countAll), 1);
if($countLeft == 0){
$step = 'end';
}
$res = array("step" => $step, "percent" => $percent, 'stepOrders' => $orders);
}
$APPLICATION->RestartBuffer();
header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET);
die(json_encode($res));
}
//update connection settings //update connection settings
if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) { if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$api_host = htmlspecialchars(trim($_POST['api_host'])); $api_host = htmlspecialchars(trim($_POST['api_host']));
$api_key = htmlspecialchars(trim($_POST['api_key'])); $api_key = htmlspecialchars(trim($_POST['api_key']));
// if empty so select all? or exception --not obligatory //bitrix site list
$orderSites = array(); $siteListArr = array();
/*foreach ($_POST[$CRM_ORDER_SITES] as $site) { foreach ($arResult['arSites'] as $arSites) {
$orderSites[] = htmlspecialchars(trim($site)); $siteListArr[$arSites['LID']] = htmlspecialchars(trim($_POST['sites-id-' . $arSites['LID']]));
}*/ }
if($api_host && $api_key) { if($api_host && $api_key) {
$api = new IntaroCrm\RestApi($api_host, $api_key); $api = new RetailCrm\RestApi($api_host, $api_key);
try { try {
$api->paymentStatusesList(); $api->paymentStatusesList();
} catch (\IntaroCrm\Exception\ApiException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::paymentStatusesList', 'intaro.crm/options.php', 'RetailCrm\RestApi::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
$uri .= '&errc=ERR_' . $e->getCode();
LocalRedirect($uri);
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::paymentStatusesList::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
@ -267,7 +280,8 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
'NAME' => 'ASC' 'NAME' => 'ASC'
), ),
array( array(
'ACTIVE' => 'Y' 'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
) )
); );
@ -349,22 +363,51 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$propsCount = 0; $propsCount = 0;
$_orderPropsArr = array(); $_orderPropsArr = array();
foreach ($arResult['orderProps'] as $orderProp) { foreach ($arResult['orderProps'] as $orderProp) {
if ((!(int) htmlspecialchars(trim($_POST['address-detail-' . $orderType['ID']]))) && $propsCount > 4) if ((!(int) htmlspecialchars(trim($_POST['address-detail-' . $orderType['ID']]))) && $propsCount > 4){
break; break;
}
$_orderPropsArr[$orderProp['ID']] = htmlspecialchars(trim($_POST['order-prop-' . $orderProp['ID'] . '-' . $orderType['ID']])); $_orderPropsArr[$orderProp['ID']] = htmlspecialchars(trim($_POST['order-prop-' . $orderProp['ID'] . '-' . $orderType['ID']]));
$propsCount++; $propsCount++;
} }
$orderPropsArr[$orderType['ID']] = $_orderPropsArr; $orderPropsArr[$orderType['ID']] = $_orderPropsArr;
} }
//legal details props
$legalDetailsArr = array();
foreach ($orderTypesList as $orderType) {
$_legalDetailsArr = array();
foreach ($arResult['legalDetails'] as $legalDetails) {
$_legalDetailsArr[$legalDetails['ID']] = htmlspecialchars(trim($_POST['legal-detail-' . $legalDetails['ID'] . '-' . $orderType['ID']]));
}
$legalDetailsArr[$orderType['ID']] = $_legalDetailsArr;
}
$customFieldsArr = array();
foreach ($orderTypesList as $orderType) {
$_customFieldsArr = array();
foreach ($arResult['customFields'] as $custom) {
$_customFieldsArr[$custom['ID']] = htmlspecialchars(trim($_POST['custom-fields-' . $custom['ID'] . '-' . $orderType['ID']]));
}
$customFieldsArr[$orderType['ID']] = $_customFieldsArr;
}
//contragents type list
$contragentTypeArr = array();
foreach ($orderTypesList as $orderType) {
$contragentTypeArr[$orderType['ID']] = htmlspecialchars(trim($_POST['contragent-type-' . $orderType['ID']]));
}
COption::SetOptionString($mid, $CRM_SITES_LIST, serialize(ICrmOrderActions::clearArr($siteListArr)));
COption::SetOptionString($mid, $CRM_ORDER_TYPES_ARR, serialize(ICrmOrderActions::clearArr($orderTypesArr))); COption::SetOptionString($mid, $CRM_ORDER_TYPES_ARR, serialize(ICrmOrderActions::clearArr($orderTypesArr)));
COption::SetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, serialize(ICrmOrderActions::clearArr($deliveryTypesArr))); COption::SetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, serialize(ICrmOrderActions::clearArr($deliveryTypesArr)));
COption::SetOptionString($mid, $CRM_PAYMENT_TYPES, serialize(ICrmOrderActions::clearArr($paymentTypesArr))); COption::SetOptionString($mid, $CRM_PAYMENT_TYPES, serialize(ICrmOrderActions::clearArr($paymentTypesArr)));
COption::SetOptionString($mid, $CRM_PAYMENT_STATUSES, serialize(ICrmOrderActions::clearArr($paymentStatusesArr))); COption::SetOptionString($mid, $CRM_PAYMENT_STATUSES, serialize(ICrmOrderActions::clearArr($paymentStatusesArr)));
COption::SetOptionString($mid, $CRM_PAYMENT, serialize(ICrmOrderActions::clearArr($paymentArr))); COption::SetOptionString($mid, $CRM_PAYMENT, serialize(ICrmOrderActions::clearArr($paymentArr)));
COption::SetOptionString($mid, $CRM_ORDER_SITES, serialize(ICrmOrderActions::clearArr($orderSites)));
COption::SetOptionString($mid, $CRM_ORDER_DISCHARGE, $orderDischarge); COption::SetOptionString($mid, $CRM_ORDER_DISCHARGE, $orderDischarge);
COption::SetOptionString($mid, $CRM_ORDER_PROPS, serialize(ICrmOrderActions::clearArr($orderPropsArr))); COption::SetOptionString($mid, $CRM_ORDER_PROPS, serialize(ICrmOrderActions::clearArr($orderPropsArr)));
COption::SetOptionString($mid, $CRM_CONTRAGENT_TYPE, serialize(ICrmOrderActions::clearArr($contragentTypeArr)));
COption::SetOptionString($mid, $CRM_LEGAL_DETAILS, serialize(ICrmOrderActions::clearArr($legalDetailsArr)));
COption::SetOptionString($mid, $CRM_CUSTOM_FIELDS, serialize(ICrmOrderActions::clearArr($customFieldsArr)));
$uri .= '&ok=Y'; $uri .= '&ok=Y';
LocalRedirect($uri); LocalRedirect($uri);
@ -372,33 +415,21 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0); $api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0); $api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0);
$api = new IntaroCrm\RestApi($api_host, $api_key); $api = new RetailCrm\RestApi($api_host, $api_key);
$arResult['arSites'] = array();
$rsSites = CSite::GetList($by, $sort, array());
while ($ar = $rsSites->Fetch())
$arResult['arSites'][] = $ar;
//prepare crm lists //prepare crm lists
try { try {
$arResult['orderTypesList'] = $api->orderTypesList(); $arResult['orderTypesList'] = $api->orderTypesList()->orderTypes;
$arResult['deliveryTypesList'] = $api->deliveryTypesList(); $arResult['deliveryTypesList'] = $api->deliveryTypesList()->deliveryTypes;
$arResult['deliveryServicesList'] = $api->deliveryServicesList(); $arResult['deliveryServicesList'] = $api->deliveryServicesList()->deliveryServices;
$arResult['paymentTypesList'] = $api->paymentTypesList(); $arResult['paymentTypesList'] = $api->paymentTypesList()->paymentTypes;
$arResult['paymentStatusesList'] = $api->paymentStatusesList(); // --statuses $arResult['paymentStatusesList'] = $api->paymentStatusesList()->paymentStatuses; // --statuses
$arResult['paymentList'] = $api->orderStatusesList(); $arResult['paymentList'] = $api->orderStatusesList()->statuses;
$arResult['paymentGroupList'] = $api->orderStatusGroupsList(); // -- statuses groups $arResult['paymentGroupList'] = $api->orderStatusGroupsList()->statusGroups; // -- statuses groups
} catch (\IntaroCrm\Exception\ApiException $e) { $arResult['sitesList'] = $api->sitesList()->sites;
} catch (\RetailCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog( ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::*List', 'intaro.crm/options.php', 'RetailCrm\RestApi::*List::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
echo CAdminMessage::ShowMessage(GetMessage('ERR_' . $e->getCode()));
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/options.php', 'IntaroCrm\RestApi::*List::CurlException',
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
@ -452,7 +483,8 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
'NAME' => 'ASC' 'NAME' => 'ASC'
), ),
array( array(
'ACTIVE' => 'Y' 'ACTIVE' => 'Y',
'SITE_ID' => $arResult['arSites'][0]['LID']
) )
); );
@ -518,9 +550,12 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$optionsPayTypes = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT_TYPES, 0)); $optionsPayTypes = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT_TYPES, 0));
$optionsPayStatuses = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT_STATUSES, 0)); // --statuses $optionsPayStatuses = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT_STATUSES, 0)); // --statuses
$optionsPayment = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT, 0)); $optionsPayment = unserialize(COption::GetOptionString($mid, $CRM_PAYMENT, 0));
$optionsSites = unserialize(COption::GetOptionString($mid, $CRM_ORDER_SITES, 0)); $optionsSitesList = unserialize(COption::GetOptionString($mid, $CRM_SITES_LIST, 0));
$optionsDischarge = COption::GetOptionString($mid, $CRM_ORDER_DISCHARGE, 0); $optionsDischarge = COption::GetOptionString($mid, $CRM_ORDER_DISCHARGE, 0);
$optionsOrderProps = unserialize(COption::GetOptionString($mid, $CRM_ORDER_PROPS, 0)); $optionsOrderProps = unserialize(COption::GetOptionString($mid, $CRM_ORDER_PROPS, 0));
$optionsContragentType = unserialize(COption::GetOptionString($mid, $CRM_CONTRAGENT_TYPE, 0));
$optionsLegalDetails = unserialize(COption::GetOptionString($mid, $CRM_LEGAL_DETAILS, 0));
$optionsCustomFields = unserialize(COption::GetOptionString($mid, $CRM_CUSTOM_FIELDS, 0));
$isCustomOrderType = function_exists('intarocrm_set_order_type') || function_exists('intarocrm_get_order_type'); $isCustomOrderType = function_exists('intarocrm_set_order_type') || function_exists('intarocrm_get_order_type');
@ -565,6 +600,22 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
else if(parseInt($(this).val()) === 0) else if(parseInt($(this).val()) === 0)
$('tr.address-detail-' + orderType).hide('slow'); $('tr.address-detail-' + orderType).hide('slow');
}); });
$('tr.contragent-type select').change(function(){
splitName = $(this).attr('name').split('-');
contragentType = $(this).val();
orderType = splitName[2];
$('tr.legal-detail-' + orderType).hide();
$('.legal-detail-title-' + orderType).hide();
$('tr.legal-detail-' + orderType).each(function(){
if($(this).hasClass(contragentType)){
$(this).show();
$('.legal-detail-title-' + orderType).show();
}
});
});
}); });
$('input[name="update-delivery-services"]').live('click', function() { $('input[name="update-delivery-services"]').live('click', function() {
@ -617,16 +668,27 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
<td width="50%" class="adm-detail-content-cell-l"><?php echo GetMessage('ICRM_API_KEY'); ?></td> <td width="50%" class="adm-detail-content-cell-l"><?php echo GetMessage('ICRM_API_KEY'); ?></td>
<td width="50%" class="adm-detail-content-cell-r"><input type="text" id="api_key" name="api_key" value="<?php echo $api_key; ?>"></td> <td width="50%" class="adm-detail-content-cell-r"><input type="text" id="api_key" name="api_key" value="<?php echo $api_key; ?>"></td>
</tr> </tr>
<!--<tr> <?php if(count($arResult['arSites'])>1):?>
<td width="50%" class="adm-detail-content-cell-l"><?php echo GetMessage('ICRM_SITES'); ?></td> <tr class="heading">
<td width="50%" class="adm-detail-content-cell-r"> <td colspan="2" style="background-color: transparent;">
<select id="sites_ids" name="sites_ids[]" multiple="multiple" size="3"> <b>
<?php echo GetMessage('ICRM_SITES'); ?>
</b>
</td>
</tr>
<?php foreach ($arResult['arSites'] as $site): ?> <?php foreach ($arResult['arSites'] as $site): ?>
<option value="<?php echo $site['LID'] ?>" <?php if(in_array($site['LID'], $optionsSites)) echo 'selected="selected"'; ?>><?php echo $site['NAME'] . ' (' . $site['LID'] . ')' ?></option> <tr>
<td width="50%" class="adm-detail-content-cell-l"><?php echo $site['NAME'] . ' (' . $site['LID'] . ')'; ?></td>
<td width="50%" class="adm-detail-content-cell-r">
<select class="typeselect" name="sites-id-<?php echo $site['LID']?>">
<?php foreach ($arResult['sitesList'] as $sitesList): ?>
<option value="<?php echo $sitesList['code'] ?>" <?php if($sitesList['code'] == $optionsSitesList[$site['LID']]) echo 'selected="selected"'; ?>><?php echo $sitesList['name']?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
</td> </td>
</tr>--> </tr>
<?php endforeach; ?>
<?php endif;?>
<?php $tabControl->BeginNextTab(); ?> <?php $tabControl->BeginNextTab(); ?>
<input type="hidden" name="tab" value="catalog"> <input type="hidden" name="tab" value="catalog">
<tr align="center"> <tr align="center">
@ -760,7 +822,20 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
<tr class="heading"> <tr class="heading">
<td colspan="2"><b><?php echo GetMessage('ORDER_TYPE_INFO') . ' ' . $bitrixOrderType['NAME']; ?></b></td> <td colspan="2"><b><?php echo GetMessage('ORDER_TYPE_INFO') . ' ' . $bitrixOrderType['NAME']; ?></b></td>
</tr> </tr>
<tr class="contragent-type">
<td width="50%" class="adm-detail-content-cell-l">
<?php echo GetMessage('CONTRAGENTS_TYPES_LIST'); ?>
</td>
<td width="50%" class="adm-detail-content-cell-r">
<select name="contragent-type-<?php echo $bitrixOrderType['ID']; ?>" class="typeselect">
<?php foreach ($arResult['contragentType'] as $contragentType): ?>
<option value="<?php echo $contragentType["ID"]; ?>" <?php if ($optionsContragentType[$bitrixOrderType['ID']] == $contragentType['ID']) echo 'selected'; ?>>
<?php echo $contragentType["NAME"]; ?>
</option>
<?php endforeach; ?>
</select>
</td>
</tr>
<?php $countProps = 1; foreach($arResult['orderProps'] as $orderProp): ?> <?php $countProps = 1; foreach($arResult['orderProps'] as $orderProp): ?>
<?php if($orderProp['ID'] == 'text'): ?> <?php if($orderProp['ID'] == 'text'): ?>
<tr class="heading"> <tr class="heading">
@ -788,7 +863,58 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
</td> </td>
</tr> </tr>
<?php $countProps++; endforeach; ?> <?php $countProps++; endforeach; ?>
<?if (isset($arResult['customFields']) && count($arResult['customFields']) > 0):?>
<tr class="heading custom-detail-title">
<td colspan="2" style="background-color: transparent;">
<b>
<?=GetMessage("ORDER_CUSTOM"); ?>
</b>
</td>
</tr>
<?foreach($arResult['customFields'] as $customFields):?>
<tr class="custom-detail-<?=$customFields['ID'];?>">
<td width="50%" class="" name="">
<?=$customFields['NAME']; ?>
</td>
<td width="50%" class="">
<select name="custom-fields-<?=$customFields['ID'] . '-' . $bitrixOrderType['ID']; ?>" class="typeselect">
<option value=""></option>
<?foreach ($arResult['arProp'][$bitrixOrderType['ID']] as $arProp):?>
<option value="<?=$arProp['CODE']?>" <?php if ($optionsCustomFields[$bitrixOrderType['ID']][$customFields['ID']] == $arProp['CODE']) echo 'selected'; ?>>
<?=$arProp['NAME']; ?>
</option>
<?endforeach;?>
</select>
</td>
</tr>
<?endforeach;?>
<?endif;?>
<tr class="heading legal-detail-title-<?php echo $bitrixOrderType['ID'];?>" <?php if(count($optionsLegalDetails[$bitrixOrderType['ID']])<1) echo 'style="display:none"'; ?>>
<td colspan="2" style="background-color: transparent;">
<b>
<?php echo GetMessage('LEGAL_DETAIL'); ?>
</b>
</td>
</tr>
<?php foreach($arResult['legalDetails'] as $legalDetails): ?>
<tr class="legal-detail-<?php echo $bitrixOrderType['ID'];?> <?php foreach($legalDetails['GROUP'] as $gr) echo $gr . ' ';?>" <?php if(!in_array($optionsContragentType[$bitrixOrderType['ID']], $legalDetails['GROUP'])) echo 'style="display:none"'; ?>>
<td width="50%" class="" name="<?php ?>">
<?php echo $legalDetails['NAME']; ?>
</td>
<td width="50%" class="">
<select name="legal-detail-<?php echo $legalDetails['ID'] . '-' . $bitrixOrderType['ID']; ?>" class="typeselect">
<option value=""></option>
<?php foreach ($arResult['arProp'][$bitrixOrderType['ID']] as $arProp): ?>
<option value="<?php echo $arProp['CODE']; ?>" <?php if ($optionsLegalDetails[$bitrixOrderType['ID']][$legalDetails['ID']] == $arProp['CODE']) echo 'selected'; ?>>
<?php echo $arProp['NAME']; ?>
</option>
<?php endforeach; ?> <?php endforeach; ?>
</select>
</td>
</tr>
<?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="heading">
@ -803,9 +929,173 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
</td> </td>
</tr> </tr>
<?php $tabControl->Buttons(); ?> <?php $tabControl->Buttons(); ?>
<input type="hidden" name="Update" value="Y" /> <input type="hidden" name="Update" value="Y" />
<input type="submit" title="<?php echo GetMessage('ICRM_OPTIONS_SUBMIT_TITLE'); ?>" value="<?php echo GetMessage('ICRM_OPTIONS_SUBMIT_VALUE'); ?>" name="btn-update" class="adm-btn-save" /> <input type="submit" title="<?php echo GetMessage('ICRM_OPTIONS_SUBMIT_TITLE'); ?>" value="<?php echo GetMessage('ICRM_OPTIONS_SUBMIT_VALUE'); ?>" name="btn-update" class="adm-btn-save" />
<?php $tabControl->End(); ?> <?php $tabControl->End(); ?>
</form> </form>
<?php } ?> <?php } ?>
<?php //order upload?>
<?php if($_GET['upl'] == 1){?>
<style type="text/css">
.instal-load-label {
color: #000;
margin-bottom: 15px;
}
.instal-progress-bar-outer {
height: 32px;
border:1px solid;
border-color:#9ba6a8 #b1bbbe #bbc5c9 #b1bbbe;
-webkit-box-shadow: 1px 1px 0 #fff, inset 0 2px 2px #c0cbce;
box-shadow: 1px 1px 0 #fff, inset 0 2px 2px #c0cbce;
background-color:#cdd8da;
background-image:-webkit-linear-gradient(top, #cdd8da, #c3ced1);
background-image:-moz-linear-gradient(top, #cdd8da, #c3ced1);
background-image:-ms-linear-gradient(top, #cdd8da, #c3ced1);
background-image:-o-linear-gradient(top, #cdd8da, #c3ced1);
background-image:linear-gradient(top, #ced9db, #c3ced1);
border-radius: 2px;
text-align: center;
color: #6a808e;
text-shadow: 0 1px rgba(255,255,255,0.85);
font-size: 18px;
line-height: 35px;
font-weight: bold;
}
.instal-progress-bar-alignment {
height: 28px;
margin: 0;
position: relative;
}
.instal-progress-bar-inner {
height: 28px;
border-radius: 2px;
border-top: solid 1px #52b9df;
background-color:#2396ce;
background-image:-webkit-linear-gradient(top, #27a8d7, #2396ce, #1c79c0);
background-image:-moz-linear-gradient(top, #27a8d7, #2396ce, #1c79c0);
background-image:-ms-linear-gradient(top, #27a8d7, #2396ce, #1c79c0);
background-image:-o-linear-gradient(top, #27a8d7, #2396ce, #1c79c0);
background-image:linear-gradient(top, #27a8d7, #2396ce, #1c79c0);
position: absolute;
overflow: hidden;
top: 1px;
left:0;
}
.instal-progress-bar-inner-text {
color: #fff;
text-shadow: 0 1px rgba(0,0,0,0.2);
font-size: 18px;
line-height: 32px;
font-weight: bold;
text-align: center;
position: absolute;
left: -2px;
top: -2px;
}
.order-upload-button{
padding: 1px 13px 2px;
height:28px;
}
.order-upload-button div{
float:right;
position:relative;
visible: none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#percent').width($('.instal-progress-bar-outer').width());
$(window).resize(function(){ // strechin progress bar
$('#percent').width($('.instal-progress-bar-outer').width());
});
// orderUpload function
function orderUpload() {
var handlerUrl = $('#upload-orders').attr('action');
var step = $('input[name="step"]').val();
var orders = $('input[name="orders"]').val();
var data = 'orders=' + orders + '&step=' + step + '&ajax=2';
// ajax request
$.ajax({
type: 'POST',
url: handlerUrl,
data: data,
dataType: 'json',
success: function(response) {
$('input[name="step"]').val(response.step);
if(response.step == 'end'){
$('input[name="step"]').val(0);
BX.closeWait();
}
else{
orderUpload();
}
$('#indicator').css('width', response.percent + '%');
$('#percent').html(response.percent + '%');
$('#percent2').html(response.percent + '%');
},
error: function () {
BX.closeWait();
$('#status').text('<?php echo GetMessage('MESS_4'); ?>');
alert('<?php echo GetMessage('MESS_5'); ?>');
}
});
}
$('input[name="start"]').live('click', function() {
BX.showWait();
orderUpload();
return false;
});
});
</script>
<br>
<form id="upload-orders" action="<?php echo $uri; ?>" method="POST">
<input type="hidden" name="step" value="0">
<div class="adm-detail-content-item-block">
<table class="adm-detail-content-table edit-table" id="edit1_edit_table">
<tbody>
<tr class="heading">
<td colspan="2"><b><?php echo GetMessage('ORDER_UPLOAD'); ?></b></td>
</tr>
<tr>
<td class="adm-detail-content-cell-r"><?php echo GetMessage('ORDER_NUMBERS'); ?> <input id="order-nombers" style="width:86%" type="text" value="" name="orders"></td>
</tr>
</tbody>
</table>
<div class="instal-load-block" id="result">
<div class="instal-load-label" id="status"><?php echo GetMessage('ORDER_UPLOAD_INFO'); ?></div>
<div class="instal-progress-bar-outer">
<div class="instal-progress-bar-alignment" style="width: 100%;">
<div class="instal-progress-bar-inner" id="indicator" style="width: 0%;">
<div class="instal-progress-bar-inner-text" style="width: 100%;" id="percent">0%</div>
</div>
<span id="percent2">0%</span>
</div>
</div>
</div>
<br />
<div class="order-upload-button">
<div align="left">
<input type="submit" name="start" value="Начать выгрузку" class="adm-btn-save">
</div>
</div>
</div>
</form>
<?php }?>

View File

@ -0,0 +1,87 @@
<?php
if (!CModule::IncludeModule("intaro.intarocrm")) return;
if (!CModule::IncludeModule("sale")) return;
class RestApiSite extends \IntaroCrm\RestApi
{
public function sitesList()
{
$url = $this->apiUrl.'reference/sites';
$result = $this->curlRequest($url);
return $result;
}
}
$mid = 'intaro.intarocrm';
$CRM_API_HOST_OPTION = 'api_host';
$CRM_API_KEY_OPTION = 'api_key';
$CRM_CONTRAGENT_TYPE = 'contragent_type';
$CRM_SITES_LIST= 'sites_list';
$api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0);
$api = new RestApiSite($api_host, $api_key);
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/intaro.intarocrm/classes/general/agent.php')) {
unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/intaro.intarocrm/classes/general/agent.php');
}
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/intaro.intarocrm/classes/general/Exception/ApiException.php')) {
unlink($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/intaro.intarocrm/classes/general/Exception/ApiException.php');
}
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/retailcrm')) {
removeDirectory($_SERVER['DOCUMENT_ROOT'] . '/retailcrm');
}
//sites
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){
$arSites[] = $ar;
}
if(count($arSites)>1){
try {
$sitesList = $api->sitesList();
} catch (\IntaroCrm\Exception\CurlException $e) {
ICrmOrderActions::eventLog(
'intaro.crm/updater.php', 'RetailCrm\RestApi::sitesList::CurlException',
$e->getCode() . ': ' . $e->getMessage()
);
return;
}
foreach ($arResult['arSites'] as $arSites) {
$siteListArr[$arSites['LID']] = $sitesList[0]['code'];
}
COption::SetOptionString($mid, $CRM_SITES_LIST, serialize(ICrmOrderActions::clearArr($siteListArr)));
}
//contragents type list
$dbOrderTypesList = CSalePersonType::GetList(
array(
"SORT" => "ASC",
"NAME" => "ASC"
),
array(
"ACTIVE" => "Y",
),
false,
false,
array()
);
$orderTypesList = array();
while ($arOrderTypesList = $dbOrderTypesList->Fetch()){
$orderTypesList[] = $arOrderTypesList;
}
$contragentTypeArr = array();
foreach ($orderTypesList as $orderType) {
$contragentTypeArr[$orderType['ID']] = 'individual';
}
COption::SetOptionString($mid, $CRM_CONTRAGENT_TYPE, serialize(ICrmOrderActions::clearArr($contragentTypeArr)));
function removeDirectory($dir) {
if ($objs = glob($dir."/*")) {
foreach($objs as $obj) {
is_dir($obj) ? removeDirectory($obj) : unlink($obj);
}
}
rmdir($dir);
}