1
0
mirror of synced 2025-02-07 18:49:23 +03:00

Merge pull request #17 from ghostrainman/master

v.2.0.3
This commit is contained in:
Alex Lushpai 2016-10-04 19:04:42 +04:00 committed by GitHub
commit 526c74631b
19 changed files with 576 additions and 565 deletions

View File

@ -1,3 +1,12 @@
## 2016-10-04 v.2.0.3
* fix состава отгрузки
## 2016-10-04 v.2.0.2
* Исправлены ошибки
## 2016-10-03 v.2.0.1
* Исправлены ошибки
## 2016-09-12 v.2.0.0 ## 2016-09-12 v.2.0.0
* API V4 * API V4
* Переход на ядро d7 * Переход на ядро d7

View File

@ -1,15 +1,15 @@
Bitrix module Bitrix module
============= =============
Bitrix module for interaction with [retailCRM](http://www.retailcrm.ru) through [REST API](http://retailcrm.ru/docs/Разработчики). Bitrix module for interaction with [retailCRM](http://www.retailcrm.ru) through [REST API](http://www.retailcrm.ru/docs/Developers/Index).
Module allows: Module allows:
* Exchange the orders with retailCRM * Exchange the orders with retailCRM
* Configure relations between dictionaries of retailCRM and Bitrix (statuses, payments, delivery types and etc) * Configure relations between dictionaries of retailCRM and Bitrix (statuses, payments, delivery types and etc)
* Generate [ICML](http://docs.retailcrm.ru/index.php?n=Разработчики.ФорматICML) (Intaro Markup Language) for catalog loading by retailCRM * Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) for catalog loading by retailCRM
Installation Installation
------------- -------------
You should install module through [Bitrix.Marketplace](http://marketplace.1c-bitrix.ru/solutions/intaro.intarocrm/). You should install module through [Bitrix.Marketplace](http://marketplace.1c-bitrix.ru/solutions/intaro.retailcrm/).

View File

@ -14,8 +14,7 @@ class Logger
{ {
$rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y')); $rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y'));
$ar = $rsSites->Fetch(); $ar = $rsSites->Fetch();
if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')) if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')) {
{
mkdir($ar['ABS_DOC_ROOT'] . $this->logPath . '/'); mkdir($ar['ABS_DOC_ROOT'] . $this->logPath . '/');
} }
$file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log'; $file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log';
@ -24,7 +23,7 @@ class Logger
$data['DATA'] = $dump; $data['DATA'] = $dump;
$f = fopen($file, "a+"); $f = fopen($file, "a+");
fwrite($f, print_r($data,true)); fwrite($f, print_r($data, true));
fclose($f); fclose($f);
// if filesize more than 5 Mb rotate it // if filesize more than 5 Mb rotate it

View File

@ -7,23 +7,25 @@ class RCrmActions
const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED'; const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
public static function SitesList(){ public static function SitesList()
{
$arSites = array(); $arSites = array();
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){ while ($ar = $rsSites->Fetch()) {
$arSites[] = $ar; $arSites[] = $ar;
} }
return $arSites; return $arSites;
} }
public static function OrderTypesList($arSites){ public static function OrderTypesList($arSites)
{
$orderTypesList = array(); $orderTypesList = array();
foreach($arSites as $site){ foreach ($arSites as $site) {
$personTypes = \Bitrix\Sale\PersonType::load($site['LID']); $personTypes = \Bitrix\Sale\PersonType::load($site['LID']);
$bitrixOrderTypesList = array(); $bitrixOrderTypesList = array();
foreach($personTypes as $personType){ foreach ($personTypes as $personType) {
if(!array_key_exists($personType['ID'], $orderTypesList)){ if (!array_key_exists($personType['ID'], $orderTypesList)) {
$bitrixOrderTypesList[$personType['ID']] = $personType; $bitrixOrderTypesList[$personType['ID']] = $personType;
} }
asort($bitrixOrderTypesList); asort($bitrixOrderTypesList);
@ -34,12 +36,13 @@ class RCrmActions
return $orderTypesList; return $orderTypesList;
} }
public static function DeliveryList(){ public static function DeliveryList()
{
$bitrixDeliveryTypesList = array(); $bitrixDeliveryTypesList = array();
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
$noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
foreach($arDeliveryServiceAll as $arDeliveryService){ foreach ($arDeliveryServiceAll as $arDeliveryService) {
if($arDeliveryService['PARENT_ID'] == '0' && $arDeliveryService['ID'] != $noOrderId){ if ($arDeliveryService['PARENT_ID'] == '0' && $arDeliveryService['ID'] != $noOrderId) {
$bitrixDeliveryTypesList[] = $arDeliveryService; $bitrixDeliveryTypesList[] = $arDeliveryService;
} }
} }
@ -47,36 +50,38 @@ class RCrmActions
return $bitrixDeliveryTypesList; return $bitrixDeliveryTypesList;
} }
public static function PaymentList(){ public static function PaymentList()
{
$bitrixPaymentTypesList = array(); $bitrixPaymentTypesList = array();
$dbPaymentAll = \Bitrix\Sale\PaySystem\Manager::getList(array( $dbPaymentAll = \Bitrix\Sale\PaySystem\Manager::getList(array(
'select' => array('ID', 'NAME'), 'select' => array('ID', 'NAME'),
'filter' => array('ACTIVE' => 'Y') 'filter' => array('ACTIVE' => 'Y')
)); ));
while($payment = $dbPaymentAll->fetch()) while ($payment = $dbPaymentAll->fetch()) {
{
$bitrixPaymentTypesList[] = $payment; $bitrixPaymentTypesList[] = $payment;
} }
return $bitrixPaymentTypesList; return $bitrixPaymentTypesList;
} }
public static function StatusesList(){ public static function StatusesList()
{
$bitrixPaymentStatusesList = array(); $bitrixPaymentStatusesList = array();
$arStatusesAll = \Bitrix\Sale\OrderStatus::getAllStatusesNames(); $arStatusesAll = \Bitrix\Sale\OrderStatus::getAllStatusesNames();
foreach($arStatusesAll as $key => $arStatus){ foreach ($arStatusesAll as $key => $arStatus) {
$bitrixPaymentStatusesList[$key] = array('ID' => $key, 'NAME' => $arStatus); $bitrixPaymentStatusesList[$key] = array('ID' => $key, 'NAME' => $arStatus);
} }
return $bitrixPaymentStatusesList; return $bitrixPaymentStatusesList;
} }
public static function OrderPropsList(){ public static function OrderPropsList()
{
$bitrixPropsList = array(); $bitrixPropsList = array();
$arPropsAll = \Bitrix\Sale\Internals\OrderPropsTable::getList(array( $arPropsAll = \Bitrix\Sale\Internals\OrderPropsTable::getList(array(
'select' => array('*') 'select' => array('*')
)); ));
while ($prop = $arPropsAll->Fetch()){ while ($prop = $arPropsAll->Fetch()) {
$bitrixPropsList[$prop['PERSON_TYPE_ID']][] = $prop; $bitrixPropsList[$prop['PERSON_TYPE_ID']][] = $prop;
} }
@ -87,8 +92,8 @@ class RCrmActions
* w+ event in bitrix log * w+ event in bitrix log
*/ */
public static function eventLog($auditType, $itemId, $description) { public static function eventLog($auditType, $itemId, $description)
{
CEventLog::Add(array( CEventLog::Add(array(
"SEVERITY" => "SECURITY", "SEVERITY" => "SECURITY",
"AUDIT_TYPE_ID" => $auditType, "AUDIT_TYPE_ID" => $auditType,
@ -105,7 +110,8 @@ class RCrmActions
* @return self name * @return self name
*/ */
public static function uploadOrdersAgent() { public static function uploadOrdersAgent()
{
RetailCrmOrder::uploadOrders(); RetailCrmOrder::uploadOrders();
$failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0)); $failedIds = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_FAILED_IDS, 0));
if (is_array($failedIds) && !empty($failedIds)) { if (is_array($failedIds) && !empty($failedIds)) {
@ -122,8 +128,9 @@ class RCrmActions
* @return self name * @return self name
*/ */
public static function orderAgent() { public static function orderAgent()
if(COption::GetOptionString('main', 'agents_use_crontab', 'N') != 'N') { {
if (COption::GetOptionString('main', 'agents_use_crontab', 'N') != 'N') {
define('NO_AGENT_CHECK', true); define('NO_AGENT_CHECK', true);
} }
@ -141,7 +148,8 @@ class RCrmActions
* @param array $arr * @param array $arr
* @return array * @return array
*/ */
public static function clearArr($arr) { public static function clearArr($arr)
{
if (is_array($arr) === false) { if (is_array($arr) === false) {
return $arr; return $arr;
} }
@ -163,7 +171,8 @@ class RCrmActions
* @param $str in SITE_CHARSET * @param $str in SITE_CHARSET
* @return $str in utf-8 * @return $str in utf-8
*/ */
public static function toJSON($str) { public static function toJSON($str)
{
global $APPLICATION; global $APPLICATION;
return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8'); return $APPLICATION->ConvertCharset($str, SITE_CHARSET, 'utf-8');
@ -175,13 +184,15 @@ class RCrmActions
* @param $str in utf-8 * @param $str in utf-8
* @return $str in SITE_CHARSET * @return $str in SITE_CHARSET
*/ */
public static function fromJSON($str) { public static function fromJSON($str)
{
global $APPLICATION; global $APPLICATION;
return $APPLICATION->ConvertCharset($str, 'utf-8', SITE_CHARSET); return $APPLICATION->ConvertCharset($str, 'utf-8', SITE_CHARSET);
} }
public static function explodeFIO($fio) { public static function explodeFIO($fio)
{
$newFio = empty($fio) ? false : explode(" ", $fio, 3); $newFio = empty($fio) ? false : explode(" ", $fio, 3);
$result = array(); $result = array();
switch (count($newFio)) { switch (count($newFio)) {
@ -210,8 +221,9 @@ class RCrmActions
return $result; return $result;
} }
public static function apiMethod($api, $methodApi, $method, $params, $site = null) { public static function apiMethod($api, $methodApi, $method, $params, $site = null)
switch($methodApi){ {
switch ($methodApi) {
case 'ordersGet': case 'ordersGet':
case 'ordersEdit': case 'ordersEdit':
case 'customersGet': case 'customersGet':

View File

@ -32,24 +32,6 @@ class RestNormalizer
$this->server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); $this->server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot();
} }
/**
* Installation file validation
* @param string $file The path to the file validation
* @return void
* @access public
* @final
*/
// final public function setValidation($file = false)
// {
// if ($file === false || is_null($file) || is_file($file) === false) {
// $file = $this->server . '/bitrix/modules/intaro.intarocrm/classes/general/config/retailcrm.json';
// }
// if (json_decode(file_get_contents($file)) === null || $this->parseConfig($file) === false) {
// ICrmOrderActions::eventLog('RestNormalizer', 'intaro.retailcrm', 'Incorrect file normalize.');
// return false;
// }
// }
/** /**
* Parsing the file validation * Parsing the file validation
* @param string $file The path to the file validation * @param string $file The path to the file validation
@ -117,10 +99,9 @@ class RestNormalizer
$formatted = array(); $formatted = array();
foreach ($data as $code => $value) { foreach ($data as $code => $value) {
if (isset($this->validation[ $code ]) && $this->validation[ $code ]['type'] == 'skip') { if (isset($this->validation[ $code ]) && $this->validation[ $code ]['type'] == 'skip') {
$formatted[ $code ] = $value; $formatted[ $code ] = $value;
}elseif (isset($this->validation[ $code ]) && is_array($value) === false) { } elseif (isset($this->validation[ $code ]) && is_array($value) === false) {
$formatted[ $code ] = $this->setFormat($value, $this->validation[ $code ]); $formatted[ $code ] = $this->setFormat($value, $this->validation[ $code ]);
} elseif (is_array($value)) { } elseif (is_array($value)) {
$formatted[ $code ] = $this->formatting($value, true); $formatted[ $code ] = $this->formatting($value, true);
@ -208,7 +189,7 @@ class RestNormalizer
} elseif (isset($validation['min']) && mb_strlen($data) < $validation['min']) { } elseif (isset($validation['min']) && mb_strlen($data) < $validation['min']) {
$pad = isset($validation['pad']) && mb_strlen($validation['pad']) == 1 ? $validation['pad'] : ' '; $pad = isset($validation['pad']) && mb_strlen($validation['pad']) == 1 ? $validation['pad'] : ' ';
$data .= str_repeat($pad, $validation['min'] - mb_strlen($data)); $data .= str_repeat($pad, $validation['min'] - mb_strlen($data));
}elseif (isset($validation['max']) && mb_strlen($data) > $validation['max']) { } elseif (isset($validation['max']) && mb_strlen($data) > $validation['max']) {
$data = mb_substr($data, 0, $validation['max']); $data = mb_substr($data, 0, $validation['max']);
} }

View File

@ -2,7 +2,8 @@
/** /**
* RCrmEvent * RCrmEvent
*/ */
class RetailCrmEvent { class RetailCrmEvent
{
protected static $MODULE_ID = 'intaro.retailcrm'; protected static $MODULE_ID = 'intaro.retailcrm';
protected static $CRM_API_HOST_OPTION = 'api_host'; protected static $CRM_API_HOST_OPTION = 'api_host';
protected static $CRM_API_KEY_OPTION = 'api_key'; protected static $CRM_API_KEY_OPTION = 'api_key';
@ -24,12 +25,13 @@ class RetailCrmEvent {
* *
* @param mixed $arFields - User arFields * @param mixed $arFields - User arFields
*/ */
function OnAfterUserUpdate($arFields) { function OnAfterUserUpdate($arFields)
if(isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']){ {
if (isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) {
return; return;
} }
if(!$arFields['RESULT']){ if (!$arFields['RESULT']) {
return; return;
} }
@ -40,7 +42,7 @@ class RetailCrmEvent {
$optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0));
$resultOrder = RetailCrmUser::customerEdit($arFields, $api, $optionsSitesList); $resultOrder = RetailCrmUser::customerEdit($arFields, $api, $optionsSitesList);
if(!$resultOrder) { if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::OnAfterUserUpdate', 'RetailCrmUser::customerEdit', 'error update customer'); RCrmActions::eventLog('RetailCrmEvent::OnAfterUserUpdate', 'RetailCrmUser::customerEdit', 'error update customer');
} }
@ -63,10 +65,11 @@ class RetailCrmEvent {
* @param mixed $ID - Order id * @param mixed $ID - Order id
* @param mixed $arFields - Order arFields * @param mixed $arFields - Order arFields
*/ */
function OnOrderSave($ID, $arFields, $arOrder, $isNew) { // function OnOrderSave($ID, $arFields, $arOrder, $isNew)
$GLOBALS['RETAILCRM_EVENT_OLD'] = true; // {
return; // $GLOBALS['RETAILCRM_EVENT_OLD'] = true;
} // return;
// }
/** /**
* onUpdateOrder * onUpdateOrder
@ -74,8 +77,9 @@ class RetailCrmEvent {
* @param mixed $ID - Order id * @param mixed $ID - Order id
* @param mixed $arFields - Order arFields * @param mixed $arFields - Order arFields
*/ */
function onUpdateOrder($ID, $arFields) { function onUpdateOrder($ID, $arFields)
if(isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']){ {
if (isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) {
$GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false; $GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false;
return; return;
} }
@ -89,7 +93,8 @@ class RetailCrmEvent {
* *
* @param object $event - Order object * @param object $event - Order object
*/ */
function orderDelete($event){ function orderDelete($event)
{
$GLOBALS['RETAILCRM_ORDER_DELETE'] = true; $GLOBALS['RETAILCRM_ORDER_DELETE'] = true;
return; return;
} }
@ -100,8 +105,9 @@ class RetailCrmEvent {
* @param object $event - Order object * @param object $event - Order object
*/ */
function orderSave($event){ function orderSave($event)
if($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true){ {
if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true) {
if (!CModule::IncludeModule('iblock')) { if (!CModule::IncludeModule('iblock')) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found');
return true; return true;
@ -118,13 +124,11 @@ class RetailCrmEvent {
} }
//проверка на существование getParameter("ENTITY") //проверка на существование getParameter("ENTITY")
if(method_exists($event, 'getId')){ if (method_exists($event, 'getId')) {
$obOrder = $event; $obOrder = $event;
} } elseif (method_exists($event, 'getParameter')) {
elseif(method_exists($event, 'getParameter')){
$obOrder = $event->getParameter("ENTITY"); $obOrder = $event->getParameter("ENTITY");
} } else {
else{
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error');
return true; return true;
} }
@ -162,23 +166,22 @@ class RetailCrmEvent {
)); ));
//многосайтовость //многосайтовость
$site = count($optionsSitesList)>1 ? $optionsSitesList[$arOrder['LID']] : null; $site = count($optionsSitesList) > 1 ? $optionsSitesList[$arOrder['LID']] : null;
//проверка на новый заказ //проверка на новый заказ
$orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site);
if(isset($orderCrm['order'])){ if (isset($orderCrm['order'])) {
$methodApi = 'ordersEdit'; $methodApi = 'ordersEdit';
} } else {
else{
$methodApi = 'ordersCreate'; $methodApi = 'ordersCreate';
} }
//user //user
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site); $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site);
if(!isset($userCrm['customer'])){ if (!isset($userCrm['customer'])) {
$arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch(); $arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch();
$resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site); $resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site);
if(!$resultUser) { if (!$resultUser) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer');
return true; return true;
} }
@ -186,7 +189,7 @@ class RetailCrmEvent {
//order //order
$resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi); $resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi);
if(!$resultOrder) { if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order'); RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order');
return true; return true;
} }

View File

@ -25,7 +25,8 @@ class RetailCrmHistory
const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED'; const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
public static function customerHistory(){ public static function customerHistory()
{
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'iblock', 'module not found');
return false; return false;
@ -46,11 +47,11 @@ class RetailCrmHistory
$historyFilter = array(); $historyFilter = array();
$historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY); $historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY);
if($historyStart && $historyStart > 0){ if ($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart; $historyFilter['sinceId'] = $historyStart;
} }
while(true){ while (true) {
try { try {
$customerHistory = $api->customersHistory($historyFilter); $customerHistory = $api->customersHistory($historyFilter);
} catch (\RetailCrm\Exception\CurlException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
@ -83,7 +84,7 @@ class RetailCrmHistory
$newUser = new CUser; $newUser = new CUser;
foreach($customers as $customer){ foreach ($customers as $customer) {
if (function_exists('retailCrmBeforeCustomerSave')) { if (function_exists('retailCrmBeforeCustomerSave')) {
$newResCustomer = retailCrmBeforeCustomerSave($customer); $newResCustomer = retailCrmBeforeCustomerSave($customer);
if (is_array($newResCustomer) && !empty($newResCustomer)) { if (is_array($newResCustomer) && !empty($newResCustomer)) {
@ -91,7 +92,7 @@ class RetailCrmHistory
} }
} }
if(isset($customer['deleted'])){ if (isset($customer['deleted'])) {
continue; continue;
} }
@ -158,43 +159,42 @@ class RetailCrmHistory
$customer['externalId'] = $registeredUserID; $customer['externalId'] = $registeredUserID;
} }
if(isset($customer['externalId'])){ if (isset($customer['externalId'])) {
$arUser = array(); $arUser = array();
if(array_key_exists('firstName', $customer)){ if (array_key_exists('firstName', $customer)) {
$arUser["NAME"] = $customer['firstName'] ? RCrmActions::fromJSON($customer['firstName']) : ''; $arUser["NAME"] = $customer['firstName'] ? RCrmActions::fromJSON($customer['firstName']) : '';
} }
if(array_key_exists('lastName', $customer)){ if (array_key_exists('lastName', $customer)) {
$arUser["LAST_NAME"] = $customer['lastName'] ? RCrmActions::fromJSON($customer['lastName']) : ''; $arUser["LAST_NAME"] = $customer['lastName'] ? RCrmActions::fromJSON($customer['lastName']) : '';
} }
if(array_key_exists('patronymic', $customer)){ if (array_key_exists('patronymic', $customer)) {
$arUser["SECOND_NAME"] = $customer['patronymic'] ? RCrmActions::fromJSON($customer['patronymic']) : ''; $arUser["SECOND_NAME"] = $customer['patronymic'] ? RCrmActions::fromJSON($customer['patronymic']) : '';
} }
if(array_key_exists('email', $customer)){ if (array_key_exists('email', $customer)) {
$arUser["EMAIL"] = $customer['email'] ? RCrmActions::fromJSON($customer['email']) : ''; $arUser["EMAIL"] = $customer['email'] ? RCrmActions::fromJSON($customer['email']) : '';
} }
if(isset($customer['phones'])){ if (isset($customer['phones'])) {
$user = CUser::GetList(($by="ID"), ($order="desc"), array('ID' => $customer['externalId']), array('FIELDS' => array('PERSONAL_PHONE', 'PERSONAL_MOBILE')))->fetch(); $user = CUser::GetList(($by="ID"), ($order="desc"), array('ID' => $customer['externalId']), array('FIELDS' => array('PERSONAL_PHONE', 'PERSONAL_MOBILE')))->fetch();
foreach($customer['phones'] as $phone){ foreach ($customer['phones'] as $phone) {
if(isset($phone['old_number']) && in_array($phone['old_number'], $user)){ if (isset($phone['old_number']) && in_array($phone['old_number'], $user)) {
$key = array_search($phone['old_number'], $user); $key = array_search($phone['old_number'], $user);
if(isset($phone['number'])){ if (isset($phone['number'])) {
$arUser[$key] = $phone['number']; $arUser[$key] = $phone['number'];
$user[$key] = $phone['number']; $user[$key] = $phone['number'];
} } else {
else{
$arUser[$key] = ''; $arUser[$key] = '';
$user[$key] = ''; $user[$key] = '';
} }
} }
if(isset($phone['number'])){ if (isset($phone['number'])) {
if((!isset($user['PERSONAL_PHONE']) || strlen($user['PERSONAL_PHONE']) == 0) && $user['PERSONAL_MOBILE'] != $phone['number']){ if ((!isset($user['PERSONAL_PHONE']) || strlen($user['PERSONAL_PHONE']) == 0) && $user['PERSONAL_MOBILE'] != $phone['number']) {
$arUser['PERSONAL_PHONE'] = $phone['number']; $arUser['PERSONAL_PHONE'] = $phone['number'];
$user['PERSONAL_PHONE'] = $phone['number']; $user['PERSONAL_PHONE'] = $phone['number'];
continue; continue;
} }
if((!isset($user['PERSONAL_MOBILE']) || strlen($user['PERSONAL_MOBILE']) == 0) && $user['PERSONAL_PHONE'] != $phone['number']){ if ((!isset($user['PERSONAL_MOBILE']) || strlen($user['PERSONAL_MOBILE']) == 0) && $user['PERSONAL_PHONE'] != $phone['number']) {
$arUser['PERSONAL_MOBILE'] = $phone['number']; $arUser['PERSONAL_MOBILE'] = $phone['number'];
$user['PERSONAL_MOBILE'] = $phone['number']; $user['PERSONAL_MOBILE'] = $phone['number'];
continue; continue;
@ -204,7 +204,7 @@ class RetailCrmHistory
} }
$u = $newUser->Update($customer['externalId'], $arUser); $u = $newUser->Update($customer['externalId'], $arUser);
if(!$u){ if (!$u) {
RCrmActions::eventLog('RetailCrmHistory::customerHistory', 'Error update user', $newUser->LAST_ERROR); RCrmActions::eventLog('RetailCrmHistory::customerHistory', 'Error update user', $newUser->LAST_ERROR);
} }
@ -220,7 +220,7 @@ class RetailCrmHistory
$end = array_pop($customerH); $end = array_pop($customerH);
COption::SetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY, $end['id']); COption::SetOptionString(self::$MODULE_ID, self::$CRM_CUSTOMER_HISTORY, $end['id']);
if($customerHistory['pagination']['totalPageCount'] == 1){ if ($customerHistory['pagination']['totalPageCount'] == 1) {
return true; return true;
} }
//новый фильтр для истории //новый фильтр для истории
@ -228,7 +228,8 @@ class RetailCrmHistory
} }
} }
public static function orderHistory() { public static function orderHistory()
{
global $USER; global $USER;
if (is_object($USER) == false) { if (is_object($USER) == false) {
$USER = new RetailUser; $USER = new RetailUser;
@ -282,11 +283,11 @@ class RetailCrmHistory
$historyFilter = array(); $historyFilter = array();
$historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY); $historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY);
if($historyStart && $historyStart > 0){ if ($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart; $historyFilter['sinceId'] = $historyStart;
} }
while(true){ while (true) {
try { try {
$orderHistory = $api->ordersHistory($historyFilter); $orderHistory = $api->ordersHistory($historyFilter);
} catch (\RetailCrm\Exception\CurlException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
@ -309,7 +310,7 @@ class RetailCrmHistory
$log = new Logger(); $log = new Logger();
$log->write($orderH, 'orderHistory'); $log->write($orderH, 'orderHistory');
if(count($orderH) == 0){ if (count($orderH) == 0) {
return true; return true;
} }
@ -326,7 +327,7 @@ class RetailCrmHistory
} }
} }
if(isset($order['deleted'])){ if (isset($order['deleted'])) {
continue; continue;
} }
@ -371,13 +372,15 @@ class RetailCrmHistory
"PASSWORD" => $userPassword, "PASSWORD" => $userPassword,
"CONFIRM_PASSWORD" => $userPassword "CONFIRM_PASSWORD" => $userPassword
); );
if($order['customer']['phones'][0]){ if ($order['customer']['phones'][0]) {
$arFields['PERSONAL_PHONE'] = $order['customer']['phones'][0]; $arFields['PERSONAL_PHONE'] = $order['customer']['phones'][0];
} }
if($order['customer']['phones'][1]){ if ($order['customer']['phones'][1]) {
$arFields['PERSONAL_MOBILE'] = $order['customer']['phones'][1]; $arFields['PERSONAL_MOBILE'] = $order['customer']['phones'][1];
} }
$registeredUserID = $newUser->Add($arFields); $registeredUserID = $newUser->Add($arFields);
if ($registeredUserID === false) { if ($registeredUserID === false) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'CUser::Register', 'Error register user'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'CUser::Register', 'Error register user');
continue; continue;
@ -405,10 +408,9 @@ class RetailCrmHistory
$order['customer']['externalId'] = $registeredUserID; $order['customer']['externalId'] = $registeredUserID;
} }
if(isset($optionsSitesList)){ if (isset($optionsSitesList)) {
$site = array_search($order['site'], $optionsSitesList); $site = array_search($order['site'], $optionsSitesList);
} } else {
else{
$site = CSite::GetDefSite(); $site = CSite::GetDefSite();
} }
@ -434,8 +436,7 @@ class RetailCrmHistory
continue; continue;
} }
} } else {
else{
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::create', 'Error order create'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::create', 'Error order create');
} }
$order['externalId'] = $externalId; $order['externalId'] = $externalId;
@ -444,47 +445,45 @@ class RetailCrmHistory
if (isset($order['externalId']) && $order['externalId']) { if (isset($order['externalId']) && $order['externalId']) {
$newOrder = Bitrix\Sale\Order::load($order['externalId']); $newOrder = Bitrix\Sale\Order::load($order['externalId']);
if(!$newOrder instanceof \Bitrix\Sale\Order){ if (!$newOrder instanceof \Bitrix\Sale\Order) {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::load', 'Error order load'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::load', 'Error order load');
continue; continue;
} }
if($optionsOrderNumbers == 'Y' && isset($order['number'])){ if ($optionsOrderNumbers == 'Y' && isset($order['number'])) {
$newOrder->setField('ACCOUNT_NUMBER', $order['number']); $newOrder->setField('ACCOUNT_NUMBER', $order['number']);
} }
//var_dump(array($order['externalId'], $newOrder->getField('PERSON_TYPE_ID'), $optionsOrderTypes, $order));
$personType = $newOrder->getField('PERSON_TYPE_ID'); $personType = $newOrder->getField('PERSON_TYPE_ID');
if($optionsOrderTypes[$order['orderType']]){ if ($optionsOrderTypes[$order['orderType']]) {
if($personType != $optionsOrderTypes[$order['orderType']] && $personType != 0){ if ($personType != $optionsOrderTypes[$order['orderType']] && $personType != 0) {
$propsRemove = true; $propsRemove = true;
} }
$personType = $optionsOrderTypes[$order['orderType']]; $personType = $optionsOrderTypes[$order['orderType']];
$newOrder->setField('PERSON_TYPE_ID', $personType); $newOrder->setField('PERSON_TYPE_ID', $personType);
} } elseif ($personType == 0) {
elseif($personType == 0){
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'orderType not found', 'PERSON_TYPE_ID = 0'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'orderType not found', 'PERSON_TYPE_ID = 0');
} }
//status //status
if($optionsPayStatuses[$order['status']]){ if ($optionsPayStatuses[$order['status']]) {
$newOrder->setField('STATUS_ID', $optionsPayStatuses[$order['status']]); $newOrder->setField('STATUS_ID', $optionsPayStatuses[$order['status']]);
if(in_array($optionsPayStatuses[$order['status']], $optionsCanselOrder)){ if (in_array($optionsPayStatuses[$order['status']], $optionsCanselOrder)) {
$newOrder->setField('CANCELED', 'Y'); $newOrder->setField('CANCELED', 'Y');
} } else {
else{
$newOrder->setField('CANCELED', 'N'); $newOrder->setField('CANCELED', 'N');
} }
} }
if(array_key_exists('statusComment', $order)){ if (array_key_exists('statusComment', $order)) {
self::setProp($newOrder, $order['statusComment'], 'REASON_CANCELED'); self::setProp($newOrder, $order['statusComment'], 'REASON_CANCELED');
} }
$propertyCollection = $newOrder->getPropertyCollection(); $propertyCollection = $newOrder->getPropertyCollection();
$propertyCollectionArr = $propertyCollection->getArray(); $propertyCollectionArr = $propertyCollection->getArray();
$nProps = array(); $nProps = array();
foreach($propertyCollectionArr['properties'] as $orderProp){ foreach ($propertyCollectionArr['properties'] as $orderProp) {
if($orderProp['ID'][0] == 'n'){ if ($orderProp['ID'][0] == 'n') {
$orderProp['ID'] = substr($orderProp['ID'], 1); $orderProp['ID'] = substr($orderProp['ID'], 1);
$orderProp['ID'] = $propertyCollection->getItemById($orderProp['ID'])->getField('ORDER_PROPS_ID'); $orderProp['ID'] = $propertyCollection->getItemById($orderProp['ID'])->getField('ORDER_PROPS_ID');
} }
@ -492,8 +491,8 @@ class RetailCrmHistory
} }
$propertyCollectionArr['properties'] = $nProps; $propertyCollectionArr['properties'] = $nProps;
if($propsRemove){//удаляем старые свойства if ($propsRemove) {//удаляем старые свойства
foreach($propertyCollectionArr['properties'] as $orderProp){ foreach ($propertyCollectionArr['properties'] as $orderProp) {
$somePropValue = $propertyCollection->getItemByOrderPropertyId($orderProp['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($orderProp['ID']);
self::setProp($somePropValue); self::setProp($somePropValue);
} }
@ -511,21 +510,21 @@ class RetailCrmHistory
} }
$propsKey = array(); $propsKey = array();
foreach($propertyCollectionArr['properties'] as $prop){ foreach ($propertyCollectionArr['properties'] as $prop) {
$propsKey[$prop['CODE']]['ID'] = $prop['ID']; $propsKey[$prop['CODE']]['ID'] = $prop['ID'];
$propsKey[$prop['CODE']]['TYPE'] = $prop['TYPE']; $propsKey[$prop['CODE']]['TYPE'] = $prop['TYPE'];
} }
//fio //fio
if($order['firstName'] || $order['lastName'] || $order['patronymic']){ if ($order['firstName'] || $order['lastName'] || $order['patronymic']) {
$fio = ''; $fio = '';
foreach($propertyCollectionArr['properties'] as $prop){ foreach ($propertyCollectionArr['properties'] as $prop) {
if(in_array($optionsOrderProps[$personType]['fio'], $prop)){ if (in_array($optionsOrderProps[$personType]['fio'], $prop)) {
$fio = $newOrder->getPropertyCollection()->getItemByOrderPropertyId($prop['ID']); $fio = $newOrder->getPropertyCollection()->getItemByOrderPropertyId($prop['ID']);
} }
} }
$fio = RCrmActions::explodeFIO($fio); $fio = RCrmActions::explodeFIO($fio);
if($fio){ if ($fio) {
$order['fio'] = trim( $order['fio'] = trim(
implode( implode(
' ', ' ',
@ -536,8 +535,7 @@ class RetailCrmHistory
) )
) )
); );
} } else {
else{
$order['fio'] = trim( $order['fio'] = trim(
implode( implode(
' ', ' ',
@ -553,21 +551,19 @@ class RetailCrmHistory
//optionsOrderProps //optionsOrderProps
if($optionsOrderProps[$personType]){ if ($optionsOrderProps[$personType]) {
foreach($optionsOrderProps[$personType] as $key => $orderProp){ foreach ($optionsOrderProps[$personType] as $key => $orderProp) {
if(array_key_exists($key, $order)){ if (array_key_exists($key, $order)) {
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, $order[$key]); self::setProp($somePropValue, $order[$key]);
} } elseif (array_key_exists($key, $order['delivery']['address'])) {
elseif(array_key_exists($key, $order['delivery']['address'])){ if ($propsKey[$key]['TYPE'] == 'LOCATION') {
if($propsKey[$key]['TYPE'] == 'LOCATION'){
$parameters['filter']['NAME'] = $order['delivery']['address'][$key]; $parameters['filter']['NAME'] = $order['delivery']['address'][$key];
$parameters['filter']['LANGUAGE_ID'] = 'ru'; $parameters['filter']['LANGUAGE_ID'] = 'ru';
$location = \Bitrix\Sale\Location\LocationTable::getListFast($parameters)->fetch(); $location = \Bitrix\Sale\Location\LocationTable::getListFast($parameters)->fetch();
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, $location['CODE']); self::setProp($somePropValue, $location['CODE']);
} } else {
else{
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, $order['delivery']['address'][$key]); self::setProp($somePropValue, $order['delivery']['address'][$key]);
} }
@ -575,39 +571,38 @@ class RetailCrmHistory
} }
} }
//optionsLegalDetails //optionsLegalDetails
if($optionsLegalDetails[$personType]){ if ($optionsLegalDetails[$personType]) {
foreach($optionsLegalDetails[$personType] as $key => $orderProp){ foreach ($optionsLegalDetails[$personType] as $key => $orderProp) {
if(array_key_exists($key, $order)){ if (array_key_exists($key, $order)) {
$somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']); $somePropValue = $propertyCollection->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, $order[$key]); self::setProp($somePropValue, $order[$key]);
} }
} }
} }
if($propsRemove){ if ($propsRemove) {
$order = $orderDump; $order = $orderDump;
} }
//paymentStatus //paymentStatus
if($optionsPayment[$order['paymentStatus']]){ if ($optionsPayment[$order['paymentStatus']]) {
$newOrder->setFieldNoDemand('PAYED', $optionsPayment[$order['paymentStatus']]); $newOrder->setFieldNoDemand('PAYED', $optionsPayment[$order['paymentStatus']]);
} }
//comments //comments
if(array_key_exists('customerComment', $order)){ if (array_key_exists('customerComment', $order)) {
self::setProp($newOrder, $order['customerComment'], 'USER_DESCRIPTION'); self::setProp($newOrder, $order['customerComment'], 'USER_DESCRIPTION');
} }
if(array_key_exists('managerComment', $order)){ if (array_key_exists('managerComment', $order)) {
self::setProp($newOrder, $order['managerComment'], 'COMMENTS'); self::setProp($newOrder, $order['managerComment'], 'COMMENTS');
} }
//items //items
$basket = $newOrder->getBasket(); $basket = $newOrder->getBasket();
foreach($order['items'] as $product){ foreach ($order['items'] as $product) {
$item = self::getExistsItem($basket, 'catalog', $product['offer']['externalId']); $item = self::getExistsItem($basket, 'catalog', $product['offer']['externalId']);
if(!$item){ if (!$item) {
$item = $basket->createItem('catalog', $product['offer']['externalId']); $item = $basket->createItem('catalog', $product['offer']['externalId']);
if($item instanceof \Bitrix\Sale\Basket){ if ($item instanceof \Bitrix\Sale\Basket) {
$elem = self::getInfoElement(); $elem = self::getInfoElement();
$item->setFields(array( $item->setFields(array(
'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(), 'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(),
@ -616,19 +611,18 @@ class RetailCrmHistory
'NAME' => $elem['NAME'], 'NAME' => $elem['NAME'],
'DETAIL_PAGE_URL' => $elem['URL'] 'DETAIL_PAGE_URL' => $elem['URL']
)); ));
} } else {
else{
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'createItem', 'Error item add'); RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'createItem', 'Error item add');
continue; continue;
} }
} }
if($product['quantity']){ if ($product['quantity']) {
$item->setFieldNoDemand('QUANTITY', $product['quantity']); $item->setFieldNoDemand('QUANTITY', $product['quantity']);
} }
if(array_key_exists('discount', $product) || array_key_exists('discountPercent', $product)){ if (array_key_exists('discount', $product) || array_key_exists('discountPercent', $product)) {
if(!isset($orderCrm)){ if (!isset($orderCrm)) {
try { try {
$orderCrm = $api->ordersGet($order['id'], 'id'); $orderCrm = $api->ordersGet($order['id'], 'id');
} catch (\RetailCrm\Exception\CurlException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
@ -639,14 +633,14 @@ class RetailCrmHistory
} }
} }
foreach($orderCrm['order']['items'] as $itemCrm){ foreach ($orderCrm['order']['items'] as $itemCrm) {
if($itemCrm['offer']['externalId'] == $product['offer']['externalId']){ if ($itemCrm['offer']['externalId'] == $product['offer']['externalId']) {
$itemCost = $itemCrm['initialPrice'] - $itemCrm['discount'] - round(($itemCrm['initialPrice'] / 100 * $itemCrm['discountPercent']), 2); $itemCost = $itemCrm['initialPrice'] - $itemCrm['discount'] - round(($itemCrm['initialPrice'] / 100 * $itemCrm['discountPercent']), 2);
break; break;
} }
} }
if(isset($itemCost) && $itemCost > 0){ if (isset($itemCost) && $itemCost > 0) {
$item->setField('CUSTOM_PRICE', 'Y'); $item->setField('CUSTOM_PRICE', 'Y');
$item->setField('PRICE', $itemCost); $item->setField('PRICE', $itemCost);
$item->setField('DISCOUNT_NAME', ''); $item->setField('DISCOUNT_NAME', '');
@ -654,7 +648,7 @@ class RetailCrmHistory
} }
} }
if($product['delete']){ if ($product['delete']) {
$item->delete(); $item->delete();
} }
$basket->save(); $basket->save();
@ -662,14 +656,13 @@ class RetailCrmHistory
} }
$orderSumm = 0; $orderSumm = 0;
foreach($basket as $item){ foreach ($basket as $item) {
$orderSumm += $item->getFinalPrice(); $orderSumm += $item->getFinalPrice();
} }
if(array_key_exists('cost', $order['delivery'])){ if (array_key_exists('cost', $order['delivery'])) {
$deliverySumm = $order['delivery']['cost']; $deliverySumm = $order['delivery']['cost'];
} } else {
else{
$deliverySumm = $newOrder->getDeliveryPrice(); $deliverySumm = $newOrder->getDeliveryPrice();
} }
@ -680,14 +673,14 @@ class RetailCrmHistory
$newOrder->save(); $newOrder->save();
//payment //payment
if(array_key_exists('paymentType', $order)){ if (array_key_exists('paymentType', $order)) {
self::paySystemUpdate($order, $optionsPayTypes); self::paySystemUpdate($order, $optionsPayTypes);
} }
//delivery //delivery
if(array_key_exists('code', $order['delivery'])/* || array_key_exists('service', $order['delivery'])*/){ if (array_key_exists('code', $order['delivery'])/* || array_key_exists('service', $order['delivery'])*/) {
//если пусто, удаляем, если нет, update или add //если пусто, удаляем, если нет, update или add
if(!isset($orderCrm)){ if (!isset($orderCrm)) {
try { try {
$orderCrm = $api->ordersGet($order['id'], 'id'); $orderCrm = $api->ordersGet($order['id'], 'id');
} catch (\RetailCrm\Exception\CurlException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
@ -699,17 +692,17 @@ class RetailCrmHistory
} }
self::shipmentUpdate($orderCrm['order'], $optionsDelivTypes); self::shipmentUpdate($orderCrm['order'], $optionsDelivTypes);
} }
if(isset($orderCrm)){ if (isset($orderCrm)) {
unset($orderCrm); unset($orderCrm);
} }
//delivery cost //delivery cost
if(array_key_exists('cost', $order['delivery'])){//сделать такую же для оплаты при изменении суммы if (array_key_exists('cost', $order['delivery'])) {
$shipment = Bitrix\Sale\Shipment::getList(array( $shipment = Bitrix\Sale\Shipment::getList(array(
'filter' => array('ORDER_ID' => $order['externalId'], 'SYSTEM' => 'N'), 'filter' => array('ORDER_ID' => $order['externalId'], 'SYSTEM' => 'N'),
'order' => array('ID') 'order' => array('ID')
))->fetch(); ))->fetch();
if($shipment){ if ($shipment) {
Bitrix\Sale\Internals\ShipmentTable::update($shipment['ID'], array('BASE_PRICE_DELIVERY' => $order['delivery']['cost'], 'PRICE_DELIVERY' => $order['delivery']['cost'], 'CUSTOM_PRICE_DELIVERY' => 'Y')); Bitrix\Sale\Internals\ShipmentTable::update($shipment['ID'], array('BASE_PRICE_DELIVERY' => $order['delivery']['cost'], 'PRICE_DELIVERY' => $order['delivery']['cost'], 'CUSTOM_PRICE_DELIVERY' => 'Y'));
} }
@ -717,7 +710,9 @@ class RetailCrmHistory
} }
Bitrix\Sale\OrderTable::update($order['externalId'], array('MARKED' => 'N', 'EMP_MARKED_ID' => '', 'REASON_MARKED' => '')); Bitrix\Sale\OrderTable::update($order['externalId'], array('MARKED' => 'N', 'EMP_MARKED_ID' => '', 'REASON_MARKED' => ''));
self::updateShipmentItem($order['externalId']);
if (function_exists('retailCrmAfterOrderSave')) { if (function_exists('retailCrmAfterOrderSave')) {
retailCrmAfterOrderSave($order); retailCrmAfterOrderSave($order);
} }
@ -730,7 +725,7 @@ class RetailCrmHistory
$end = array_pop($orderH); $end = array_pop($orderH);
COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY, $end['id']); COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY, $end['id']);
if($orderHistory['pagination']['totalPageCount'] == 1){ if ($orderHistory['pagination']['totalPageCount'] == 1) {
return true; return true;
} }
//новый фильтр для истории //новый фильтр для истории
@ -739,79 +734,76 @@ class RetailCrmHistory
} }
public static function assemblyCustomer($customerHistory){ public static function assemblyCustomer($customerHistory)
{
$server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); $server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot();
$fields = array(); $fields = array();
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) { if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
$objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml'); $objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml');
foreach($objects->fields->field as $object) foreach ($objects->fields->field as $object) {
{
$fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object;
} }
} }
$customers = array(); $customers = array();
foreach ($customerHistory as $change) { foreach ($customerHistory as $change) {
$change['customer'] = self::removeEmpty($change['customer']); $change['customer'] = self::removeEmpty($change['customer']);
if($customers[$change['customer']['id']]){ if ($customers[$change['customer']['id']]) {
$customers[$change['customer']['id']] = array_merge($customers[$change['customer']['id']], $change['customer']); $customers[$change['customer']['id']] = array_merge($customers[$change['customer']['id']], $change['customer']);
} } else {
else{
$customers[$change['customer']['id']] = $change['customer']; $customers[$change['customer']['id']] = $change['customer'];
} }
if($change['customer']['contragent']['contragentType']){ if ($change['customer']['contragent']['contragentType']) {
$change['customer']['contragentType'] = self::newValue($change['customer']['contragent']['contragentType']); $change['customer']['contragentType'] = self::newValue($change['customer']['contragent']['contragentType']);
unset($change['customer']['contragent']); unset($change['customer']['contragent']);
} }
if($fields['customer'][$change['field']] == 'phones'){ if ($fields['customer'][$change['field']] == 'phones') {
$key = count($customers[$change['customer']['id']]['phones']); $key = count($customers[$change['customer']['id']]['phones']);
if(isset($change['oldValue'])){ if (isset($change['oldValue'])) {
$customers[$change['customer']['id']]['phones'][$key]['old_number'] = $change['oldValue']; $customers[$change['customer']['id']]['phones'][$key]['old_number'] = $change['oldValue'];
} }
if(isset($change['newValue'])){ if (isset($change['newValue'])) {
$customers[$change['customer']['id']]['phones'][$key]['number'] = $change['newValue']; $customers[$change['customer']['id']]['phones'][$key]['number'] = $change['newValue'];
} }
} } else {
else{ if ($fields['customerAddress'][$change['field']]) {
if($fields['customerAddress'][$change['field']]){
$customers[$change['customer']['id']]['address'][$fields['customerAddress'][$change['field']]] = $change['newValue']; $customers[$change['customer']['id']]['address'][$fields['customerAddress'][$change['field']]] = $change['newValue'];
} } elseif ($fields['customerContragent'][$change['field']]) {
elseif($fields['customerContragent'][$change['field']]){
$customers[$change['customer']['id']]['contragent'][$fields['customerContragent'][$change['field']]] = $change['newValue']; $customers[$change['customer']['id']]['contragent'][$fields['customerContragent'][$change['field']]] = $change['newValue'];
} } elseif ($fields['customer'][$change['field']]) {
elseif($fields['customer'][$change['field']]){
$customers[$change['customer']['id']][$fields['customer'][$change['field']]] = self::newValue($change['newValue']); $customers[$change['customer']['id']][$fields['customer'][$change['field']]] = self::newValue($change['newValue']);
} }
if(isset($change['created'])){ if (isset($change['created'])) {
$customers[$change['customer']['id']]['create'] = 1; $customers[$change['customer']['id']]['create'] = 1;
} }
if(isset($change['deleted'])){ if (isset($change['deleted'])) {
$customers[$change['customer']['id']]['deleted'] = 1; $customers[$change['customer']['id']]['deleted'] = 1;
} }
} }
} }
return $customers; return $customers;
} }
public static function assemblyOrder($orderHistory){ public static function assemblyOrder($orderHistory)
{
$server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot(); $server = \Bitrix\Main\Context::getCurrent()->getServer()->getDocumentRoot();
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) { if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
$objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml'); $objects = simplexml_load_file($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml');
foreach($objects->fields->field as $object) foreach ($objects->fields->field as $object) {
{
$fields[(string)$object["group"]][(string)$object["id"]] = (string)$object; $fields[(string)$object["group"]][(string)$object["id"]] = (string)$object;
} }
} }
$orders = array(); $orders = array();
foreach ($orderHistory as $change) { foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']); $change['order'] = self::removeEmpty($change['order']);
if($change['order']['items']){ if ($change['order']['items']) {
$items = array(); $items = array();
foreach($change['order']['items'] as $item){ foreach ($change['order']['items'] as $item) {
if(isset($change['created'])){ if (isset($change['created'])) {
$item['create'] = 1; $item['create'] = 1;
} }
$items[$item['id']] = $item; $items[$item['id']] = $item;
@ -819,113 +811,103 @@ class RetailCrmHistory
$change['order']['items'] = $items; $change['order']['items'] = $items;
} }
if($change['order']['contragent']['contragentType']){ if ($change['order']['contragent']['contragentType']) {
$change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']); $change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
unset($change['order']['contragent']); unset($change['order']['contragent']);
} }
if($orders[$change['order']['id']]){ if ($orders[$change['order']['id']]) {
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']); $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
} } else {
else{
$orders[$change['order']['id']] = $change['order']; $orders[$change['order']['id']] = $change['order'];
} }
if($change['item']){ if ($change['item']) {
if($orders[$change['order']['id']]['items'][$change['item']['id']]){ if ($orders[$change['order']['id']]['items'][$change['item']['id']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']); $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
} } else {
else{
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
} }
if(empty($change['oldValue']) && $change['field'] == 'order_product'){ if (empty($change['oldValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1; $orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1;
unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']); unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']);
} }
if(empty($change['newValue']) && $change['field'] == 'order_product'){ if (empty($change['newValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1; $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1;
} }
if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]){ if (!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
} }
} } else {
else{ if ($fields['delivery'][$change['field']] == 'service') {
if($fields['delivery'][$change['field']] == 'service'){
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
} } elseif ($fields['delivery'][$change['field']]) {
elseif($fields['delivery'][$change['field']]){
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']); $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
} } elseif ($fields['orderAddress'][$change['field']]) {
elseif($fields['orderAddress'][$change['field']]){
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
} } elseif ($fields['integrationDelivery'][$change['field']]) {
elseif($fields['integrationDelivery'][$change['field']]){
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']); $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
} } elseif ($fields['customerContragent'][$change['field']]) {
elseif($fields['customerContragent'][$change['field']]){
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
} } elseif (strripos($change['field'], 'custom_') !== false) {
elseif(strripos($change['field'], 'custom_') !== false){
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
} } elseif ($fields['order'][$change['field']]){
elseif($fields['order'][$change['field']]){
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']); $orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
} }
if(isset($change['created'])){ if (isset($change['created'])) {
$orders[$change['order']['id']]['create'] = 1; $orders[$change['order']['id']]['create'] = 1;
} }
if(isset($change['deleted'])){ if (isset($change['deleted'])) {
$orders[$change['order']['id']]['deleted'] = 1; $orders[$change['order']['id']]['deleted'] = 1;
} }
} }
} }
return $orders; return $orders;
} }
public static function shipmentUpdate($orderCrm, $optionsDelivTypes){ public static function shipmentUpdate($orderCrm, $optionsDelivTypes)
if(isset($orderCrm['delivery']['code'])){ {
if (isset($orderCrm['delivery']['code'])) {
$crmCode = $orderCrm['delivery']['code']; $crmCode = $orderCrm['delivery']['code'];
if(isset($orderCrm['delivery']['data']['deliveryType'])){ if (isset($orderCrm['delivery']['data']['deliveryType'])) {
$crmService = $orderCrm['delivery']['data']['deliveryType']; $crmService = $orderCrm['delivery']['data']['deliveryType'];
} } elseif (isset($orderCrm['delivery']['service'])) {
elseif (isset($orderCrm['delivery']['service'])) {
$crmService = $orderCrm['delivery']['service']; $crmService = $orderCrm['delivery']['service'];
} }
//подбираем код битриксового сервиса //подбираем код битриксового сервиса
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
foreach($arDeliveryServiceAll as $arDeliveryService){ foreach ($arDeliveryServiceAll as $arDeliveryService) {
$arDeliveryCode[$arDeliveryService['CODE']] = $arDeliveryService['ID']; $arDeliveryCode[$arDeliveryService['CODE']] = $arDeliveryService['ID'];
$arDeliveryID[$arDeliveryService['ID']] = $arDeliveryService; $arDeliveryID[$arDeliveryService['ID']] = $arDeliveryService;
if($arDeliveryService['ID'] == $optionsDelivTypes[$crmCode]){ if ($arDeliveryService['ID'] == $optionsDelivTypes[$crmCode]) {
$dCode = $arDeliveryService['CODE'] . ':' . $crmService; $dCode = $arDeliveryService['CODE'] . ':' . $crmService;
} }
} }
//будем менять доставку на этот id //будем менять доставку на этот id
if($crmService && $arDeliveryCode[$dCode]){ if ($crmService && $arDeliveryCode[$dCode]) {
$nowDelivery = $arDeliveryCode[$dCode]; $nowDelivery = $arDeliveryCode[$dCode];
} } else {
else{
$nowDelivery = $optionsDelivTypes[$crmCode]; $nowDelivery = $optionsDelivTypes[$crmCode];
} }
//найти текущую доставку в заказе //найти текущую доставку в заказе
$cnt = Bitrix\Sale\Internals\ShipmentTable::getCount(array('ORDER_ID' => $orderCrm['externalId'])); $cnt = Bitrix\Sale\Internals\ShipmentTable::getCount(array('ORDER_ID' => $orderCrm['externalId']));
if($cnt > 0){//обновляем if ($cnt > 0) {//обновляем
$obDeliverys = \Bitrix\Sale\Shipment::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']), $obDeliverys = \Bitrix\Sale\Shipment::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']),
'order' => array('ID'))); 'order' => array('ID')));
while($arDelivery = $obDeliverys->fetch()){ while ($arDelivery = $obDeliverys->fetch()) {
if($arDelivery['DELIVERY_ID'] != $nowDelivery){ if ($arDelivery['DELIVERY_ID'] != $nowDelivery) {
\Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery)); \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery));
\Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $nowDelivery, 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME'])); \Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $nowDelivery, 'DELIVERY_NAME' => $arDeliveryID[$nowDelivery]['NAME']));
} }
} }
} } else {//создаем
else{//создаем
\Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery)); \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $nowDelivery));
$shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array( $shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array(
'ORDER_ID' => $orderCrm['externalId'], 'ORDER_ID' => $orderCrm['externalId'],
@ -965,19 +947,18 @@ class RetailCrmHistory
'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime() 'DATE_INSERT'=> new \Bitrix\Main\Type\DateTime()
)); ));
} }
} } else {
else{
//ищем у заказа на сайте доставки и удаляем/заменяем на без доставки //ищем у заказа на сайте доставки и удаляем/заменяем на без доставки
$noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
\Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $noOrderId)); \Bitrix\Sale\OrderTable::update($orderCrm['externalId'], array('DELIVERY_ID' => $noOrderId));
$obDeliverys = Bitrix\Sale\Shipment::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']), $obDeliverys = Bitrix\Sale\Shipment::getList(array('filter' => array('ORDER_ID' => $orderCrm['externalId']),
'order' => array('ID'))); 'order' => array('ID')));
$create = true; $create = true;
while($arDelivery = $obDeliverys->fetch()){ while ($arDelivery = $obDeliverys->fetch()) {
\Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $noOrderId, 'DELIVERY_NAME' => 'Без доставки')); \Bitrix\Sale\Internals\ShipmentTable::update($arDelivery['ID'], array('DELIVERY_ID' => $noOrderId, 'DELIVERY_NAME' => 'Без доставки'));
$create = false; $create = false;
} }
if($create){ if ($create) {
$shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array( $shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable::add(array(
'ORDER_ID' => $orderCrm['externalId'], 'ORDER_ID' => $orderCrm['externalId'],
'STATUS_ID' => 'DN', 'STATUS_ID' => 'DN',
@ -1021,28 +1002,87 @@ class RetailCrmHistory
return true; return true;
} }
public static function paySystemUpdate($order, $optionsPayment){ public static function updateShipmentItem($orderId)
if(isset($order['paymentType'])){ {
if($optionsPayment[$order['paymentType']]){ $orderBasket = \Bitrix\Sale\Internals\BasketTable::getList(array(
'filter' => array('ORDER_ID' => $orderId),
'select' => array('ID', 'QUANTITY')
));
$basketItems = array();
while ($basketItem = $orderBasket->fetch()) {
$basketItems[] = $basketItem;
$bItems[] = $basketItem['ID'];
}
$obShipments = \Bitrix\Sale\Internals\ShipmentTable::getList(array(
'filter' => array('ORDER_ID' => $orderId),
'select' => array('ID')
));
$shipmentItems = array();
while ($arShipment = $obShipments->fetch()) {
$dlvBaslet = \Bitrix\Sale\Internals\ShipmentItemTable::getList(array(
'order' => array('ORDER_DELIVERY_ID'),
'filter' => array('ORDER_DELIVERY_ID' => $arShipment['ID'])
));
$shipmentItems[$arShipment['ID']] = array();
while ($item = $dlvBaslet->fetch()) {
$shipmentItems[$arShipment['ID']][] = $item;
}
}
foreach ($basketItems as $basketItem) {
foreach ($shipmentItems as $key => $arShipmentItems) {
$found = false;
foreach ($arShipmentItems as $elShipmentItem) {
if (!in_array($elShipmentItem['BASKET_ID'], $bItems)) {
//удаляем элемент
\Bitrix\Sale\Internals\ShipmentItemTable::delete($elShipmentItem['ID']);
}
if ($elShipmentItem['BASKET_ID'] == $basketItem['ID']) {
//нашли
$found = true;
//проверяем кол-во, если нужно, обновляем
if ($elShipmentItem['QUANTITY'] != $basketItem['QUANTITY']) {
\Bitrix\Sale\Internals\ShipmentItemTable::update($elShipmentItem['ID'], array('QUANTITY' => $basketItem['QUANTITY']));
}
}
}
if (!$found) {
//добавляем
\Bitrix\Sale\Internals\ShipmentItemTable::add(array(
'ORDER_DELIVERY_ID' => $key,
'BASKET_ID' => $basketItem['ID'],
'DATE_INSERT' => new \Bitrix\Main\Type\DateTime(),
'QUANTITY' => $basketItem['QUANTITY'],
'RESERVED_QUANTITY' => '0.00',
));
}
}
}
}
public static function paySystemUpdate($order, $optionsPayment)
{
if (isset($order['paymentType'])) {
if ($optionsPayment[$order['paymentType']]) {
$paymentList = RCrmActions::PaymentList(); $paymentList = RCrmActions::PaymentList();
$arPayments = array(); $arPayments = array();
$arPaymentsName = array(); $arPaymentsName = array();
foreach($paymentList as $payment){ foreach ($paymentList as $payment) {
$arPayments[] = $payment['ID']; $arPayments[] = $payment['ID'];
$arPaymentsName[$payment['ID']] = $payment['NAME']; $arPaymentsName[$payment['ID']] = $payment['NAME'];
} }
if(in_array($optionsPayment[$order['paymentType']], $arPayments)){ if (in_array($optionsPayment[$order['paymentType']], $arPayments)) {
\Bitrix\Sale\OrderTable::update($order['externalId'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']])); \Bitrix\Sale\OrderTable::update($order['externalId'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']]));
$payment = \Bitrix\Sale\Payment::getList(array( $payment = \Bitrix\Sale\Payment::getList(array(
'filter' => array('ORDER_ID' => $order['externalId']), 'filter' => array('ORDER_ID' => $order['externalId']),
'order' => array('ID') 'order' => array('ID')
))->fetch(); ))->fetch();
if($payment){ if ($payment) {//если уже существует, update
//если уже существует, update
\Bitrix\Sale\Internals\PaymentTable::update($payment['ID'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']], 'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]], 'SUM' => $order['summ'])); \Bitrix\Sale\Internals\PaymentTable::update($payment['ID'], array('PAY_SYSTEM_ID' => $optionsPayment[$order['paymentType']], 'PAY_SYSTEM_NAME' => $arPaymentsName[$optionsPayment[$order['paymentType']]], 'SUM' => $order['summ']));
} } else {
else{
\Bitrix\Sale\Internals\PaymentTable::add(array( \Bitrix\Sale\Internals\PaymentTable::add(array(
'ORDER_ID' => $order['externalId'], 'ORDER_ID' => $order['externalId'],
'PAID' => 'N', 'PAID' => 'N',
@ -1058,46 +1098,42 @@ class RetailCrmHistory
)); ));
} }
//запись в историю //запись в историю
} } else {//ошибка, нет такой активной платежной системы
else{
//ошибка, нет такой активной платежной системы
RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found'); RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found');
} }
} } else {//ошибка, возможно платежная система не сопоставлена
else{
//ошибка, возможно платежная система не сопоставлена
RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in option');; RCrmActions::eventLog('RetailCrmHistory::paySystemUpdate', 'RCrmActions::PaymentList()', 'Error paySystem not found in option');;
} }
} } else {
else{
\Bitrix\Sale\OrderTable::update($order['externalId'], array('PAY_SYSTEM_ID' => '')); \Bitrix\Sale\OrderTable::update($order['externalId'], array('PAY_SYSTEM_ID' => ''));
$payment = \Bitrix\Sale\Payment::getList(array( $payment = \Bitrix\Sale\Payment::getList(array(
'filter' => array('ORDER_ID' => $order['externalId']), 'filter' => array('ORDER_ID' => $order['externalId']),
'order' => array('ID') 'order' => array('ID')
))->fetch(); ))->fetch();
if($payment['ID']){ if ($payment['ID']) {
\Bitrix\Sale\Internals\PaymentTable::delete($payment['ID']); \Bitrix\Sale\Internals\PaymentTable::delete($payment['ID']);
} }
//запись в историю //запись в историю
} }
} }
public static function newValue($value){ public static function newValue($value)
if(isset($value['code'])){ {
if (isset($value['code'])) {
return $value['code']; return $value['code'];
} } else {
else{
return $value; return $value;
} }
} }
public static function removeEmpty($inputArray){ public static function removeEmpty($inputArray)
{
$outputArray = array(); $outputArray = array();
if (!empty($inputArray)){ if (!empty($inputArray)) {
foreach ($inputArray as $key => $element){ foreach ($inputArray as $key => $element) {
if(!empty($element) || $element === 0 || $element === '0'){ if (!empty($element) || $element === 0 || $element === '0') {
if (is_array($element)){ if (is_array($element)) {
$element = self::removeEmpty($element); $element = self::removeEmpty($element);
} }
$outputArray[$key] = $element; $outputArray[$key] = $element;
@ -1108,30 +1144,28 @@ class RetailCrmHistory
return $outputArray; return $outputArray;
} }
public static function setProp($obj, $value, $prop){ public static function setProp($obj, $value, $prop)
if(!isset($obj)){ {
if (!isset($obj)) {
return false; return false;
} }
if($prop && $value){ if ($prop && $value) {
$obj->setField($prop, $value); $obj->setField($prop, $value);
} } elseif ($value) {
elseif($value){
$obj->setValue($value); $obj->setValue($value);
} } else {
else{
$obj->delete(); $obj->delete();
} }
return true; return true;
} }
public static function getExistsItem($basket, $moduleId, $productId){ public static function getExistsItem($basket, $moduleId, $productId)
foreach ($basket as $basketItem) {
{ foreach ($basket as $basketItem) {
$itemExists = ($basketItem->getField('PRODUCT_ID') == $productId && $basketItem->getField('MODULE') == $moduleId); $itemExists = ($basketItem->getField('PRODUCT_ID') == $productId && $basketItem->getField('MODULE') == $moduleId);
if ($itemExists) if ($itemExists) {
{
return $basketItem; return $basketItem;
} }
} }
@ -1139,13 +1173,15 @@ class RetailCrmHistory
return false; return false;
} }
public static function getInfoElement($offerId){ public static function getInfoElement($offerId)
{
$elementInfo = CIBlockElement::GetByID($offerId)->fetch(); $elementInfo = CIBlockElement::GetByID($offerId)->fetch();
$url = CAllIBlock::ReplaceDetailUrl($elementInfo['DETAIL_PAGE_URL'], $elementInfo, false, 'E'); $url = CAllIBlock::ReplaceDetailUrl($elementInfo['DETAIL_PAGE_URL'], $elementInfo, false, 'E');
$info = array( $info = array(
'NAME' => $elementInfo['NAME'], 'NAME' => $elementInfo['NAME'],
'URL' => $url, 'URL' => $url,
); );
return $info; return $info;
} }
} }

View File

@ -49,7 +49,7 @@ class RetailCrmICML
public function Load() public function Load()
{ {
global $USER; global $USER;
if(!isset($_SESSION["SESS_AUTH"]["USER_ID"]) || !$_SESSION["SESS_AUTH"]["USER_ID"]){ if (!isset($_SESSION["SESS_AUTH"]["USER_ID"]) || !$_SESSION["SESS_AUTH"]["USER_ID"]) {
$USER = new CUser; $USER = new CUser;
} }
@ -64,10 +64,9 @@ class RetailCrmICML
$responseBody = curl_exec($curlHandler); $responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); $statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
curl_close($curlHandler); curl_close($curlHandler);
if($statusCode == 200){ if ($statusCode == 200) {
$this->protocol = 'https://'; $this->protocol = 'https://';
} } else {
else{
$this->protocol = 'http://'; $this->protocol = 'http://';
} }
@ -124,6 +123,7 @@ class RetailCrmICML
$newText = $this->application->ConvertCharset($text, $this->encodingDefault, $this->encoding); $newText = $this->application->ConvertCharset($text, $this->encodingDefault, $this->encoding);
$newText = strip_tags($newText); $newText = strip_tags($newText);
$newText = str_replace("&", "&#x26;", $newText); $newText = str_replace("&", "&#x26;", $newText);
return $newText; return $newText;
} }
@ -132,10 +132,11 @@ class RetailCrmICML
$fullFilename = $_SERVER["DOCUMENT_ROOT"] . $filename; $fullFilename = $_SERVER["DOCUMENT_ROOT"] . $filename;
CheckDirPath($fullFilename); CheckDirPath($fullFilename);
if ($fp = @fopen($fullFilename, "w")) if ($fp = @fopen($fullFilename, "w")){
return $fp; return $fp;
else } else {
return false; return false;
}
} }
protected function PreWriteCatalog() protected function PreWriteCatalog()
@ -175,8 +176,9 @@ class RetailCrmICML
protected function WriteLog($text) protected function WriteLog($text)
{ {
if ($this->isLogged) if ($this->isLogged) {
@fwrite($this->fpLog, Date("Y:m:d H:i:s") . ": " . $text . "\n"); @fwrite($this->fpLog, Date("Y:m:d H:i:s") . ": " . $text . "\n");
}
} }
protected function PostWriteCatalog() protected function PostWriteCatalog()
@ -194,8 +196,7 @@ class RetailCrmICML
protected function GetCategories() protected function GetCategories()
{ {
$categories = array(); $categories = array();
foreach ($this->iblocks as $id) foreach ($this->iblocks as $id) {
{
$filter = array("IBLOCK_ID" => $id); $filter = array("IBLOCK_ID" => $id);
$dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter); $dbRes = CIBlockSection::GetList(array("left_margin" => "asc"), $filter);
@ -214,6 +215,7 @@ class RetailCrmICML
$categories[$arRes['ID']] = $arRes; $categories[$arRes['ID']] = $arRes;
} }
} }
return $categories; return $categories;
} }
@ -240,8 +242,7 @@ class RetailCrmICML
1 1
); );
foreach ($this->iblocks as $key => $id) foreach ($this->iblocks as $key => $id) {
{
// Get Info by infoblocks // Get Info by infoblocks
$iblock['IBLOCK_DB'] = CIBlock::GetByID($id)->Fetch(); $iblock['IBLOCK_DB'] = CIBlock::GetByID($id)->Fetch();
$iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id); $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($id);
@ -266,7 +267,7 @@ class RetailCrmICML
} }
} }
$arSelectOffer = Array ( $arSelectOffer = array(
'ID', 'ID',
'ACTIVE', 'ACTIVE',
"NAME", "NAME",
@ -288,7 +289,7 @@ class RetailCrmICML
"IBLOCK_ID" => $id "IBLOCK_ID" => $id
); );
$order = array("id"); $order = array("id");
$arNavStatParams = Array( $arNavStatParams = array(
"iNumPage" => 1, "iNumPage" => 1,
"nPageSize" => $this->pageSize, "nPageSize" => $this->pageSize,
); );
@ -298,8 +299,7 @@ class RetailCrmICML
// Get products on this page // Get products on this page
$elems = array(); $elems = array();
$dbResProductsIds = CIBlockElement::GetList($order, $filter, false, $arNavStatParams, array('ID')); $dbResProductsIds = CIBlockElement::GetList($order, $filter, false, $arNavStatParams, array('ID'));
while($obIds = $dbResProductsIds->Fetch()) while ($obIds = $dbResProductsIds->Fetch()) {
{
$elems[] = $obIds['ID']; $elems[] = $obIds['ID'];
} }
$arfilter = array( $arfilter = array(
@ -312,7 +312,6 @@ class RetailCrmICML
$pictures = array(); $pictures = array();
$products = array(); $products = array();
while ($product = $dbResProducts->GetNext()) { while ($product = $dbResProducts->GetNext()) {
// Compile products to array // Compile products to array
$products[$product['ID']] = $product; $products[$product['ID']] = $product;
$products[$product['ID']]['offers'] = array(); $products[$product['ID']]['offers'] = array();
@ -320,13 +319,11 @@ class RetailCrmICML
$detailPicture = intval($product["DETAIL_PICTURE"]); $detailPicture = intval($product["DETAIL_PICTURE"]);
$previewPicture = intval($product["PREVIEW_PICTURE"]); $previewPicture = intval($product["PREVIEW_PICTURE"]);
if ($detailPicture > 0 || $previewPicture > 0) if ($detailPicture > 0 || $previewPicture > 0) {
{
$picture = $detailPicture; $picture = $detailPicture;
if ($picture <= 0) { if ($picture <= 0) {
$picture = $previewPicture; $picture = $previewPicture;
} }
// Link pictureID and productID // Link pictureID and productID
$pictures[$picture] = $product['ID']; $pictures[$picture] = $product['ID'];
} }
@ -337,9 +334,8 @@ class RetailCrmICML
$pictureIDs = array_keys($pictures); $pictureIDs = array_keys($pictures);
// Get pathes of pictures // Get pathes of pictures
$dbFiles = CFile::GetList(Array(), Array("@ID" => implode(',', $pictureIDs))); $dbFiles = CFile::GetList(array(), array("@ID" => implode(',', $pictureIDs)));
while($file = $dbFiles->GetNext()) { while ($file = $dbFiles->GetNext()) {
// Link picture to product // Link picture to product
$products[$pictures[$file['ID']]]['PICTURE'] = $this->protocol . $products[$pictures[$file['ID']]]['PICTURE'] = $this->protocol .
$this->serverName . $this->serverName .
@ -372,20 +368,17 @@ class RetailCrmICML
$stringOffers = ""; $stringOffers = "";
foreach ($products as $product) { foreach ($products as $product) {
// Get properties of product // Get properties of product
$resPropertiesProduct = Array(); $resPropertiesProduct = Array();
foreach ($this->propertiesProduct[$id] as $key => $propProduct) { foreach ($this->propertiesProduct[$id] as $key => $propProduct) {
$resPropertiesProduct[$key] = ""; $resPropertiesProduct[$key] = "";
if ($propProduct != "") { if ($propProduct != "") {
if (isset($product["PROPERTY_" . $propProduct . "_NAME"])){ if (isset($product["PROPERTY_" . $propProduct . "_NAME"])) {
$resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_NAME"]; $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_NAME"];
} } elseif (isset($product["PROPERTY_" . $propProduct . "_VALUE"])) {
elseif (isset($product["PROPERTY_" . $propProduct . "_VALUE"])){
$resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_VALUE"]; $resPropertiesProduct[$key] = $product["PROPERTY_" . $propProduct . "_VALUE"];
} } elseif (isset($product[$propProduct])) {
elseif (isset($product[$propProduct])){
$resPropertiesProduct[$key] = $product[$propProduct]; $resPropertiesProduct[$key] = $product[$propProduct];
} }
if (array_key_exists($key, $this->propertiesUnitProduct[$id])) { if (array_key_exists($key, $this->propertiesUnitProduct[$id])) {
@ -396,13 +389,13 @@ class RetailCrmICML
} }
// Get categories of product // Get categories of product
$categories = Array(); $categories = array();
$dbResCategories = CIBlockElement::GetElementGroups($product['ID'], true); $dbResCategories = CIBlockElement::GetElementGroups($product['ID'], true);
while ($arResCategory = $dbResCategories->Fetch()) { while ($arResCategory = $dbResCategories->Fetch()) {
$categories[$arResCategory["ID"]] = array( $categories[$arResCategory["ID"]] = array(
'ID' => $arResCategory["ID"], 'ID' => $arResCategory["ID"],
'NAME' => $arResCategory["NAME"], 'NAME' => $arResCategory["NAME"],
); );
} }
if (count($categories) == 0) { if (count($categories) == 0) {
$catId = $this->mainSection + $id; $catId = $this->mainSection + $id;
@ -412,7 +405,6 @@ class RetailCrmICML
$existOffer = false; $existOffer = false;
if (!empty($iblockOffer['IBLOCK_ID'])) { if (!empty($iblockOffer['IBLOCK_ID'])) {
foreach ($product['offers'] as $offer) { foreach ($product['offers'] as $offer) {
$offer['PRODUCT_ID'] = $product["ID"]; $offer['PRODUCT_ID'] = $product["ID"];
$offer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"]; $offer['DETAIL_PAGE_URL'] = $product["DETAIL_PAGE_URL"];
@ -426,13 +418,11 @@ class RetailCrmICML
// Get properties of product // Get properties of product
foreach ($this->propertiesSKU[$id] as $key => $propSKU) { foreach ($this->propertiesSKU[$id] as $key => $propSKU) {
if ($propSKU != "") { if ($propSKU != "") {
if (isset ($offer["PROPERTY_" . $propSKU . "_NAME"])){ if (isset ($offer["PROPERTY_" . $propSKU . "_NAME"])) {
$offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_NAME"]; $offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_NAME"];
} } elseif (isset($offer["PROPERTY_" . $propSKU . "_VALUE"])) {
elseif (isset($offer["PROPERTY_" . $propSKU . "_VALUE"])){
$offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_VALUE"]; $offer['_PROP_' . $key] = $offer["PROPERTY_" . $propSKU . "_VALUE"];
} } elseif (isset($offer[$propSKU])) {
elseif (isset($offer[$propSKU])){
$offer['_PROP_' . $key] = $offer[$propSKU]; $offer['_PROP_' . $key] = $offer[$propSKU];
} }
if (array_key_exists($key, $this->propertiesUnitSKU[$id])) { if (array_key_exists($key, $this->propertiesUnitSKU[$id])) {
@ -443,7 +433,7 @@ class RetailCrmICML
} }
foreach ($resPropertiesProduct as $key => $propProduct) { foreach ($resPropertiesProduct as $key => $propProduct) {
if ($this->propertiesProduct[$id][$key] != "" && !isset($offer[$key])){ if ($this->propertiesProduct[$id][$key] != "" && !isset($offer[$key])) {
$offer['_PROP_' . $key] = $propProduct; $offer['_PROP_' . $key] = $propProduct;
} }
} }
@ -453,7 +443,6 @@ class RetailCrmICML
} }
} }
if (!$existOffer) { if (!$existOffer) {
$product['PRODUCT_ID'] = $product["ID"]; $product['PRODUCT_ID'] = $product["ID"];
$product['PRODUCT_NAME'] = $product["NAME"]; $product['PRODUCT_NAME'] = $product["NAME"];
$product['PRODUCT_ACTIVE'] = $product["ACTIVE"]; $product['PRODUCT_ACTIVE'] = $product["ACTIVE"];
@ -473,7 +462,7 @@ class RetailCrmICML
} }
unset($products); unset($products);
if ($this->isLogged){ if ($this->isLogged) {
$this->WriteLog(($this->pageSize * $arNavStatParams['iNumPage']) . " product(s) has been loaded from " . $id . " IB (memory usage: " . memory_get_usage() . ")"); $this->WriteLog(($this->pageSize * $arNavStatParams['iNumPage']) . " product(s) has been loaded from " . $id . " IB (memory usage: " . memory_get_usage() . ")");
} }
if ($stringOffers != "") { if ($stringOffers != "") {
@ -482,8 +471,7 @@ class RetailCrmICML
} }
$arNavStatParams['iNumPage'] = $dbResProductsIds->NavPageNomer + 1; $arNavStatParams['iNumPage'] = $dbResProductsIds->NavPageNomer + 1;
} } while ($dbResProductsIds->NavPageNomer < $dbResProductsIds->NavPageCount);
while ($dbResProductsIds->NavPageNomer < $dbResProductsIds->NavPageCount);
} }
} }
@ -494,23 +482,23 @@ class RetailCrmICML
"productId=\"" . $this->PrepareValue($arOffer["PRODUCT_ID"]) . "\" ". "productId=\"" . $this->PrepareValue($arOffer["PRODUCT_ID"]) . "\" ".
"quantity=\"" . $this->PrepareValue(DoubleVal($arOffer['QUANTITY'])) . "\">\n"; "quantity=\"" . $this->PrepareValue(DoubleVal($arOffer['QUANTITY'])) . "\">\n";
if ($arOffer['PRODUCT_ACTIVE'] == "N"){ if ($arOffer['PRODUCT_ACTIVE'] == "N") {
$offer .= "<productActivity>" . $this->PrepareValue($arOffer['PRODUCT_ACTIVE']) . "</productActivity>\n"; $offer .= "<productActivity>" . $this->PrepareValue($arOffer['PRODUCT_ACTIVE']) . "</productActivity>\n";
} }
$keys = array_keys($categories); $keys = array_keys($categories);
if (strpos($arOffer['DETAIL_PAGE_URL'], "#SECTION_PATH#") !== false) { if (strpos($arOffer['DETAIL_PAGE_URL'], "#SECTION_PATH#") !== false) {
if (count($categories) != 0) { if (count($categories) != 0) {
$category = $allCategories[$keys[0]]; $category = $allCategories[$keys[0]];
$path = $category['CODE']; $path = $category['CODE'];
if(intval($category["IBLOCK_SECTION_ID"] ) != 0) { if (intval($category["IBLOCK_SECTION_ID"] ) != 0) {
while (true) { while (true) {
$category = $allCategories[$category['IBLOCK_SECTION_ID']]; $category = $allCategories[$category['IBLOCK_SECTION_ID']];
$path = $category['CODE'] . '/' . $path; $path = $category['CODE'] . '/' . $path;
if(intval($category["IBLOCK_SECTION_ID"] ) == 0) if(intval($category["IBLOCK_SECTION_ID"]) == 0){
break; break;
}
} }
} }
@ -525,7 +513,7 @@ class RetailCrmICML
if ($arOffer['PURCHASE_PRICE'] && $this->loadPurchasePrice) { if ($arOffer['PURCHASE_PRICE'] && $this->loadPurchasePrice) {
$offer .= "<purchasePrice>" . $this->PrepareValue($arOffer['PURCHASE_PRICE']) . "</purchasePrice>\n"; $offer .= "<purchasePrice>" . $this->PrepareValue($arOffer['PURCHASE_PRICE']) . "</purchasePrice>\n";
} }
foreach ($categories as $category){ foreach ($categories as $category) {
$offer .= "<categoryId>" . $category['ID'] . "</categoryId>\n"; $offer .= "<categoryId>" . $category['ID'] . "</categoryId>\n";
} }
@ -536,26 +524,25 @@ class RetailCrmICML
foreach ($this->propertiesProduct[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { foreach ($this->propertiesProduct[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) {
if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) { if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) {
if ($key === "manufacturer"){ if ($key === "manufacturer") {
$offer .= "<vendor>" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</vendor>\n"; $offer .= "<vendor>" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</vendor>\n";
} } else {
else{
$offer .= '<param name="' . $key . '"' . (isset($arOffer['_PROP_' . $key . "_UNIT"]) ? ' unit="' . $arOffer['_PROP_' . $key . "_UNIT"] . '"' : "") . ">" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</param>\n"; $offer .= '<param name="' . $key . '"' . (isset($arOffer['_PROP_' . $key . "_UNIT"]) ? ' unit="' . $arOffer['_PROP_' . $key . "_UNIT"] . '"' : "") . ">" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</param>\n";
} }
} }
} }
foreach ($this->propertiesSKU[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) { foreach ($this->propertiesSKU[$iblock['IBLOCK_DB']['ID']] as $key => $propProduct) {
if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) { if ($propProduct != "" && $arOffer['_PROP_' . $key] != null) {
if ($key === "manufacturer"){ if ($key === "manufacturer") {
$offer .= "<vendor>" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</vendor>\n"; $offer .= "<vendor>" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</vendor>\n";
} } else {
else{
$offer .= '<param name="' . $key . '"' . (isset($arOffer['_PROP_' . $key . "_UNIT"]) ? ' unit="' . $arOffer['_PROP_' . $key . "_UNIT"] . '"' : "") . ">" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</param>\n"; $offer .= '<param name="' . $key . '"' . (isset($arOffer['_PROP_' . $key . "_UNIT"]) ? ' unit="' . $arOffer['_PROP_' . $key . "_UNIT"] . '"' : "") . ">" . $this->PrepareValue($arOffer['_PROP_' . $key]) . "</param>\n";
} }
} }
} }
$offer.= "</offer>\n"; $offer.= "</offer>\n";
return $offer; return $offer;
} }
} }

View File

@ -34,8 +34,9 @@ class RetailCrmOrder
* @return boolean * @return boolean
* @return array - array('order' = $order, 'customer' => $customer) * @return array - array('order' = $order, 'customer' => $customer)
*/ */
public static function orderSend($arFields, $api, $arParams, $send = false, $site = null, $methodApi = 'ordersEdit') { public static function orderSend($arFields, $api, $arParams, $send = false, $site = null, $methodApi = 'ordersEdit')
if(!$api || empty($arParams)) { // add cond to check $arParams {
if (!$api || empty($arParams)) { // add cond to check $arParams
return false; return false;
} }
if (empty($arFields)) { if (empty($arFields)) {
@ -63,13 +64,13 @@ class RetailCrmOrder
'cost' => $arFields['PRICE_DELIVERY'] 'cost' => $arFields['PRICE_DELIVERY']
), ),
); );
if(isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != ''){ if (isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') {
$order['customer']['browserId'] = $_COOKIE['_rc']; $order['customer']['browserId'] = $_COOKIE['_rc'];
} }
$order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']]; $order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arFields['PERSON_TYPE_ID']];
//свойства //свойства
foreach($arFields['PROPS']['properties'] as $prop){ foreach ($arFields['PROPS']['properties'] as $prop) {
if ($search = array_search($prop['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) { if ($search = array_search($prop['CODE'], $arParams['optionsLegalDetails'][$arFields['PERSON_TYPE_ID']])) {
$order['contragent'][$search] = $prop['VALUE'][0];//юр данные заказа $order['contragent'][$search] = $prop['VALUE'][0];//юр данные заказа
} elseif ($search = array_search($prop['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) { } elseif ($search = array_search($prop['CODE'], $arParams['optionsCustomFields'][$arFields['PERSON_TYPE_ID']])) {
@ -105,7 +106,7 @@ class RetailCrmOrder
} }
//корзина //корзина
foreach($arFields['BASKET'] as $product){ foreach ($arFields['BASKET'] as $product) {
$item = array( $item = array(
'quantity' => $product['QUANTITY'], 'quantity' => $product['QUANTITY'],
'offer' => array('externalId' => $product['PRODUCT_ID'], 'offer' => array('externalId' => $product['PRODUCT_ID'],
@ -159,7 +160,8 @@ class RetailCrmOrder
* @param $failed -- flag to export failed orders * @param $failed -- flag to export failed orders
* @return boolean * @return boolean
*/ */
public static function uploadOrders($pSize = 50, $failed = false, $orderList = false) { public static function uploadOrders($pSize = 50, $failed = false, $orderList = false)
{
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
RCrmActions::eventLog('RetailCrmOrder::uploadOrders', 'iblock', 'module not found'); RCrmActions::eventLog('RetailCrmOrder::uploadOrders', 'iblock', 'module not found');
return true; return true;
@ -191,7 +193,7 @@ class RetailCrmOrder
'limit' => $pSize, 'limit' => $pSize,
'select' => array('ID') 'select' => array('ID')
)); ));
while($arOrder = $dbOrder->fetch()){ while ($arOrder = $dbOrder->fetch()) {
$orderIds[] = $arOrder['ID']; $orderIds[] = $arOrder['ID'];
} }
} }
@ -230,9 +232,9 @@ class RetailCrmOrder
); );
$recOrders = array(); $recOrders = array();
foreach($orderIds as $orderId){ foreach ($orderIds as $orderId) {
$id = \Bitrix\Sale\Order::load($orderId); $id = \Bitrix\Sale\Order::load($orderId);
if(!$id){ if (!$id) {
continue; continue;
} }
$order = self::orderObjToArr($id); $order = self::orderObjToArr($id);
@ -243,7 +245,7 @@ class RetailCrmOrder
$arCustomers = RetailCrmUser::customerSend($user, $api, $optionsContragentType[$order['PERSON_TYPE_ID']], false, $site); $arCustomers = RetailCrmUser::customerSend($user, $api, $optionsContragentType[$order['PERSON_TYPE_ID']], false, $site);
$arOrders = self::orderSend($order, $api, $arParams, false, $site); $arOrders = self::orderSend($order, $api, $arParams, false, $site);
if (!$arCustomers || !$arOrders){ if (!$arCustomers || !$arOrders) {
continue; continue;
} }
@ -253,8 +255,8 @@ class RetailCrmOrder
$recOrders[] = $orderId; $recOrders[] = $orderId;
} }
if(count($resOrders) > 0){ if (count($resOrders) > 0) {
foreach($resCustomers as $key => $customerLoad){ foreach ($resCustomers as $key => $customerLoad) {
$site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null;
if (RCrmActions::apiMethod($api, 'customersUpload', __METHOD__, $customerLoad, $site) === false) { if (RCrmActions::apiMethod($api, 'customersUpload', __METHOD__, $customerLoad, $site) === false) {
return false; return false;
@ -263,7 +265,7 @@ class RetailCrmOrder
time_nanosleep(0, 250000000); time_nanosleep(0, 250000000);
} }
} }
foreach($resOrders as $key => $orderLoad){ foreach ($resOrders as $key => $orderLoad) {
$site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null; $site = count($optionsSitesList) > 1 ? $optionsSitesList[$key] : null;
if (RCrmActions::apiMethod($api, 'ordersUpload', __METHOD__, $orderLoad, $site) === false) { if (RCrmActions::apiMethod($api, 'ordersUpload', __METHOD__, $orderLoad, $site) === false) {
return false; return false;
@ -282,7 +284,8 @@ class RetailCrmOrder
return true; return true;
} }
public static function orderObjToArr($obOrder){ public static function orderObjToArr($obOrder)
{
$arOrder = array( $arOrder = array(
'ID' => $obOrder->getId(), 'ID' => $obOrder->getId(),
'NUMBER' => $obOrder->getField('ACCOUNT_NUMBER'), 'NUMBER' => $obOrder->getField('ACCOUNT_NUMBER'),
@ -304,14 +307,13 @@ class RetailCrmOrder
); );
$shipmentList = $obOrder->getShipmentCollection(); $shipmentList = $obOrder->getShipmentCollection();
foreach($shipmentList as $shipmentData){ foreach ($shipmentList as $shipmentData) {
if($shipmentData->getDeliveryId()){ if ($shipmentData->getDeliveryId()) {
$delivery = \Bitrix\Sale\Delivery\Services\Manager::getById($shipmentData->getDeliveryId()); $delivery = \Bitrix\Sale\Delivery\Services\Manager::getById($shipmentData->getDeliveryId());
if($delivery['PARENT_ID']){ if ($delivery['PARENT_ID']) {
$servise = explode(':', $delivery['CODE']); $servise = explode(':', $delivery['CODE']);
$shipment = array('id' => $delivery['PARENT_ID'], 'service' => $servise[1]); $shipment = array('id' => $delivery['PARENT_ID'], 'service' => $servise[1]);
} } else {
else{
$shipment = array('id' => $delivery['ID']); $shipment = array('id' => $delivery['ID']);
} }
$arOrder['DELIVERYS'][] = $shipment; $arOrder['DELIVERYS'][] = $shipment;
@ -319,7 +321,7 @@ class RetailCrmOrder
} }
$basketItems = $obOrder->getBasket(); $basketItems = $obOrder->getBasket();
foreach($basketItems as $item){ foreach ($basketItems as $item) {
$arOrder['BASKET'][] = $item->getFields(); $arOrder['BASKET'][] = $item->getFields();
} }

View File

@ -2,8 +2,9 @@
IncludeModuleLangFile(__FILE__); IncludeModuleLangFile(__FILE__);
class RetailCrmUser class RetailCrmUser
{ {
public static function customerSend($arFields, $api, $contragentType, $send = false, $site = null){//только на создание public static function customerSend($arFields, $api, $contragentType, $send = false, $site = null)
if(!$api || empty($contragentType)) { // add cond to check $arParams {
if (!$api || empty($contragentType)) { // add cond to check $arParams
return false; return false;
} }
if (empty($arFields)) { if (empty($arFields)) {
@ -19,13 +20,13 @@ class RetailCrmUser
'createdAt' => new \DateTime($arFields['DATE_REGISTER']), 'createdAt' => new \DateTime($arFields['DATE_REGISTER']),
'contragentType' => $contragentType 'contragentType' => $contragentType
); );
if(isset($arFields['PERSONAL_PHONE'])){ if (isset($arFields['PERSONAL_PHONE'])) {
$customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE'];
} }
if(isset($arUser['WORK_PHONE'])){ if (isset($arUser['WORK_PHONE'])) {
$customer['phones'][]['number'] = $arFields['WORK_PHONE']; $customer['phones'][]['number'] = $arFields['WORK_PHONE'];
} }
if(isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != ''){ if (isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') {
$customer['browserId'] = $_COOKIE['_rc']; $customer['browserId'] = $_COOKIE['_rc'];
} }
@ -42,7 +43,7 @@ class RetailCrmUser
$log = new Logger(); $log = new Logger();
$log->write($customer, 'customer'); $log->write($customer, 'customer');
if($send) { if ($send) {
if (!RCrmActions::apiMethod($api, 'customersCreate', __METHOD__, $customer, $site)) { if (!RCrmActions::apiMethod($api, 'customersCreate', __METHOD__, $customer, $site)) {
return false; return false;
} }
@ -64,32 +65,31 @@ class RetailCrmUser
'patronymic' => $arFields['SECOND_NAME'], 'patronymic' => $arFields['SECOND_NAME'],
'email' => $arFields['EMAIL'] 'email' => $arFields['EMAIL']
); );
if(isset($arFields['PERSONAL_PHONE'])){ if (isset($arFields['PERSONAL_PHONE'])) {
$customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE'];
} }
if(isset($arFields['WORK_PHONE'])){ if (isset($arFields['WORK_PHONE'])) {
$customer['phones'][]['number'] = $arFields['WORK_PHONE']; $customer['phones'][]['number'] = $arFields['WORK_PHONE'];
} }
$found = false; $found = false;
if(count($optionsSitesList)>1){ if (count($optionsSitesList) > 1) {
foreach($optionsSitesList as $site){ foreach ($optionsSitesList as $site) {
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site); $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site);
if(isset($userCrm['customer'])){ if (isset($userCrm['customer'])) {
$found = true; $found = true;
break; break;
} }
} }
} } else {
else{
$site = null; $site = null;
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site); $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site);
if(isset($userCrm['customer'])){ if (isset($userCrm['customer'])) {
$found = true; $found = true;
} }
} }
if($found){ if ($found) {
$normalizer = new RestNormalizer(); $normalizer = new RestNormalizer();
$customer = $normalizer->normalize($customer, 'customers'); $customer = $normalizer->normalize($customer, 'customers');

View File

@ -1,2 +1 @@
- Переход на новое API Битрикса - fix состава отгрузки
- Переход на API црм v4

View File

@ -1,40 +1,41 @@
<?php <?php
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_run.php")){ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_run.php")){
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_run.php"); require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_run.php");
} } else {
else{
ignore_user_abort(true); ignore_user_abort(true);
set_time_limit(0); set_time_limit(0);
global $APPLICATION; global $APPLICATION;
if (!CModule::IncludeModule("iblock")) if (!CModule::IncludeModule("iblock")){
return; return;
if (!CModule::IncludeModule("catalog")) }
if (!CModule::IncludeModule("catalog")){
return; return;
if (!CModule::IncludeModule("intaro.retailcrm")) }
if (!CModule::IncludeModule("intaro.retailcrm")){
return; return;
}
$rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y')); $rsSites = CSite::GetList($by, $sort, array('ACTIVE' => 'Y'));
while ($ar = $rsSites->Fetch()){ while ($ar = $rsSites->Fetch()) {
if($ar['DEF'] == 'Y'){ if ($ar['DEF'] == 'Y') {
$SERVER_NAME = $ar['SERVER_NAME']; $SERVER_NAME = $ar['SERVER_NAME'];
} }
} }
$iblockProperties = Array( $iblockProperties = array(
"article" => "article", "article" => "article",
"manufacturer" => "manufacturer", "manufacturer" => "manufacturer",
"color" =>"color", "color" =>"color",
"weight" => "weight", "weight" => "weight",
"size" => "size", "size" => "size",
"length" => "length", "length" => "length",
"width" => "width", "width" => "width",
"height" => "height", "height" => "height",
); );
$IBLOCK_PROPERTY_SKU = array(); $IBLOCK_PROPERTY_SKU = array();
$IBLOCK_PROPERTY_UNIT_SKU = array(); $IBLOCK_PROPERTY_UNIT_SKU = array();
foreach ($iblockProperties as $prop) { foreach ($iblockProperties as $prop) {
$skuUnitProps = ('IBLOCK_PROPERTY_UNIT_SKU' . "_" . $prop); $skuUnitProps = ('IBLOCK_PROPERTY_UNIT_SKU' . "_" . $prop);
$skuUnitProps = $$skuUnitProps; $skuUnitProps = $$skuUnitProps;
if (is_array($skuUnitProps)) { if (is_array($skuUnitProps)) {
@ -54,7 +55,6 @@ else{
$IBLOCK_PROPERTY_PRODUCT = array(); $IBLOCK_PROPERTY_PRODUCT = array();
$IBLOCK_PROPERTY_UNIT_PRODUCT = array(); $IBLOCK_PROPERTY_UNIT_PRODUCT = array();
foreach ($iblockProperties as $prop) { foreach ($iblockProperties as $prop) {
$productUnitProps = "IBLOCK_PROPERTY_UNIT_PRODUCT" . "_" . $prop; $productUnitProps = "IBLOCK_PROPERTY_UNIT_PRODUCT" . "_" . $prop;
$productUnitProps = $$productUnitProps; $productUnitProps = $$productUnitProps;
if (is_array($productUnitProps)) { if (is_array($productUnitProps)) {

View File

@ -1,22 +1,23 @@
<? <?
if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_setup.php")){ if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_setup.php")){
require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_setup.php"); require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/php_interface/retailcrm/export_setup.php");
} } else {
else{ $iblockProperties = array(
$iblockProperties = Array( "article" => "article",
"article" => "article", "manufacturer" => "manufacturer",
"manufacturer" => "manufacturer", "color" =>"color",
"color" =>"color", "size" => "size",
"size" => "size", "weight" => "weight",
"weight" => "weight", "length" => "length",
"length" => "length", "width" => "width",
"width" => "width", "height" => "height",
"height" => "height", );
);
if(!check_bitrix_sessid()) return; if(!check_bitrix_sessid()) {
return;
}
__IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.retailcrm/lang/", "/icml_export_setup.php")); __IncludeLang(GetLangFileName($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/intaro.retailcrm/lang/", "/icml_export_setup.php"));
$MODULE_ID = 'intaro.retailcrm'; $MODULE_ID = 'intaro.retailcrm';
$CRM_CATALOG_BASE_PRICE = 'catalog_base_price'; $CRM_CATALOG_BASE_PRICE = 'catalog_base_price';
@ -33,7 +34,6 @@ else{
if (($ACTION == 'EXPORT' || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && $STEP == 1) if (($ACTION == 'EXPORT' || $ACTION == 'EXPORT_EDIT' || $ACTION == 'EXPORT_COPY') && $STEP == 1)
{ {
if (isset($arOldSetupVars['SETUP_FILE_NAME'])) if (isset($arOldSetupVars['SETUP_FILE_NAME']))
$SETUP_FILE_NAME = $arOldSetupVars['SETUP_FILE_NAME']; $SETUP_FILE_NAME = $arOldSetupVars['SETUP_FILE_NAME'];
if (isset($arOldSetupVars['LOAD_PURCHASE_PRICE'])) if (isset($arOldSetupVars['LOAD_PURCHASE_PRICE']))

View File

@ -1,3 +1,3 @@
<? <?
//<title>retailCRM</title> //<title>retailCRM</title>
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.retailcrm/export/export_run.php"); require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/intaro.retailcrm/export/export_run.php");

View File

@ -1,3 +1,3 @@
<? <?
//<title>retailCRM</title> //<title>retailCRM</title>
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/intaro.retailcrm/export/export_setup.php"); require($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/intaro.retailcrm/export/export_setup.php");

View File

@ -10,8 +10,8 @@ IncludeModuleLangFile(__FILE__);
if (class_exists('intaro_retailcrm')) if (class_exists('intaro_retailcrm'))
return; return;
class intaro_retailcrm extends CModule { class intaro_retailcrm extends CModule
{
var $MODULE_ID = 'intaro.retailcrm'; var $MODULE_ID = 'intaro.retailcrm';
var $OLD_MODULE_ID = 'intaro.intarocrm'; var $OLD_MODULE_ID = 'intaro.intarocrm';
var $MODULE_VERSION; var $MODULE_VERSION;
@ -49,7 +49,8 @@ class intaro_retailcrm extends CModule {
var $CRM_CANSEL_ORDER = 'cansel_order'; var $CRM_CANSEL_ORDER = 'cansel_order';
var $INSTALL_PATH; var $INSTALL_PATH;
function intaro_retailcrm() { function intaro_retailcrm()
{
$arModuleVersion = array(); $arModuleVersion = array();
$path = str_replace("\\", "/", __FILE__); $path = str_replace("\\", "/", __FILE__);
$path = substr($path, 0, strlen($path) - strlen("/index.php")); $path = substr($path, 0, strlen($path) - strlen("/index.php"));
@ -67,7 +68,8 @@ class intaro_retailcrm extends CModule {
* Functions DoInstall and DoUninstall are * Functions DoInstall and DoUninstall are
* All other functions are optional * All other functions are optional
*/ */
function DoInstall() { function DoInstall()
{
global $APPLICATION, $step, $arResult; global $APPLICATION, $step, $arResult;
if (!in_array('curl', get_loaded_extensions())) { if (!in_array('curl', get_loaded_extensions())) {
@ -78,12 +80,14 @@ class intaro_retailcrm extends CModule {
$infoSale = CModule::CreateModuleObject('sale')->MODULE_VERSION; $infoSale = CModule::CreateModuleObject('sale')->MODULE_VERSION;
if (version_compare($infoSale, '16', '<=')) { if (version_compare($infoSale, '16', '<=')) {
$APPLICATION->ThrowException(GetMessage("SALE_VERSION_ERR")); $APPLICATION->ThrowException(GetMessage("SALE_VERSION_ERR"));
return false; return false;
} }
if (!date_default_timezone_get()) { if (!date_default_timezone_get()) {
if (!ini_get('date.timezone')) { if (!ini_get('date.timezone')) {
$APPLICATION->ThrowException(GetMessage("DATE_TIMEZONE_ERR")); $APPLICATION->ThrowException(GetMessage("DATE_TIMEZONE_ERR"));
return false; return false;
} }
} }
@ -107,25 +111,23 @@ class intaro_retailcrm extends CModule {
if (file_exists($this->INSTALL_PATH . '/../classes/general/config/options.xml')) { if (file_exists($this->INSTALL_PATH . '/../classes/general/config/options.xml')) {
$options = simplexml_load_file($this->INSTALL_PATH . '/../classes/general/config/options.xml'); $options = simplexml_load_file($this->INSTALL_PATH . '/../classes/general/config/options.xml');
foreach($options->contragents->contragent as $contragent) foreach ($options->contragents->contragent as $contragent) {
{
$type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET); $type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$contragent["id"]; $type["ID"] = (string)$contragent["id"];
$arResult['contragentType'][] = $type; $arResult['contragentType'][] = $type;
unset ($type); unset ($type);
} }
foreach($options->fields->field as $field) foreach($options->fields->field as $field) {
{
$type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET); $type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$field["id"]; $type["ID"] = (string)$field["id"];
if ($field["group"] == 'custom') { if ($field["group"] == 'custom') {
$arResult['customFields'][] = $type; $arResult['customFields'][] = $type;
} elseif(!$field["group"]){ } elseif (!$field["group"]) {
$arResult['orderProps'][] = $type; $arResult['orderProps'][] = $type;
} else{ } else {
$groups = explode(",", (string)$field["group"]); $groups = explode(",", (string)$field["group"]);
foreach($groups as $group){ foreach ($groups as $group) {
$type["GROUP"][] = trim($group); $type["GROUP"][] = trim($group);
} }
$arResult['legalDetails'][] = $type; $arResult['legalDetails'][] = $type;
@ -134,9 +136,9 @@ class intaro_retailcrm extends CModule {
} }
} }
if($step == 11){ if ($step == 11) {
$arResult['arSites'] = RCrmActions::SitesList(); $arResult['arSites'] = RCrmActions::SitesList();
if(count($arResult['arSites'])<2){ if (count($arResult['arSites']) < 2) {
$step = 2; $step = 2;
} }
} }
@ -153,17 +155,17 @@ class intaro_retailcrm extends CModule {
$arResult['errCode'] = 'ERR_CATALOG'; $arResult['errCode'] = 'ERR_CATALOG';
} }
if($api_host = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_API_HOST_OPTION, 0)){ if ($api_host = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_API_HOST_OPTION, 0)) {
$arResult['API_HOST'] = $api_host; $arResult['API_HOST'] = $api_host;
} }
if($api_key = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_API_KEY_OPTION, 0)){ if ($api_key = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_API_KEY_OPTION, 0)) {
$arResult['API_KEY'] = $api_key; $arResult['API_KEY'] = $api_key;
} }
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
); );
} else if ($step == 11) { } elseif ($step == 11) {
//new page //new page
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE'; $arResult['errCode'] = 'ERR_SALE';
@ -190,7 +192,9 @@ class intaro_retailcrm extends CModule {
// 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';
}
$api_host = $api_host['scheme'] . '://' . $api_host['host']; $api_host = $api_host['scheme'] . '://' . $api_host['host'];
if (!$api_host || !$api_key) { if (!$api_host || !$api_key) {
@ -224,7 +228,7 @@ class intaro_retailcrm extends CModule {
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);
if($sites_list = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_SITES_LIST, 0)){ if ($sites_list = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_SITES_LIST, 0)) {
$arResult['SITES_LIST'] = unserialize($sites_list); $arResult['SITES_LIST'] = unserialize($sites_list);
} }
@ -232,15 +236,12 @@ class intaro_retailcrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php'
); );
} else if ($step == 2) {//доставки, оплаты, типы заказов } else if ($step == 2) {//доставки, оплаты, типы заказов
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE'; $arResult['errCode'] = 'ERR_SALE';
} }
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK'; $arResult['errCode'] = 'ERR_IBLOCK';
} }
if (!CModule::IncludeModule("catalog")) { if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG'; $arResult['errCode'] = 'ERR_CATALOG';
} }
@ -249,6 +250,7 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
); );
return; return;
} }
@ -535,13 +537,13 @@ class intaro_retailcrm extends CModule {
die(json_encode(array("success" => true, "result" => $input))); die(json_encode(array("success" => true, "result" => $input)));
}*/ }*/
if(count($arResult['arSites'])>1){ if (count($arResult['arSites']) > 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);
foreach($arResult['arSites'] as $site){ foreach ($arResult['arSites'] as $site) {
if($_POST['sites-id-'.$site['LID']] && !empty($_POST['sites-id-'.$site['LID']])){ if ($_POST['sites-id-'.$site['LID']] && !empty($_POST['sites-id-'.$site['LID']])) {
$siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-'.$site['LID']])); $siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-'.$site['LID']]));
} }
} }
@ -555,14 +557,15 @@ class intaro_retailcrm extends CModule {
$this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key); $this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key);
COption::SetOptionString($this->MODULE_ID, $this->CRM_SITES_LIST, serialize($siteCode)); COption::SetOptionString($this->MODULE_ID, $this->CRM_SITES_LIST, serialize($siteCode));
} } else {//если 1 сайт
else{//если 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]));
// 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';
}
$api_host = $api_host['scheme'] . '://' . $api_host['host']; $api_host = $api_host['scheme'] . '://' . $api_host['host'];
if (!$api_host || !$api_key) { if (!$api_host || !$api_key) {
@ -623,28 +626,28 @@ class intaro_retailcrm extends CModule {
//bitrix statusesList --statuses //bitrix statusesList --statuses
$arResult['bitrixStatusesList'] = RCrmActions::StatusesList(); $arResult['bitrixStatusesList'] = RCrmActions::StatusesList();
if($order_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_TYPES_ARR, 0)){ if ($order_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_TYPES_ARR, 0)) {
$arResult['ORDER_TYPES'] = array_flip(unserialize($order_types)); $arResult['ORDER_TYPES'] = array_flip(unserialize($order_types));
} }
if($delivery_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, 0)){ if ($delivery_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_DELIVERY_TYPES_ARR, 0)) {
$arResult['DELIVERY_TYPES'] = array_flip(unserialize($delivery_types)); $arResult['DELIVERY_TYPES'] = array_flip(unserialize($delivery_types));
} }
if($payment_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT_TYPES, 0)){ if ($payment_types = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT_TYPES, 0)) {
$arResult['PAYMENT_TYPES'] = array_flip(unserialize($payment_types)); $arResult['PAYMENT_TYPES'] = array_flip(unserialize($payment_types));
} }
if($payment_statuses = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT_STATUSES, 0)){ if ($payment_statuses = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT_STATUSES, 0)) {
$arResult['PAYMENT_STATUSES'] = array_flip(unserialize($payment_statuses)); $arResult['PAYMENT_STATUSES'] = array_flip(unserialize($payment_statuses));
} }
if($payment = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT, 0)){ if ($payment = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_PAYMENT, 0)) {
$arResult['PAYMENT'] = array_flip(unserialize($payment)); $arResult['PAYMENT'] = array_flip(unserialize($payment));
} }
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step2.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step2.php'
); );
} else if ($step == 3) {//сопостовление свойств заказа } elseif ($step == 3) {//сопостовление свойств заказа
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
//handler $arResult['errCode'] = 'ERR_SALE';
} }
if (isset($_POST['back']) && $_POST['back']) { if (isset($_POST['back']) && $_POST['back']) {
@ -663,7 +666,7 @@ class intaro_retailcrm extends CModule {
$arResult['bitrixOrderTypesList'] = RCrmActions::OrderTypesList($arResult['arSites']); $arResult['bitrixOrderTypesList'] = RCrmActions::OrderTypesList($arResult['arSites']);
$orderTypesArr = array(); $orderTypesArr = array();
foreach($arResult['bitrixOrderTypesList'] as $orderType){ foreach ($arResult['bitrixOrderTypesList'] as $orderType) {
$orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']])); $orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']]));
} }
@ -672,13 +675,12 @@ class intaro_retailcrm extends CModule {
if (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'false') {//сами настраиваем доставки if (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'false') {//сами настраиваем доставки
$deliveryTypesArr = array(); $deliveryTypesArr = array();
foreach($arResult['bitrixDeliveryTypesList'] as $delivery){ foreach ($arResult['bitrixDeliveryTypesList'] as $delivery) {
$deliveryTypesArr[$delivery['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $delivery['ID']])); $deliveryTypesArr[$delivery['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $delivery['ID']]));
} }
} } elseif (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'true') {//отправка доставок в црм
elseif (htmlspecialchars(trim($_POST['delivery-types-export'])) == 'true') {//отправка доставок в црм
// send to intaro crm and save delivery types! // send to intaro crm and save delivery types!
foreach($optionsDelivTypes as $deliveryType){ foreach ($optionsDelivTypes as $deliveryType) {
$load = true; $load = true;
try { try {
$this->RETAIL_CRM_API->deliveryTypesEdit(RCrmActions::clearArr(array( $this->RETAIL_CRM_API->deliveryTypesEdit(RCrmActions::clearArr(array(
@ -695,11 +697,11 @@ class intaro_retailcrm extends CModule {
$e->getCode() . ': ' . $e->getMessage() $e->getCode() . ': ' . $e->getMessage()
); );
} }
if($load){ if ($load) {
foreach($optionsDelivTypes as $deliveryService){ foreach ($optionsDelivTypes as $deliveryService) {
if($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $deliveryType['ID']){ if ($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $deliveryType['ID']) {
$srv = explode(':', $deliveryService['CODE']); $srv = explode(':', $deliveryService['CODE']);
if(count($srv) == 2){ if (count($srv) == 2) {
try { try {
$this->RETAIL_CRM_API->deliveryServicesEdit(RCrmActions::clearArr(array( $this->RETAIL_CRM_API->deliveryServicesEdit(RCrmActions::clearArr(array(
'code' => $srv[1], 'code' => $srv[1],
@ -723,7 +725,7 @@ class intaro_retailcrm extends CModule {
$arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList(); $arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList();
$paymentTypesArr = array(); $paymentTypesArr = array();
foreach($arResult['bitrixPaymentTypesList'] as $payment){ foreach ($arResult['bitrixPaymentTypesList'] as $payment) {
$paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']])); $paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']]));
} }
@ -733,9 +735,9 @@ class intaro_retailcrm extends CModule {
$paymentStatusesArr = array(); $paymentStatusesArr = array();
$canselOrderArr = array(); $canselOrderArr = array();
foreach($arResult['bitrixStatusesList'] as $status){ foreach ($arResult['bitrixStatusesList'] as $status) {
$paymentStatusesArr[$status['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $status['ID']])); $paymentStatusesArr[$status['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $status['ID']]));
if(trim($_POST['order-cansel-' . $status['ID']]) == 'Y'){ if (trim($_POST['order-cansel-' . $status['ID']]) == 'Y') {
$canselOrderArr[] = $status['ID']; $canselOrderArr[] = $status['ID'];
} }
} }
@ -759,25 +761,25 @@ class intaro_retailcrm extends CModule {
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, serialize(array())); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, serialize(array()));
COption::SetOptionString($this->MODULE_ID, $this->CRM_CANSEL_ORDER, serialize(RCrmActions::clearArr($canselOrderArr))); COption::SetOptionString($this->MODULE_ID, $this->CRM_CANSEL_ORDER, serialize(RCrmActions::clearArr($canselOrderArr)));
if($orderProps = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_PROPS, 0)){ if ($orderProps = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_PROPS, 0)) {
$arResult['ORDER_PROPS'] = unserialize($orderProps); $arResult['ORDER_PROPS'] = unserialize($orderProps);
} }
if($customFields = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_CUSTOM_FIELDS, 0)){ if ($customFields = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_CUSTOM_FIELDS, 0)) {
$arResult['CUSTOM_FIELDS'] = unserialize($customFields); $arResult['CUSTOM_FIELDS'] = unserialize($customFields);
} }
if($legalDetails = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_LEGAL_DETAILS, 0)){ if ($legalDetails = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_LEGAL_DETAILS, 0)) {
$arResult['LEGAL_DETAILS'] = unserialize($legalDetails); $arResult['LEGAL_DETAILS'] = unserialize($legalDetails);
} }
if($contragentType = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_CONTRAGENT_TYPE, 0)){ if ($contragentType = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_CONTRAGENT_TYPE, 0)) {
$arResult['CONTRAGENT_TYPES'] = unserialize($contragentType); $arResult['CONTRAGENT_TYPES'] = unserialize($contragentType);
} }
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step3.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step3.php'
); );
} else if ($step == 4) {//выгрузка старых заказов } elseif ($step == 4) {//выгрузка старых заказов
if (!CModule::IncludeModule("sale")) { if (!CModule::IncludeModule("sale")) {
//handler $arResult['errCode'] = 'ERR_SALE';
} }
if (isset($_POST['back']) && $_POST['back']) { if (isset($_POST['back']) && $_POST['back']) {
@ -794,15 +796,14 @@ class intaro_retailcrm extends CModule {
$countLeft = (int) \Bitrix\Sale\Internals\OrderTable::getCount(array('>ID' => $lastUpOrderId)); $countLeft = (int) \Bitrix\Sale\Internals\OrderTable::getCount(array('>ID' => $lastUpOrderId));
$countAll = (int) \Bitrix\Sale\Internals\OrderTable::getCount(); $countAll = (int) \Bitrix\Sale\Internals\OrderTable::getCount();
if (!isset($_POST['finish'])){ if (!isset($_POST['finish'])) {
$finish = 0; $finish = 0;
} } else {
else{
$finish = (int) $_POST['finish']; $finish = (int) $_POST['finish'];
} }
$percent = round(100 - ($countLeft * 100 / $countAll), 1); $percent = round(100 - ($countLeft * 100 / $countAll), 1);
if (!$countLeft){ if (!$countLeft) {
$finish = 1; $finish = 1;
} }
$APPLICATION->RestartBuffer(); $APPLICATION->RestartBuffer();
@ -820,7 +821,7 @@ class intaro_retailcrm extends CModule {
$orderTypesList = RCrmActions::OrderTypesList(RCrmActions::SitesList()); $orderTypesList = RCrmActions::OrderTypesList(RCrmActions::SitesList());
$orderTypesArr = array(); $orderTypesArr = array();
foreach($orderTypesList as $orderType){ foreach ($orderTypesList as $orderType) {
$orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']])); $orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']]));
} }
@ -829,8 +830,9 @@ class intaro_retailcrm extends CModule {
$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++;
} }
@ -871,14 +873,14 @@ class intaro_retailcrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step4.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step4.php'
); );
} else if ($step == 5) {//экспорт каталога } elseif ($step == 5) {//экспорт каталога
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK'; $arResult['errCode'] = 'ERR_IBLOCK';
} }
if (!CModule::IncludeModule("catalog")) { if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG'; $arResult['errCode'] = 'ERR_CATALOG';
} }
$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);
$api = new \RetailCrm\ApiClient($api_host, $api_key); $api = new \RetailCrm\ApiClient($api_host, $api_key);
@ -886,7 +888,7 @@ class intaro_retailcrm extends CModule {
$customerH = self::historyLoad($api, 'customersHistory'); $customerH = self::historyLoad($api, 'customersHistory');
COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY, $customerH); COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY, $customerH);
//если есть старое значение, переделываем его на новый лад, иначе вычисляем //если есть старое значение, переделываем его на новый лад, иначе вычисляем
if($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)){ if ($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)) {
try { try {
$history = $api->ordersHistory(array('startDate' => $historyDate)); $history = $api->ordersHistory(array('startDate' => $historyDate));
} catch (\RetailCrm\Exception\CurlException $e) { } catch (\RetailCrm\Exception\CurlException $e) {
@ -902,23 +904,22 @@ class intaro_retailcrm extends CModule {
); );
} }
if(isset($history['history'])){ if (isset($history['history'])) {
$hIs = (int)$history['history'][0]['id'] - 1; $hIs = (int)$history['history'][0]['id'] - 1;
$orderH = $hIs; $orderH = $hIs;
} } else {
else{
$orderH = self::historyLoad($api, 'ordersHistory'); $orderH = self::historyLoad($api, 'ordersHistory');
} }
} } else {
else{
$orderH = self::historyLoad($api, 'ordersHistory'); $orderH = self::historyLoad($api, 'ordersHistory');
} }
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY, $orderH); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY, $orderH);
if($orderLastId = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_LAST_ID, 0)){ if ($orderLastId = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_LAST_ID, 0)) {
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, $orderLastId); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, $orderLastId);
} }
if($orderFailedIds = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_FAILED_IDS, 0)){ if ($orderFailedIds = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_FAILED_IDS, 0)) {
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, $orderFailedIds); COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_FAILED_IDS, $orderFailedIds);
} }
@ -935,12 +936,10 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php'
); );
} else if ($step == 6) {//регистрация модуля } elseif ($step == 6) {//регистрация модуля
if (!CModule::IncludeModule("iblock")) { if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK'; $arResult['errCode'] = 'ERR_IBLOCK';
} }
if (!CModule::IncludeModule("catalog")) { if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG'; $arResult['errCode'] = 'ERR_CATALOG';
} }
@ -949,6 +948,7 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php'
); );
return; return;
} }
@ -958,12 +958,13 @@ class intaro_retailcrm extends CModule {
); );
} }
if (!isset($_POST['IBLOCK_EXPORT'])) if (!isset($_POST['IBLOCK_EXPORT'])) {
$arResult['errCode'] = 'ERR_FIELDS_IBLOCK'; $arResult['errCode'] = 'ERR_FIELDS_IBLOCK';
else } else {
$iblocks = $_POST['IBLOCK_EXPORT']; $iblocks = $_POST['IBLOCK_EXPORT'];
}
$iblockProperties = Array( $iblockProperties = array(
"article" => "article", "article" => "article",
"manufacturer" => "manufacturer", "manufacturer" => "manufacturer",
"color" => "color", "color" => "color",
@ -996,30 +997,34 @@ class intaro_retailcrm extends CModule {
} }
} }
if (!isset($_POST['SETUP_FILE_NAME'])) if (!isset($_POST['SETUP_FILE_NAME'])) {
$arResult['errCode'] = 'ERR_FIELDS_FILE'; $arResult['errCode'] = 'ERR_FIELDS_FILE';
else } else {
$filename = $_POST['SETUP_FILE_NAME']; $filename = $_POST['SETUP_FILE_NAME'];
}
if (!isset($_POST['TYPE_LOADING'])) if (!isset($_POST['TYPE_LOADING'])) {
$typeLoading = 0; $typeLoading = 0;
else } else {
$typeLoading = $_POST['TYPE_LOADING']; $typeLoading = $_POST['TYPE_LOADING'];
}
if (!isset($_POST['SETUP_PROFILE_NAME'])) if (!isset($_POST['SETUP_PROFILE_NAME'])) {
$profileName = ""; $profileName = "";
else } else {
$profileName = $_POST['SETUP_PROFILE_NAME']; $profileName = $_POST['SETUP_PROFILE_NAME'];
}
if ($typeLoading != 'none' && $profileName == "") if ($typeLoading != 'none' && $profileName == "") {
$arResult['errCode'] = 'ERR_FIELDS_PROFILE'; $arResult['errCode'] = 'ERR_FIELDS_PROFILE';
}
if ($filename == "")
if ($filename == "") {
$arResult['errCode'] = 'ERR_FIELDS_FILE'; $arResult['errCode'] = 'ERR_FIELDS_FILE';
}
if (isset($arResult['errCode']) && $arResult['errCode']) { if (isset($arResult['errCode']) && $arResult['errCode']) {
$arOldValues = array(
$arOldValues = Array(
'IBLOCK_EXPORT' => $iblocks, 'IBLOCK_EXPORT' => $iblocks,
'IBLOCK_PROPERTY_SKU' => $propertiesSKU, 'IBLOCK_PROPERTY_SKU' => $propertiesSKU,
'IBLOCK_PROPERTY_UNIT_SKU' => $propertiesUnitSKU, 'IBLOCK_PROPERTY_UNIT_SKU' => $propertiesUnitSKU,
@ -1033,21 +1038,14 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile( $APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php' GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php'
); );
return; return;
} }
RegisterModule($this->MODULE_ID); RegisterModule($this->MODULE_ID);
//RegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "RetailCrmEvent", "onSalePayOrder");
//RegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleCancelOrder");
//RegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAccountNumberSet");
//RegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "RetailCrmEvent", "onSendOrderMail");
RegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder"); RegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder");
RegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd"); RegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd");
RegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave"); RegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave");
//RegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "OnSaleBeforeReserveOrder");
//RegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleReserveOrder");
//RegisterModuleDependences("main", "OnAfterUserRegister", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserRegister");
//RegisterModuleDependences("main", "OnAfterUserAdd", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserAdd");
RegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate"); RegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
RegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave"); RegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave");
RegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete"); RegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
@ -1094,10 +1092,10 @@ class intaro_retailcrm extends CModule {
)); ));
if (intval($PROFILE_ID) <= 0) { if (intval($PROFILE_ID) <= 0) {
$arResult['errCode'] = 'ERR_IBLOCK'; $arResult['errCode'] = 'ERR_IBLOCK';
return; return;
} }
if ($typeLoading == 'agent') { if ($typeLoading == 'agent') {
$dateAgent = new DateTime(); $dateAgent = new DateTime();
$intAgent = new DateInterval('PT60S'); // PT60S - 60 sec; $intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
$dateAgent->add($intAgent); $dateAgent->add($intAgent);
@ -1199,7 +1197,8 @@ class intaro_retailcrm extends CModule {
} }
} }
function DoUninstall() { function DoUninstall()
{
global $APPLICATION; global $APPLICATION;
CAgent::RemoveAgent("RCrmActions::orderAgent();", $this->MODULE_ID); CAgent::RemoveAgent("RCrmActions::orderAgent();", $this->MODULE_ID);
@ -1226,17 +1225,9 @@ class intaro_retailcrm extends CModule {
COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_NUMBERS); COption::RemoveOption($this->MODULE_ID, $this->CRM_ORDER_NUMBERS);
COption::RemoveOption($this->MODULE_ID, $this->CRM_CANSEL_ORDER); COption::RemoveOption($this->MODULE_ID, $this->CRM_CANSEL_ORDER);
//UnRegisterModuleDependences("sale", "OnSalePayOrder", $this->MODULE_ID, "RetailCrmEvent", "onSalePayOrder");
//UnRegisterModuleDependences("sale", "OnSaleCancelOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleCancelOrder");
//UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $this->MODULE_ID, "RetailCrmEvent", "onSendOrderMail");
UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder"); UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder");
UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd"); UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd");
UnRegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave"); UnRegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave");
//UnRegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAccountNumberSet");
//UnRegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleBeforeReserveOrder");
//UnRegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleReserveOrder");
//UnRegisterModuleDependences("main", "OnAfterUserRegister", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserRegister");
//UnRegisterModuleDependences("main", "OnAfterUserAdd", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserAdd");
UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate"); UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
UnRegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave"); UnRegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave");
UnRegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete"); UnRegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
@ -1263,13 +1254,15 @@ class intaro_retailcrm extends CModule {
); );
} }
function CopyFiles() { function CopyFiles()
{
CopyDirFiles( CopyDirFiles(
$_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/export/', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/', true, true $_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/' . $this->MODULE_ID . '/install/export/', $_SERVER['DOCUMENT_ROOT'] . '/bitrix/php_interface/include/catalog_export/', true, true
); );
} }
function DeleteFiles() { function DeleteFiles()
{
$rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y')); $rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y'));
$defaultSite = array(); $defaultSite = array();
while ($ar = $rsSites->Fetch()) { while ($ar = $rsSites->Fetch()) {
@ -1305,10 +1298,11 @@ class intaro_retailcrm extends CModule {
return $strVars; return $strVars;
} }
function historyLoad($api, $method){ function historyLoad($api, $method)
{
$page = null; $page = null;
$i = 0; $i = 0;
while(true){ while (true) {
$i++; $i++;
try { try {
$history = $api->$method(array(), $page); $history = $api->$method(array(), $page);
@ -1330,15 +1324,14 @@ class intaro_retailcrm extends CModule {
return $end['id']; return $end['id'];
} }
if(isset($history['history'])){ if (isset($history['history'])) {
$end = array_pop($history['history']); $end = array_pop($history['history']);
} } else {
else{
$end['id'] = 0; $end['id'] = 0;
break; break;
} }
if($history['pagination']['totalPageCount'] == $history['pagination']['currentPage']){ if ($history['pagination']['totalPageCount'] == $history['pagination']['currentPage']) {
break; break;
} }

View File

@ -24,7 +24,6 @@ else{
) )
); );
} }
echo"<pre>";var_export($arResult);echo"</pre>";
?> ?>
<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">

View File

@ -1,6 +1,6 @@
<? <?
$arModuleVersion = array( $arModuleVersion = array(
"VERSION" => "2.0.0", "VERSION" => "2.0.3",
"VERSION_DATE" => "2016-09-12 12:00:00" "VERSION_DATE" => "2016-10-04 18:00:00"
); );

View File

@ -36,23 +36,21 @@ $arResult = array();
if (file_exists($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.retailcrm/classes/general/config/options.xml')) { if (file_exists($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.retailcrm/classes/general/config/options.xml')) {
$options = simplexml_load_file($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.retailcrm/classes/general/config/options.xml'); $options = simplexml_load_file($_SERVER["DOCUMENT_ROOT"] . '/bitrix/modules/intaro.retailcrm/classes/general/config/options.xml');
foreach($options->contragents->contragent as $contragent) foreach($options->contragents->contragent as $contragent) {
{
$type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET); $type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$contragent["id"]; $type["ID"] = (string)$contragent["id"];
$arResult['contragentType'][] = $type; $arResult['contragentType'][] = $type;
unset ($type); unset ($type);
} }
foreach($options->fields->field as $field) foreach($options->fields->field as $field) {
{
$type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET); $type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$field["id"]; $type["ID"] = (string)$field["id"];
if ($field["group"] == 'custom') { if ($field["group"] == 'custom') {
$arResult['customFields'][] = $type; $arResult['customFields'][] = $type;
} elseif(!$field["group"]){ } elseif (!$field["group"]) {
$arResult['orderProps'][] = $type; $arResult['orderProps'][] = $type;
} else{ } else {
$groups = explode(",", (string)$field["group"]); $groups = explode(",", (string)$field["group"]);
foreach ($groups as $group) { foreach ($groups as $group) {
$type["GROUP"][] = trim($group); $type["GROUP"][] = trim($group);
@ -86,11 +84,11 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
$optionsDelivTypes = unserialize(COption::GetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, 0)); $optionsDelivTypes = unserialize(COption::GetOptionString($mid, $CRM_DELIVERY_TYPES_ARR, 0));
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
foreach($optionsDelivTypes as $key => $deliveryType){ foreach ($optionsDelivTypes as $key => $deliveryType) {
foreach($arDeliveryServiceAll as $deliveryService){ foreach ($arDeliveryServiceAll as $deliveryService) {
if($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $key){ if ($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $key) {
$srv = explode(':', $deliveryService['CODE']); $srv = explode(':', $deliveryService['CODE']);
if(count($srv) == 2){ if (count($srv) == 2) {
try { try {
$api->deliveryServicesEdit(RCrmActions::clearArr(array( $api->deliveryServicesEdit(RCrmActions::clearArr(array(
'code' => $srv[1], 'code' => $srv[1],
@ -114,18 +112,18 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
} }
//upload orders after install module //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){ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') && isset($_POST['ajax']) && $_POST['ajax'] == 2) {
$step = $_POST['step']; $step = $_POST['step'];
$orders = $_POST['orders']; $orders = $_POST['orders'];
$countStep = 50; // 50 orders on step $countStep = 50; // 50 orders on step
if($orders){ if ($orders) {
$ordersArr = explode(',', $orders); $ordersArr = explode(',', $orders);
$orders = array(); $orders = array();
foreach($ordersArr as $_ordersArr){ foreach ($ordersArr as $_ordersArr) {
$ordersList = explode('-', trim($_ordersArr)); $ordersList = explode('-', trim($_ordersArr));
if(count($ordersList) > 1){ if (count($ordersList) > 1) {
for($i = (int)trim($ordersList[0]); $i <= (int)trim($ordersList[count($ordersList) - 1]); $i++){ for ($i = (int)trim($ordersList[0]); $i <= (int)trim($ordersList[count($ordersList) - 1]); $i++) {
$orders[] = $i; $orders[] = $i;
} }
} else{ } else{
@ -141,14 +139,13 @@ if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQ
$percent = round((($step * $countStep + count($stepOrders)) * 100 / count($orders)), 1); $percent = round((($step * $countStep + count($stepOrders)) * 100 / count($orders)), 1);
$step++; $step++;
if(!$splitedOrders[$step]){ if (!$splitedOrders[$step]) {
$step='end'; $step = 'end';
} }
$res = array("step" => $step, "percent" => $percent, 'stepOrders' => $stepOrders); $res = array("step" => $step, "percent" => $percent, 'stepOrders' => $stepOrders);
} else{ } else {
$orders = array(); $orders = array();
for($i = 1; $i <= $countStep; $i++){ for($i = 1; $i <= $countStep; $i++){
$orders[] = $i + $step * $countStep; $orders[] = $i + $step * $countStep;
} }
@ -160,7 +157,7 @@ if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQ
$countAll = (int) CSaleOrder::GetList(array("ID" => "ASC"), array(), array()); $countAll = (int) CSaleOrder::GetList(array("ID" => "ASC"), array(), array());
$percent = round(100 - ($countLeft * 100 / $countAll), 1); $percent = round(100 - ($countLeft * 100 / $countAll), 1);
if($countLeft == 0){ if ($countLeft == 0) {
$step = 'end'; $step = 'end';
} }
@ -183,7 +180,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$siteListArr[$arSites['LID']] = htmlspecialchars(trim($_POST['sites-id-' . $arSites['LID']])); $siteListArr[$arSites['LID']] = htmlspecialchars(trim($_POST['sites-id-' . $arSites['LID']]));
} }
if($api_host && $api_key) { if ($api_host && $api_key) {
$api = new RetailCrm\ApiClient($api_host, $api_key); $api = new RetailCrm\ApiClient($api_host, $api_key);
try { try {
$api->paymentStatusesList(); $api->paymentStatusesList();
@ -205,7 +202,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$orderTypesList = RCrmActions::OrderTypesList($arResult['arSites']); $orderTypesList = RCrmActions::OrderTypesList($arResult['arSites']);
$orderTypesArr = array(); $orderTypesArr = array();
foreach($orderTypesList as $orderType){ foreach ($orderTypesList as $orderType) {
$orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']])); $orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']]));
} }
@ -213,7 +210,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$arResult['bitrixDeliveryTypesList'] = RCrmActions::DeliveryList(); $arResult['bitrixDeliveryTypesList'] = RCrmActions::DeliveryList();
$deliveryTypesArr = array(); $deliveryTypesArr = array();
foreach($arResult['bitrixDeliveryTypesList'] as $delivery){ foreach ($arResult['bitrixDeliveryTypesList'] as $delivery) {
$deliveryTypesArr[$delivery['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $delivery['ID']])); $deliveryTypesArr[$delivery['ID']] = htmlspecialchars(trim($_POST['delivery-type-' . $delivery['ID']]));
} }
@ -221,7 +218,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList(); $arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList();
$paymentTypesArr = array(); $paymentTypesArr = array();
foreach($arResult['bitrixPaymentTypesList'] as $payment){ foreach ($arResult['bitrixPaymentTypesList'] as $payment) {
$paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']])); $paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']]));
} }
@ -231,9 +228,9 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$paymentStatusesArr = array(); $paymentStatusesArr = array();
$canselOrderArr = array(); $canselOrderArr = array();
//$paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY'])); //$paymentStatusesArr['YY'] = htmlspecialchars(trim($_POST['payment-status-YY']));
foreach($arResult['bitrixStatusesList'] as $status){ foreach ($arResult['bitrixStatusesList'] as $status) {
$paymentStatusesArr[$status['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $status['ID']])); $paymentStatusesArr[$status['ID']] = htmlspecialchars(trim($_POST['payment-status-' . $status['ID']]));
if(trim($_POST['order-cansel-' . $status['ID']]) == 'Y'){ if (trim($_POST['order-cansel-' . $status['ID']]) == 'Y') {
$canselOrderArr[] = $status['ID']; $canselOrderArr[] = $status['ID'];
} }
} }
@ -249,15 +246,14 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
// 0 - agent // 0 - agent
// 1 - event // 1 - event
$orderDischarge = 0; $orderDischarge = 0;
$orderDischarge = (int) htmlspecialchars(trim($_POST['order-discharge'])); $orderDischarge = (int) htmlspecialchars(trim($_POST['order-discharge']));
///////////тут дописать\\\\\\\\\\\\\\\
if (($orderDischarge != $previousDischarge) && ($orderDischarge == 0)) { if (($orderDischarge != $previousDischarge) && ($orderDischarge == 0)) {
// remove depenedencies // remove depenedencies
UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $mid, "ICrmOrderEvent", "onSendOrderMail"); UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $mid, "ICrmOrderEvent", "onSendOrderMail");
UnRegisterModuleDependences("sale", "OnOrderUpdate", $mid, "ICrmOrderEvent", "onUpdateOrder"); UnRegisterModuleDependences("sale", "OnOrderUpdate", $mid, "ICrmOrderEvent", "onUpdateOrder");
UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $mid, "ICrmOrderEvent", "onBeforeOrderAdd"); UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $mid, "ICrmOrderEvent", "onBeforeOrderAdd");
} else if (($orderDischarge != $previousDischarge) && ($orderDischarge == 1)) { } elseif (($orderDischarge != $previousDischarge) && ($orderDischarge == 1)) {
// event dependencies // event dependencies
RegisterModuleDependences("sale", "OnOrderNewSendEmail", $mid, "ICrmOrderEvent", "onSendOrderMail"); RegisterModuleDependences("sale", "OnOrderNewSendEmail", $mid, "ICrmOrderEvent", "onSendOrderMail");
RegisterModuleDependences("sale", "OnOrderUpdate", $mid, "ICrmOrderEvent", "onUpdateOrder"); RegisterModuleDependences("sale", "OnOrderUpdate", $mid, "ICrmOrderEvent", "onUpdateOrder");
@ -269,7 +265,7 @@ 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']]));
@ -324,7 +320,6 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
} else { } else {
$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 RetailCrm\ApiClient($api_host, $api_key); $api = new RetailCrm\ApiClient($api_host, $api_key);
//prepare crm lists //prepare crm lists
@ -360,10 +355,6 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
//bitrix statusesList //bitrix statusesList
$arResult['bitrixPaymentStatusesList'] = RCrmActions::StatusesList(); $arResult['bitrixPaymentStatusesList'] = RCrmActions::StatusesList();
/*$arResult['bitrixPaymentStatusesList'][] = array(
'ID' => 'YY',
'NAME' => GetMessage('CANCELED')
);*/
//bitrix pyament Y/N //bitrix pyament Y/N
$arResult['bitrixPaymentList'][0]['NAME'] = GetMessage('PAYMENT_Y'); $arResult['bitrixPaymentList'][0]['NAME'] = GetMessage('PAYMENT_Y');