1
0
mirror of synced 2025-01-18 08:51:40 +03:00
This commit is contained in:
Евгений Тыщицкий 2016-10-04 17:57:39 +03:00
parent 53c1117621
commit 02828f45e6
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
* API V4
* Переход на ядро d7

View File

@ -1,15 +1,15 @@
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:
* Exchange the orders with retailCRM
* 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
-------------
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'));
$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 . '/');
}
$file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log';
@ -24,7 +23,7 @@ class Logger
$data['DATA'] = $dump;
$f = fopen($file, "a+");
fwrite($f, print_r($data,true));
fwrite($f, print_r($data, true));
fclose($f);
// if filesize more than 5 Mb rotate it

View File

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

View File

@ -32,24 +32,6 @@ class RestNormalizer
$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
* @param string $file The path to the file validation
@ -117,10 +99,9 @@ class RestNormalizer
$formatted = array();
foreach ($data as $code => $value) {
if (isset($this->validation[ $code ]) && $this->validation[ $code ]['type'] == 'skip') {
$formatted[ $code ] = $value;
}elseif (isset($this->validation[ $code ]) && is_array($value) === false) {
} elseif (isset($this->validation[ $code ]) && is_array($value) === false) {
$formatted[ $code ] = $this->setFormat($value, $this->validation[ $code ]);
} elseif (is_array($value)) {
$formatted[ $code ] = $this->formatting($value, true);
@ -208,7 +189,7 @@ class RestNormalizer
} elseif (isset($validation['min']) && mb_strlen($data) < $validation['min']) {
$pad = isset($validation['pad']) && mb_strlen($validation['pad']) == 1 ? $validation['pad'] : ' ';
$data .= str_repeat($pad, $validation['min'] - mb_strlen($data));
}elseif (isset($validation['max']) && mb_strlen($data) > $validation['max']) {
} elseif (isset($validation['max']) && mb_strlen($data) > $validation['max']) {
$data = mb_substr($data, 0, $validation['max']);
}

View File

@ -2,7 +2,8 @@
/**
* RCrmEvent
*/
class RetailCrmEvent {
class RetailCrmEvent
{
protected static $MODULE_ID = 'intaro.retailcrm';
protected static $CRM_API_HOST_OPTION = 'api_host';
protected static $CRM_API_KEY_OPTION = 'api_key';
@ -24,12 +25,13 @@ class RetailCrmEvent {
*
* @param mixed $arFields - User arFields
*/
function OnAfterUserUpdate($arFields) {
if(isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']){
function OnAfterUserUpdate($arFields)
{
if (isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) {
return;
}
if(!$arFields['RESULT']){
if (!$arFields['RESULT']) {
return;
}
@ -40,7 +42,7 @@ class RetailCrmEvent {
$optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0));
$resultOrder = RetailCrmUser::customerEdit($arFields, $api, $optionsSitesList);
if(!$resultOrder) {
if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::OnAfterUserUpdate', 'RetailCrmUser::customerEdit', 'error update customer');
}
@ -63,10 +65,11 @@ class RetailCrmEvent {
* @param mixed $ID - Order id
* @param mixed $arFields - Order arFields
*/
function OnOrderSave($ID, $arFields, $arOrder, $isNew) {
$GLOBALS['RETAILCRM_EVENT_OLD'] = true;
return;
}
// function OnOrderSave($ID, $arFields, $arOrder, $isNew)
// {
// $GLOBALS['RETAILCRM_EVENT_OLD'] = true;
// return;
// }
/**
* onUpdateOrder
@ -74,8 +77,9 @@ class RetailCrmEvent {
* @param mixed $ID - Order id
* @param mixed $arFields - Order arFields
*/
function onUpdateOrder($ID, $arFields) {
if(isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']){
function onUpdateOrder($ID, $arFields)
{
if (isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) {
$GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] = false;
return;
}
@ -89,7 +93,8 @@ class RetailCrmEvent {
*
* @param object $event - Order object
*/
function orderDelete($event){
function orderDelete($event)
{
$GLOBALS['RETAILCRM_ORDER_DELETE'] = true;
return;
}
@ -100,8 +105,9 @@ class RetailCrmEvent {
* @param object $event - Order object
*/
function orderSave($event){
if($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true){
function orderSave($event)
{
if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] !== false && $GLOBALS['RETAIL_CRM_HISTORY'] !== true && $GLOBALS['RETAILCRM_ORDER_DELETE'] !== true) {
if (!CModule::IncludeModule('iblock')) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found');
return true;
@ -118,13 +124,11 @@ class RetailCrmEvent {
}
//проверка на существование getParameter("ENTITY")
if(method_exists($event, 'getId')){
if (method_exists($event, 'getId')) {
$obOrder = $event;
}
elseif(method_exists($event, 'getParameter')){
} elseif (method_exists($event, 'getParameter')) {
$obOrder = $event->getParameter("ENTITY");
}
else{
} else {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error');
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);
if(isset($orderCrm['order'])){
if (isset($orderCrm['order'])) {
$methodApi = 'ordersEdit';
}
else{
} else {
$methodApi = 'ordersCreate';
}
//user
$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();
$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');
return true;
}
@ -186,7 +189,7 @@ class RetailCrmEvent {
//order
$resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi);
if(!$resultOrder) {
if (!$resultOrder) {
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order');
return true;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1,3 @@
<?
//<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>
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'))
return;
class intaro_retailcrm extends CModule {
class intaro_retailcrm extends CModule
{
var $MODULE_ID = 'intaro.retailcrm';
var $OLD_MODULE_ID = 'intaro.intarocrm';
var $MODULE_VERSION;
@ -49,7 +49,8 @@ class intaro_retailcrm extends CModule {
var $CRM_CANSEL_ORDER = 'cansel_order';
var $INSTALL_PATH;
function intaro_retailcrm() {
function intaro_retailcrm()
{
$arModuleVersion = array();
$path = str_replace("\\", "/", __FILE__);
$path = substr($path, 0, strlen($path) - strlen("/index.php"));
@ -67,7 +68,8 @@ class intaro_retailcrm extends CModule {
* Functions DoInstall and DoUninstall are
* All other functions are optional
*/
function DoInstall() {
function DoInstall()
{
global $APPLICATION, $step, $arResult;
if (!in_array('curl', get_loaded_extensions())) {
@ -78,12 +80,14 @@ class intaro_retailcrm extends CModule {
$infoSale = CModule::CreateModuleObject('sale')->MODULE_VERSION;
if (version_compare($infoSale, '16', '<=')) {
$APPLICATION->ThrowException(GetMessage("SALE_VERSION_ERR"));
return false;
}
if (!date_default_timezone_get()) {
if (!ini_get('date.timezone')) {
$APPLICATION->ThrowException(GetMessage("DATE_TIMEZONE_ERR"));
return false;
}
}
@ -107,25 +111,23 @@ class intaro_retailcrm extends CModule {
if (file_exists($this->INSTALL_PATH . '/../classes/general/config/options.xml')) {
$options = simplexml_load_file($this->INSTALL_PATH . '/../classes/general/config/options.xml');
foreach($options->contragents->contragent as $contragent)
{
foreach ($options->contragents->contragent as $contragent) {
$type["NAME"] = $APPLICATION->ConvertCharset((string)$contragent, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$contragent["id"];
$arResult['contragentType'][] = $type;
unset ($type);
}
foreach($options->fields->field as $field)
{
foreach($options->fields->field as $field) {
$type["NAME"] = $APPLICATION->ConvertCharset((string)$field, 'utf-8', SITE_CHARSET);
$type["ID"] = (string)$field["id"];
if ($field["group"] == 'custom') {
$arResult['customFields'][] = $type;
} elseif(!$field["group"]){
} elseif (!$field["group"]) {
$arResult['orderProps'][] = $type;
} else{
} else {
$groups = explode(",", (string)$field["group"]);
foreach($groups as $group){
foreach ($groups as $group) {
$type["GROUP"][] = trim($group);
}
$arResult['legalDetails'][] = $type;
@ -134,9 +136,9 @@ class intaro_retailcrm extends CModule {
}
}
if($step == 11){
if ($step == 11) {
$arResult['arSites'] = RCrmActions::SitesList();
if(count($arResult['arSites'])<2){
if (count($arResult['arSites']) < 2) {
$step = 2;
}
}
@ -153,17 +155,17 @@ class intaro_retailcrm extends CModule {
$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;
}
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;
}
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
);
} else if ($step == 11) {
} elseif ($step == 11) {
//new page
if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE';
@ -190,7 +192,9 @@ class intaro_retailcrm extends CModule {
// form correct url
$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'];
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_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);
}
@ -232,15 +236,12 @@ class intaro_retailcrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step11.php'
);
} else if ($step == 2) {//доставки, оплаты, типы заказов
if (!CModule::IncludeModule("sale")) {
$arResult['errCode'] = 'ERR_SALE';
}
if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK';
}
if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG';
}
@ -249,6 +250,7 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step1.php'
);
return;
}
@ -535,13 +537,13 @@ class intaro_retailcrm extends CModule {
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_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
foreach($arResult['arSites'] as $site){
if($_POST['sites-id-'.$site['LID']] && !empty($_POST['sites-id-'.$site['LID']])){
foreach ($arResult['arSites'] as $site) {
if ($_POST['sites-id-'.$site['LID']] && !empty($_POST['sites-id-'.$site['LID']])) {
$siteCode[$site['LID']] = htmlspecialchars(trim($_POST['sites-id-'.$site['LID']]));
}
}
@ -555,14 +557,15 @@ class intaro_retailcrm extends CModule {
$this->RETAIL_CRM_API = new \RetailCrm\ApiClient($api_host, $api_key);
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_key = htmlspecialchars(trim($_POST[$this->CRM_API_KEY_OPTION]));
// form correct url
$api_host = parse_url($api_host);
if($api_host['scheme'] != 'https') $api_host['scheme'] = 'https';
if($api_host['scheme'] != 'https') {
$api_host['scheme'] = 'https';
}
$api_host = $api_host['scheme'] . '://' . $api_host['host'];
if (!$api_host || !$api_key) {
@ -623,28 +626,28 @@ class intaro_retailcrm extends CModule {
//bitrix statusesList --statuses
$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));
}
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));
}
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));
}
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));
}
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));
}
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step2.php'
);
} else if ($step == 3) {//сопостовление свойств заказа
} elseif ($step == 3) {//сопостовление свойств заказа
if (!CModule::IncludeModule("sale")) {
//handler
$arResult['errCode'] = 'ERR_SALE';
}
if (isset($_POST['back']) && $_POST['back']) {
@ -663,7 +666,7 @@ class intaro_retailcrm extends CModule {
$arResult['bitrixOrderTypesList'] = RCrmActions::OrderTypesList($arResult['arSites']);
$orderTypesArr = array();
foreach($arResult['bitrixOrderTypesList'] as $orderType){
foreach ($arResult['bitrixOrderTypesList'] as $orderType) {
$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') {//сами настраиваем доставки
$deliveryTypesArr = array();
foreach($arResult['bitrixDeliveryTypesList'] as $delivery){
foreach ($arResult['bitrixDeliveryTypesList'] as $delivery) {
$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!
foreach($optionsDelivTypes as $deliveryType){
foreach ($optionsDelivTypes as $deliveryType) {
$load = true;
try {
$this->RETAIL_CRM_API->deliveryTypesEdit(RCrmActions::clearArr(array(
@ -695,11 +697,11 @@ class intaro_retailcrm extends CModule {
$e->getCode() . ': ' . $e->getMessage()
);
}
if($load){
foreach($optionsDelivTypes as $deliveryService){
if($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $deliveryType['ID']){
if ($load) {
foreach ($optionsDelivTypes as $deliveryService) {
if ($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $deliveryType['ID']) {
$srv = explode(':', $deliveryService['CODE']);
if(count($srv) == 2){
if (count($srv) == 2) {
try {
$this->RETAIL_CRM_API->deliveryServicesEdit(RCrmActions::clearArr(array(
'code' => $srv[1],
@ -723,7 +725,7 @@ class intaro_retailcrm extends CModule {
$arResult['bitrixPaymentTypesList'] = RCrmActions::PaymentList();
$paymentTypesArr = array();
foreach($arResult['bitrixPaymentTypesList'] as $payment){
foreach ($arResult['bitrixPaymentTypesList'] as $payment) {
$paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']]));
}
@ -733,9 +735,9 @@ class intaro_retailcrm extends CModule {
$paymentStatusesArr = array();
$canselOrderArr = array();
foreach($arResult['bitrixStatusesList'] as $status){
foreach ($arResult['bitrixStatusesList'] as $status) {
$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'];
}
}
@ -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_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);
}
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);
}
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);
}
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);
}
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step3.php'
);
} else if ($step == 4) {//выгрузка старых заказов
} elseif ($step == 4) {//выгрузка старых заказов
if (!CModule::IncludeModule("sale")) {
//handler
$arResult['errCode'] = 'ERR_SALE';
}
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));
$countAll = (int) \Bitrix\Sale\Internals\OrderTable::getCount();
if (!isset($_POST['finish'])){
if (!isset($_POST['finish'])) {
$finish = 0;
}
else{
} else {
$finish = (int) $_POST['finish'];
}
$percent = round(100 - ($countLeft * 100 / $countAll), 1);
if (!$countLeft){
if (!$countLeft) {
$finish = 1;
}
$APPLICATION->RestartBuffer();
@ -820,7 +821,7 @@ class intaro_retailcrm extends CModule {
$orderTypesList = RCrmActions::OrderTypesList(RCrmActions::SitesList());
$orderTypesArr = array();
foreach($orderTypesList as $orderType){
foreach ($orderTypesList as $orderType) {
$orderTypesArr[$orderType['ID']] = htmlspecialchars(trim($_POST['order-type-' . $orderType['ID']]));
}
@ -829,8 +830,9 @@ class intaro_retailcrm extends CModule {
$propsCount = 0;
$_orderPropsArr = array();
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;
}
$_orderPropsArr[$orderProp['ID']] = htmlspecialchars(trim($_POST['order-prop-' . $orderProp['ID'] . '-' . $orderType['ID']]));
$propsCount++;
}
@ -871,14 +873,14 @@ class intaro_retailcrm extends CModule {
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step4.php'
);
} else if ($step == 5) {//экспорт каталога
} elseif ($step == 5) {//экспорт каталога
if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK';
}
if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG';
}
$api_host = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($this->MODULE_ID, $this->CRM_API_KEY_OPTION, 0);
$api = new \RetailCrm\ApiClient($api_host, $api_key);
@ -886,7 +888,7 @@ class intaro_retailcrm extends CModule {
$customerH = self::historyLoad($api, 'customersHistory');
COption::SetOptionString($this->MODULE_ID, $this->CRM_CUSTOMER_HISTORY, $customerH);
//если есть старое значение, переделываем его на новый лад, иначе вычисляем
if($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)){
if ($historyDate = COption::GetOptionString($this->OLD_MODULE_ID, 'order_history_date', 0)) {
try {
$history = $api->ordersHistory(array('startDate' => $historyDate));
} 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;
$orderH = $hIs;
}
else{
} else {
$orderH = self::historyLoad($api, 'ordersHistory');
}
}
else{
} else {
$orderH = self::historyLoad($api, 'ordersHistory');
}
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_HISTORY, $orderH);
if($orderLastId = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_LAST_ID, 0)){
if ($orderLastId = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_LAST_ID, 0)) {
COption::SetOptionString($this->MODULE_ID, $this->CRM_ORDER_LAST_ID, $orderLastId);
}
if($orderFailedIds = COption::GetOptionString($this->OLD_MODULE_ID, $this->CRM_ORDER_FAILED_IDS, 0)){
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);
}
@ -935,12 +936,10 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php'
);
} else if ($step == 6) {//регистрация модуля
} elseif ($step == 6) {//регистрация модуля
if (!CModule::IncludeModule("iblock")) {
$arResult['errCode'] = 'ERR_IBLOCK';
}
if (!CModule::IncludeModule("catalog")) {
$arResult['errCode'] = 'ERR_CATALOG';
}
@ -949,6 +948,7 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php'
);
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';
else
} else {
$iblocks = $_POST['IBLOCK_EXPORT'];
}
$iblockProperties = Array(
$iblockProperties = array(
"article" => "article",
"manufacturer" => "manufacturer",
"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';
else
} else {
$filename = $_POST['SETUP_FILE_NAME'];
}
if (!isset($_POST['TYPE_LOADING']))
if (!isset($_POST['TYPE_LOADING'])) {
$typeLoading = 0;
else
} else {
$typeLoading = $_POST['TYPE_LOADING'];
}
if (!isset($_POST['SETUP_PROFILE_NAME']))
if (!isset($_POST['SETUP_PROFILE_NAME'])) {
$profileName = "";
else
} else {
$profileName = $_POST['SETUP_PROFILE_NAME'];
}
if ($typeLoading != 'none' && $profileName == "")
if ($typeLoading != 'none' && $profileName == "") {
$arResult['errCode'] = 'ERR_FIELDS_PROFILE';
if ($filename == "")
}
if ($filename == "") {
$arResult['errCode'] = 'ERR_FIELDS_FILE';
}
if (isset($arResult['errCode']) && $arResult['errCode']) {
$arOldValues = Array(
$arOldValues = array(
'IBLOCK_EXPORT' => $iblocks,
'IBLOCK_PROPERTY_SKU' => $propertiesSKU,
'IBLOCK_PROPERTY_UNIT_SKU' => $propertiesUnitSKU,
@ -1033,21 +1038,14 @@ class intaro_retailcrm extends CModule {
$APPLICATION->IncludeAdminFile(
GetMessage('MODULE_INSTALL_TITLE'), $this->INSTALL_PATH . '/step5.php'
);
return;
}
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", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd");
RegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave");
//RegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "OnSaleBeforeReserveOrder");
//RegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleReserveOrder");
//RegisterModuleDependences("main", "OnAfterUserRegister", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserRegister");
//RegisterModuleDependences("main", "OnAfterUserAdd", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserAdd");
RegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
RegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave");
RegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
@ -1094,10 +1092,10 @@ class intaro_retailcrm extends CModule {
));
if (intval($PROFILE_ID) <= 0) {
$arResult['errCode'] = 'ERR_IBLOCK';
return;
}
if ($typeLoading == 'agent') {
$dateAgent = new DateTime();
$intAgent = new DateInterval('PT60S'); // PT60S - 60 sec;
$dateAgent->add($intAgent);
@ -1199,7 +1197,8 @@ class intaro_retailcrm extends CModule {
}
}
function DoUninstall() {
function DoUninstall()
{
global $APPLICATION;
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_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", "OnBeforeOrderAdd", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAdd");
UnRegisterModuleDependences("sale", "OnOrderSave", $this->MODULE_ID, "RetailCrmEvent", "OnOrderSave");
//UnRegisterModuleDependences("sale", "OnBeforeOrderAccountNumberSet", $this->MODULE_ID, "RetailCrmEvent", "onBeforeOrderAccountNumberSet");
//UnRegisterModuleDependences("sale", "OnSaleBeforeReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleBeforeReserveOrder");
//UnRegisterModuleDependences("sale", "OnSaleReserveOrder", $this->MODULE_ID, "RetailCrmEvent", "onSaleReserveOrder");
//UnRegisterModuleDependences("main", "OnAfterUserRegister", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserRegister");
//UnRegisterModuleDependences("main", "OnAfterUserAdd", $this->MODULE_ID, "ICrmOrderEvent", "OnAfterUserAdd");
UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
UnRegisterModuleDependences("sale", "OnSaleOrderEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "orderSave");
UnRegisterModuleDependences("sale", "OnSaleOrderEntityDelete", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
@ -1263,13 +1254,15 @@ class intaro_retailcrm extends CModule {
);
}
function CopyFiles() {
function CopyFiles()
{
CopyDirFiles(
$_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'));
$defaultSite = array();
while ($ar = $rsSites->Fetch()) {
@ -1305,10 +1298,11 @@ class intaro_retailcrm extends CModule {
return $strVars;
}
function historyLoad($api, $method){
function historyLoad($api, $method)
{
$page = null;
$i = 0;
while(true){
while (true) {
$i++;
try {
$history = $api->$method(array(), $page);
@ -1330,15 +1324,14 @@ class intaro_retailcrm extends CModule {
return $end['id'];
}
if(isset($history['history'])){
if (isset($history['history'])) {
$end = array_pop($history['history']);
}
else{
} else {
$end['id'] = 0;
break;
}
if($history['pagination']['totalPageCount'] == $history['pagination']['currentPage']){
if ($history['pagination']['totalPageCount'] == $history['pagination']['currentPage']) {
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">

View File

@ -1,6 +1,6 @@
<?
$arModuleVersion = array(
"VERSION" => "2.0.0",
"VERSION_DATE" => "2016-09-12 12:00:00"
"VERSION" => "2.0.3",
"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')) {
$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["ID"] = (string)$contragent["id"];
$arResult['contragentType'][] = $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["ID"] = (string)$field["id"];
if ($field["group"] == 'custom') {
$arResult['customFields'][] = $type;
} elseif(!$field["group"]){
} elseif (!$field["group"]) {
$arResult['orderProps'][] = $type;
} else{
} else {
$groups = explode(",", (string)$field["group"]);
foreach ($groups as $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));
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
foreach($optionsDelivTypes as $key => $deliveryType){
foreach($arDeliveryServiceAll as $deliveryService){
if($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $key){
foreach ($optionsDelivTypes as $key => $deliveryType) {
foreach ($arDeliveryServiceAll as $deliveryService) {
if ($deliveryService['PARENT_ID'] != 0 && $deliveryService['PARENT_ID'] == $key) {
$srv = explode(':', $deliveryService['CODE']);
if(count($srv) == 2){
if (count($srv) == 2) {
try {
$api->deliveryServicesEdit(RCrmActions::clearArr(array(
'code' => $srv[1],
@ -114,18 +112,18 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE
}
//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'];
$orders = $_POST['orders'];
$countStep = 50; // 50 orders on step
if($orders){
if ($orders) {
$ordersArr = explode(',', $orders);
$orders = array();
foreach($ordersArr as $_ordersArr){
foreach ($ordersArr as $_ordersArr) {
$ordersList = explode('-', trim($_ordersArr));
if(count($ordersList) > 1){
for($i = (int)trim($ordersList[0]); $i <= (int)trim($ordersList[count($ordersList) - 1]); $i++){
if (count($ordersList) > 1) {
for ($i = (int)trim($ordersList[0]); $i <= (int)trim($ordersList[count($ordersList) - 1]); $i++) {
$orders[] = $i;
}
} 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);
$step++;
if(!$splitedOrders[$step]){
$step='end';
if (!$splitedOrders[$step]) {
$step = 'end';
}
$res = array("step" => $step, "percent" => $percent, 'stepOrders' => $stepOrders);
} else{
$orders = array();
} else {
$orders = array();
for($i = 1; $i <= $countStep; $i++){
$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());
$percent = round(100 - ($countLeft * 100 / $countAll), 1);
if($countLeft == 0){
if ($countLeft == 0) {
$step = 'end';
}
@ -183,7 +180,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$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);
try {
$api->paymentStatusesList();
@ -205,7 +202,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$orderTypesList = RCrmActions::OrderTypesList($arResult['arSites']);
$orderTypesArr = array();
foreach($orderTypesList as $orderType){
foreach ($orderTypesList as $orderType) {
$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();
$deliveryTypesArr = array();
foreach($arResult['bitrixDeliveryTypesList'] as $delivery){
foreach ($arResult['bitrixDeliveryTypesList'] as $delivery) {
$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();
$paymentTypesArr = array();
foreach($arResult['bitrixPaymentTypesList'] as $payment){
foreach ($arResult['bitrixPaymentTypesList'] as $payment) {
$paymentTypesArr[$payment['ID']] = htmlspecialchars(trim($_POST['payment-type-' . $payment['ID']]));
}
@ -231,9 +228,9 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$paymentStatusesArr = array();
$canselOrderArr = array();
//$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']]));
if(trim($_POST['order-cansel-' . $status['ID']]) == 'Y'){
if (trim($_POST['order-cansel-' . $status['ID']]) == 'Y') {
$canselOrderArr[] = $status['ID'];
}
}
@ -249,15 +246,14 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
// 0 - agent
// 1 - event
$orderDischarge = 0;
$orderDischarge = (int) htmlspecialchars(trim($_POST['order-discharge']));
///////////тут дописать\\\\\\\\\\\\\\\
$orderDischarge = (int) htmlspecialchars(trim($_POST['order-discharge']));
if (($orderDischarge != $previousDischarge) && ($orderDischarge == 0)) {
// remove depenedencies
UnRegisterModuleDependences("sale", "OnOrderNewSendEmail", $mid, "ICrmOrderEvent", "onSendOrderMail");
UnRegisterModuleDependences("sale", "OnOrderUpdate", $mid, "ICrmOrderEvent", "onUpdateOrder");
UnRegisterModuleDependences("sale", "OnBeforeOrderAdd", $mid, "ICrmOrderEvent", "onBeforeOrderAdd");
} else if (($orderDischarge != $previousDischarge) && ($orderDischarge == 1)) {
} elseif (($orderDischarge != $previousDischarge) && ($orderDischarge == 1)) {
// event dependencies
RegisterModuleDependences("sale", "OnOrderNewSendEmail", $mid, "ICrmOrderEvent", "onSendOrderMail");
RegisterModuleDependences("sale", "OnOrderUpdate", $mid, "ICrmOrderEvent", "onUpdateOrder");
@ -269,7 +265,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
$propsCount = 0;
$_orderPropsArr = array();
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;
}
$_orderPropsArr[$orderProp['ID']] = htmlspecialchars(trim($_POST['order-prop-' . $orderProp['ID'] . '-' . $orderType['ID']]));
@ -324,7 +320,6 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
} else {
$api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0);
$api_key = COption::GetOptionString($mid, $CRM_API_KEY_OPTION, 0);
$api = new RetailCrm\ApiClient($api_host, $api_key);
//prepare crm lists
@ -360,10 +355,6 @@ if (isset($_POST['Update']) && ($_POST['Update'] == 'Y')) {
//bitrix statusesList
$arResult['bitrixPaymentStatusesList'] = RCrmActions::StatusesList();
/*$arResult['bitrixPaymentStatusesList'][] = array(
'ID' => 'YY',
'NAME' => GetMessage('CANCELED')
);*/
//bitrix pyament Y/N
$arResult['bitrixPaymentList'][0]['NAME'] = GetMessage('PAYMENT_Y');