2016-09-15 16:42:10 +03:00
< ? php
IncludeModuleLangFile ( __FILE__ );
class RetailCrmHistory
{
public static $MODULE_ID = 'intaro.retailcrm' ;
public static $CRM_API_HOST_OPTION = 'api_host' ;
public static $CRM_API_KEY_OPTION = 'api_key' ;
public static $CRM_ORDER_TYPES_ARR = 'order_types_arr' ;
public static $CRM_DELIVERY_TYPES_ARR = 'deliv_types_arr' ;
public static $CRM_PAYMENT_TYPES = 'pay_types_arr' ;
public static $CRM_PAYMENT_STATUSES = 'pay_statuses_arr' ;
public static $CRM_PAYMENT = 'payment_arr' ; //order payment Y/N
public static $CRM_ORDER_LAST_ID = 'order_last_id' ;
public static $CRM_SITES_LIST = 'sites_list' ;
public static $CRM_ORDER_PROPS = 'order_props' ;
public static $CRM_LEGAL_DETAILS = 'legal_details' ;
public static $CRM_CUSTOM_FIELDS = 'custom_fields' ;
public static $CRM_CONTRAGENT_TYPE = 'contragent_type' ;
public static $CRM_ORDER_FAILED_IDS = 'order_failed_ids' ;
public static $CRM_ORDER_HISTORY = 'order_history' ;
public static $CRM_CUSTOMER_HISTORY = 'customer_history' ;
public static $CRM_CATALOG_BASE_PRICE = 'catalog_base_price' ;
public static $CRM_ORDER_NUMBERS = 'order_numbers' ;
public static $CRM_CANSEL_ORDER = 'cansel_order' ;
const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED' ;
2016-10-04 17:57:39 +03:00
public static function customerHistory ()
{
2016-09-15 16:42:10 +03:00
if ( ! CModule :: IncludeModule ( " iblock " )) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'iblock' , 'module not found' );
return false ;
}
if ( ! CModule :: IncludeModule ( " sale " )) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'sale' , 'module not found' );
return false ;
}
if ( ! CModule :: IncludeModule ( " catalog " )) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'catalog' , 'module not found' );
return false ;
}
$api_host = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_API_HOST_OPTION , 0 );
$api_key = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_API_KEY_OPTION , 0 );
$api = new RetailCrm\ApiClient ( $api_host , $api_key );
$historyFilter = array ();
$historyStart = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_CUSTOMER_HISTORY );
2016-10-04 17:57:39 +03:00
if ( $historyStart && $historyStart > 0 ) {
2016-09-15 16:42:10 +03:00
$historyFilter [ 'sinceId' ] = $historyStart ;
}
2016-10-04 17:57:39 +03:00
while ( true ) {
2016-09-15 16:42:10 +03:00
try {
$customerHistory = $api -> customersHistory ( $historyFilter );
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::customerHistory' , 'RetailCrm\RestApi::customersHistory::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
return false ;
} catch ( InvalidArgumentException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::customerHistory' , 'RetailCrm\RestApi::customersHistory::InvalidArgumentException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
return false ;
}
$customerH = isset ( $customerHistory [ 'history' ]) ? $customerHistory [ 'history' ] : array ();
$log = new Logger ();
$log -> write ( $customerH , 'customerHistory' );
if ( count ( $customerH ) == 0 ){
return true ;
}
$customers = self :: assemblyCustomer ( $customerH );
$GLOBALS [ 'RETAIL_CRM_HISTORY' ] = true ;
$newUser = new CUser ;
2016-10-04 17:57:39 +03:00
foreach ( $customers as $customer ) {
2016-09-15 16:42:10 +03:00
if ( function_exists ( 'retailCrmBeforeCustomerSave' )) {
$newResCustomer = retailCrmBeforeCustomerSave ( $customer );
if ( is_array ( $newResCustomer ) && ! empty ( $newResCustomer )) {
$customer = $newResCustomer ;
}
}
2016-10-04 17:57:39 +03:00
if ( isset ( $customer [ 'deleted' ])) {
2016-09-15 16:42:10 +03:00
continue ;
}
if ( ! isset ( $customer [ 'externalId' ])) {
if ( ! isset ( $customer [ 'id' ])) {
continue ;
}
$registerNewUser = true ;
if ( ! isset ( $customer [ 'email' ]) || $customer [ 'email' ] == '' ) {
$login = $customer [ 'email' ] = uniqid ( 'user_' . time ()) . '@crm.com' ;
} else {
$dbUser = CUser :: GetList (( $by = 'ID' ), ( $sort = 'ASC' ), array ( '=EMAIL' => $customer [ 'email' ]));
switch ( $dbUser -> SelectedRowsCount ()) {
case 0 :
$login = $customer [ 'email' ];
break ;
case 1 :
$arUser = $dbUser -> Fetch ();
$registeredUserID = $arUser [ 'ID' ];
$registerNewUser = false ;
break ;
default :
$login = uniqid ( 'user_' . time ()) . '@crm.com' ;
break ;
}
}
if ( $registerNewUser === true ) {
$userPassword = uniqid ();
$arFields = array (
" EMAIL " => $customer [ 'email' ],
" LOGIN " => $login ,
" ACTIVE " => " Y " ,
" PASSWORD " => $userPassword ,
" CONFIRM_PASSWORD " => $userPassword
);
$registeredUserID = $newUser -> Add ( $arFields );
if ( $registeredUserID === false ) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'CUser::Register' , 'Error register user' );
continue ;
}
try {
$api -> customersFixExternalIds ( array ( array ( 'id' => $customer [ 'id' ], 'externalId' => $registeredUserID )));
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::customerFixExternalIds::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
continue ;
} catch ( InvalidArgumentException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::customerFixExternalIds::InvalidArgumentException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
continue ;
}
}
$customer [ 'externalId' ] = $registeredUserID ;
}
2016-10-04 17:57:39 +03:00
if ( isset ( $customer [ 'externalId' ])) {
2016-09-15 16:42:10 +03:00
$arUser = array ();
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'firstName' , $customer )) {
2016-09-15 16:42:10 +03:00
$arUser [ " NAME " ] = $customer [ 'firstName' ] ? RCrmActions :: fromJSON ( $customer [ 'firstName' ]) : '' ;
}
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'lastName' , $customer )) {
2016-09-15 16:42:10 +03:00
$arUser [ " LAST_NAME " ] = $customer [ 'lastName' ] ? RCrmActions :: fromJSON ( $customer [ 'lastName' ]) : '' ;
}
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'patronymic' , $customer )) {
2016-09-15 16:42:10 +03:00
$arUser [ " SECOND_NAME " ] = $customer [ 'patronymic' ] ? RCrmActions :: fromJSON ( $customer [ 'patronymic' ]) : '' ;
}
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'email' , $customer )) {
2016-09-15 16:42:10 +03:00
$arUser [ " EMAIL " ] = $customer [ 'email' ] ? RCrmActions :: fromJSON ( $customer [ 'email' ]) : '' ;
}
2016-10-04 17:57:39 +03:00
if ( isset ( $customer [ 'phones' ])) {
2016-09-15 16:42:10 +03:00
$user = CUser :: GetList (( $by = " ID " ), ( $order = " desc " ), array ( 'ID' => $customer [ 'externalId' ]), array ( 'FIELDS' => array ( 'PERSONAL_PHONE' , 'PERSONAL_MOBILE' ))) -> fetch ();
2016-10-04 17:57:39 +03:00
foreach ( $customer [ 'phones' ] as $phone ) {
if ( isset ( $phone [ 'old_number' ]) && in_array ( $phone [ 'old_number' ], $user )) {
2016-09-15 16:42:10 +03:00
$key = array_search ( $phone [ 'old_number' ], $user );
2016-10-04 17:57:39 +03:00
if ( isset ( $phone [ 'number' ])) {
2016-09-15 16:42:10 +03:00
$arUser [ $key ] = $phone [ 'number' ];
$user [ $key ] = $phone [ 'number' ];
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$arUser [ $key ] = '' ;
$user [ $key ] = '' ;
}
}
2016-10-04 17:57:39 +03:00
if ( isset ( $phone [ 'number' ])) {
if (( ! isset ( $user [ 'PERSONAL_PHONE' ]) || strlen ( $user [ 'PERSONAL_PHONE' ]) == 0 ) && $user [ 'PERSONAL_MOBILE' ] != $phone [ 'number' ]) {
2016-09-15 16:42:10 +03:00
$arUser [ 'PERSONAL_PHONE' ] = $phone [ 'number' ];
$user [ 'PERSONAL_PHONE' ] = $phone [ 'number' ];
continue ;
}
2016-10-04 17:57:39 +03:00
if (( ! isset ( $user [ 'PERSONAL_MOBILE' ]) || strlen ( $user [ 'PERSONAL_MOBILE' ]) == 0 ) && $user [ 'PERSONAL_PHONE' ] != $phone [ 'number' ]) {
2016-09-15 16:42:10 +03:00
$arUser [ 'PERSONAL_MOBILE' ] = $phone [ 'number' ];
$user [ 'PERSONAL_MOBILE' ] = $phone [ 'number' ];
continue ;
}
}
}
}
$u = $newUser -> Update ( $customer [ 'externalId' ], $arUser );
2016-10-04 17:57:39 +03:00
if ( ! $u ) {
2016-09-15 16:42:10 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::customerHistory' , 'Error update user' , $newUser -> LAST_ERROR );
}
if ( function_exists ( 'retailCrmAfterCustomerSave' )) {
retailCrmAfterCustomerSave ( $customer );
}
}
}
$GLOBALS [ 'RETAIL_CRM_HISTORY' ] = false ;
//запоминаем номер последнего изменения
$end = array_pop ( $customerH );
COption :: SetOptionString ( self :: $MODULE_ID , self :: $CRM_CUSTOMER_HISTORY , $end [ 'id' ]);
2016-10-04 17:57:39 +03:00
if ( $customerHistory [ 'pagination' ][ 'totalPageCount' ] == 1 ) {
2016-09-15 16:42:10 +03:00
return true ;
}
//новый фильтр для истории
$historyFilter [ 'sinceId' ] = $end [ 'id' ];
}
}
2016-10-04 17:57:39 +03:00
public static function orderHistory ()
{
2016-09-15 16:42:10 +03:00
global $USER ;
if ( is_object ( $USER ) == false ) {
$USER = new RetailUser ;
}
if ( ! CModule :: IncludeModule ( " iblock " )) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'iblock' , 'module not found' );
return false ;
}
if ( ! CModule :: IncludeModule ( " sale " )) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'sale' , 'module not found' );
return false ;
}
if ( ! CModule :: IncludeModule ( " catalog " )) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'catalog' , 'module not found' );
return false ;
}
$api_host = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_API_HOST_OPTION , 0 );
$api_key = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_API_KEY_OPTION , 0 );
$optionsOrderTypes = array_flip ( unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_ORDER_TYPES_ARR , 0 )));
$optionsDelivTypes = array_flip ( unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_DELIVERY_TYPES_ARR , 0 )));
$optionsPayTypes = array_flip ( unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_PAYMENT_TYPES , 0 )));
$optionsPayStatuses = array_flip ( unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_PAYMENT_STATUSES , 0 ))); // --statuses
$optionsPayment = array_flip ( unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_PAYMENT , 0 )));
$optionsOrderProps = unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_ORDER_PROPS , 0 ));
$optionsLegalDetails = unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_LEGAL_DETAILS , 0 ));
$optionsContragentType = unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_CONTRAGENT_TYPE , 0 ));
$optionsSitesList = unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_SITES_LIST , 0 ));
$optionsCustomFields = unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_CUSTOM_FIELDS , 0 ));
$optionsOrderNumbers = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_ORDER_NUMBERS , 0 );
$optionsCanselOrder = unserialize ( COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_CANSEL_ORDER , 0 ));
$api = new RetailCrm\ApiClient ( $api_host , $api_key );
$historyFilter = array ();
$historyStart = COption :: GetOptionString ( self :: $MODULE_ID , self :: $CRM_ORDER_HISTORY );
2016-10-04 17:57:39 +03:00
if ( $historyStart && $historyStart > 0 ) {
2016-09-15 16:42:10 +03:00
$historyFilter [ 'sinceId' ] = $historyStart ;
}
2016-10-04 17:57:39 +03:00
while ( true ) {
2016-09-15 16:42:10 +03:00
try {
$orderHistory = $api -> ordersHistory ( $historyFilter );
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::ordersHistory::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
return false ;
} catch ( InvalidArgumentException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::ordersHistory::InvalidArgumentException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
return false ;
}
$orderH = isset ( $orderHistory [ 'history' ]) ? $orderHistory [ 'history' ] : array ();
$log = new Logger ();
$log -> write ( $orderH , 'orderHistory' );
2016-10-04 17:57:39 +03:00
if ( count ( $orderH ) == 0 ) {
2016-09-15 16:42:10 +03:00
return true ;
}
$orders = self :: assemblyOrder ( $orderH );
$GLOBALS [ 'RETAIL_CRM_HISTORY' ] = true ;
//обработка заказа
foreach ( $orders as $order ) {
if ( function_exists ( 'retailCrmBeforeOrderSave' )) {
$newResOrder = retailCrmBeforeOrderSave ( $order );
if ( is_array ( $newResOrder ) && ! empty ( $newResOrder )) {
$order = $newResOrder ;
}
}
2016-10-14 15:25:02 +03:00
$log -> write ( $order , 'assemblyOrderHistory' );
2016-10-20 17:41:07 +03:00
if ( $order [ 'deleted' ]) {
2016-09-15 16:42:10 +03:00
continue ;
}
if ( ! isset ( $order [ 'externalId' ])) {
if ( ! isset ( $order [ 'customer' ][ 'externalId' ])) {
if ( ! isset ( $order [ 'customer' ][ 'id' ])) {
continue ;
}
$registerNewUser = true ;
if ( ! isset ( $order [ 'customer' ][ 'email' ]) || $order [ 'customer' ][ 'email' ] == '' ) {
$login = $order [ 'customer' ][ 'email' ] = uniqid ( 'user_' . time ()) . '@crm.com' ;
} else {
$dbUser = CUser :: GetList (( $by = 'ID' ), ( $sort = 'ASC' ), array ( '=EMAIL' => $order [ 'email' ]));
switch ( $dbUser -> SelectedRowsCount ()) {
case 0 :
$login = $order [ 'customer' ][ 'email' ];
break ;
case 1 :
$arUser = $dbUser -> Fetch ();
$registeredUserID = $arUser [ 'ID' ];
$registerNewUser = false ;
break ;
default :
$login = uniqid ( 'user_' . time ()) . '@crm.com' ;
break ;
}
}
if ( $registerNewUser === true ) {
$userPassword = uniqid ();
$newUser = new CUser ;
$arFields = array (
" NAME " => RCrmActions :: fromJSON ( $order [ 'customer' ][ 'firstName' ]),
" LAST_NAME " => RCrmActions :: fromJSON ( $order [ 'customer' ][ 'lastName' ]),
" SECOND_NAME " => RCrmActions :: fromJSON ( $order [ 'customer' ][ 'patronymic' ]),
" EMAIL " => $order [ 'customer' ][ 'email' ],
" LOGIN " => $login ,
" ACTIVE " => " Y " ,
" PASSWORD " => $userPassword ,
" CONFIRM_PASSWORD " => $userPassword
);
2016-10-04 17:57:39 +03:00
if ( $order [ 'customer' ][ 'phones' ][ 0 ]) {
2016-09-15 16:42:10 +03:00
$arFields [ 'PERSONAL_PHONE' ] = $order [ 'customer' ][ 'phones' ][ 0 ];
}
2016-10-04 17:57:39 +03:00
if ( $order [ 'customer' ][ 'phones' ][ 1 ]) {
2016-09-15 16:42:10 +03:00
$arFields [ 'PERSONAL_MOBILE' ] = $order [ 'customer' ][ 'phones' ][ 1 ];
}
2016-10-04 17:57:39 +03:00
2016-09-15 16:42:10 +03:00
$registeredUserID = $newUser -> Add ( $arFields );
2016-10-04 17:57:39 +03:00
2016-09-15 16:42:10 +03:00
if ( $registeredUserID === false ) {
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'CUser::Register' , 'Error register user' );
continue ;
}
try {
$api -> customersFixExternalIds ( array ( array ( 'id' => $order [ 'customer' ][ 'id' ], 'externalId' => $registeredUserID )));
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::customerFixExternalIds::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
continue ;
} catch ( InvalidArgumentException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::customerFixExternalIds::InvalidArgumentException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
continue ;
}
}
$order [ 'customer' ][ 'externalId' ] = $registeredUserID ;
}
2016-10-20 17:41:07 +03:00
if ( $optionsSitesList ) {
2016-09-15 16:42:10 +03:00
$site = array_search ( $order [ 'site' ], $optionsSitesList );
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$site = CSite :: GetDefSite ();
}
$newOrder = Bitrix\Sale\Order :: create ( $site , $order [ 'customer' ][ 'externalId' ]);
$newOrder = $newOrder -> save ();
$externalId = $newOrder -> getId ();
if ( isset ( $externalId )) {
try {
$api -> ordersFixExternalIds ( array ( array ( 'id' => $order [ 'id' ], 'externalId' => $externalId )));
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::orderFixExternalIds::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
continue ;
} catch ( InvalidArgumentException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::orderFixExternalIds::InvalidArgumentException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
continue ;
}
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'Bitrix\Sale\Order::create' , 'Error order create' );
}
$order [ 'externalId' ] = $externalId ;
}
if ( isset ( $order [ 'externalId' ]) && $order [ 'externalId' ]) {
2016-10-06 17:34:35 +03:00
$itemUpdate = false ;
2016-09-15 16:42:10 +03:00
$newOrder = Bitrix\Sale\Order :: load ( $order [ 'externalId' ]);
2016-10-03 16:56:59 +03:00
2016-10-04 17:57:39 +03:00
if ( ! $newOrder instanceof \Bitrix\Sale\Order ) {
2016-10-20 17:41:07 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'Bitrix\Sale\Order::load' , 'Error order load id=' . $order [ 'externalId' ]);
2016-09-15 16:42:10 +03:00
continue ;
}
2016-10-20 17:41:07 +03:00
if ( $optionsSitesList ) {
$site = array_search ( $order [ 'site' ], $optionsSitesList );
} else {
$site = CSite :: GetDefSite ();
}
2016-09-15 16:42:10 +03:00
2016-10-04 17:57:39 +03:00
if ( $optionsOrderNumbers == 'Y' && isset ( $order [ 'number' ])) {
2016-09-15 16:42:10 +03:00
$newOrder -> setField ( 'ACCOUNT_NUMBER' , $order [ 'number' ]);
2016-10-03 16:56:59 +03:00
}
2016-10-04 17:57:39 +03:00
2016-10-03 16:56:59 +03:00
$personType = $newOrder -> getField ( 'PERSON_TYPE_ID' );
2016-10-04 17:57:39 +03:00
if ( $optionsOrderTypes [ $order [ 'orderType' ]]) {
if ( $personType != $optionsOrderTypes [ $order [ 'orderType' ]] && $personType != 0 ) {
2016-10-03 16:56:59 +03:00
$propsRemove = true ;
}
2016-09-15 16:42:10 +03:00
$personType = $optionsOrderTypes [ $order [ 'orderType' ]];
$newOrder -> setField ( 'PERSON_TYPE_ID' , $personType );
2016-10-04 17:57:39 +03:00
} elseif ( $personType == 0 ) {
2016-10-03 16:56:59 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'orderType not found' , 'PERSON_TYPE_ID = 0' );
}
2016-09-15 16:42:10 +03:00
//status
2016-10-04 17:57:39 +03:00
if ( $optionsPayStatuses [ $order [ 'status' ]]) {
2016-09-15 16:42:10 +03:00
$newOrder -> setField ( 'STATUS_ID' , $optionsPayStatuses [ $order [ 'status' ]]);
2016-10-04 17:57:39 +03:00
if ( in_array ( $optionsPayStatuses [ $order [ 'status' ]], $optionsCanselOrder )) {
2016-10-14 15:25:02 +03:00
$newOrder -> setFieldNoDemand ( 'CANCELED' , 'Y' );
2016-10-04 17:57:39 +03:00
} else {
2016-10-14 15:25:02 +03:00
$newOrder -> setFieldNoDemand ( 'CANCELED' , 'N' );
2016-09-15 16:42:10 +03:00
}
}
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'statusComment' , $order )) {
2016-10-12 11:40:18 +03:00
self :: setProp ( $newOrder , RCrmActions :: fromJSON ( $order [ 'statusComment' ]), 'REASON_CANCELED' );
2016-10-03 16:56:59 +03:00
}
2016-09-15 16:42:10 +03:00
$propertyCollection = $newOrder -> getPropertyCollection ();
$propertyCollectionArr = $propertyCollection -> getArray ();
2016-10-03 16:56:59 +03:00
$nProps = array ();
2016-10-04 17:57:39 +03:00
foreach ( $propertyCollectionArr [ 'properties' ] as $orderProp ) {
if ( $orderProp [ 'ID' ][ 0 ] == 'n' ) {
2016-10-03 16:56:59 +03:00
$orderProp [ 'ID' ] = substr ( $orderProp [ 'ID' ], 1 );
$orderProp [ 'ID' ] = $propertyCollection -> getItemById ( $orderProp [ 'ID' ]) -> getField ( 'ORDER_PROPS_ID' );
}
$nProps [] = $orderProp ;
}
$propertyCollectionArr [ 'properties' ] = $nProps ;
2016-10-04 17:57:39 +03:00
if ( $propsRemove ) { //удаляем старые свойства
foreach ( $propertyCollectionArr [ 'properties' ] as $orderProp ) {
2016-10-03 16:56:59 +03:00
$somePropValue = $propertyCollection -> getItemByOrderPropertyId ( $orderProp [ 'ID' ]);
self :: setProp ( $somePropValue );
}
try {
$orderCrm = $api -> ordersGet ( $order [ 'id' ], 'id' );
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::ordersGet0::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
}
$orderDump = $order ;
$order = $orderCrm [ 'order' ];
}
2016-09-15 16:42:10 +03:00
$propsKey = array ();
2016-10-04 17:57:39 +03:00
foreach ( $propertyCollectionArr [ 'properties' ] as $prop ) {
2016-09-15 16:42:10 +03:00
$propsKey [ $prop [ 'CODE' ]][ 'ID' ] = $prop [ 'ID' ];
2016-10-03 16:56:59 +03:00
$propsKey [ $prop [ 'CODE' ]][ 'TYPE' ] = $prop [ 'TYPE' ];
2016-09-15 16:42:10 +03:00
}
//fio
2016-10-04 17:57:39 +03:00
if ( $order [ 'firstName' ] || $order [ 'lastName' ] || $order [ 'patronymic' ]) {
2016-09-15 16:42:10 +03:00
$fio = '' ;
2016-10-04 17:57:39 +03:00
foreach ( $propertyCollectionArr [ 'properties' ] as $prop ) {
if ( in_array ( $optionsOrderProps [ $personType ][ 'fio' ], $prop )) {
2016-10-14 15:25:02 +03:00
$getFio = $newOrder -> getPropertyCollection () -> getItemByOrderPropertyId ( $prop [ 'ID' ]);
if ( method_exists ( $getFio , 'getValue' )) {
$fio = $getFio -> getValue ();
}
2016-09-15 16:42:10 +03:00
}
}
$fio = RCrmActions :: explodeFIO ( $fio );
2016-10-12 11:40:18 +03:00
$newFio = array ();
2016-10-04 17:57:39 +03:00
if ( $fio ) {
2016-10-12 11:40:18 +03:00
$newFio [] = isset ( $order [ 'lastName' ]) ? RCrmActions :: fromJSON ( $order [ 'lastName' ]) : ( isset ( $fio [ 'lastName' ]) ? $fio [ 'lastName' ] : '' );
$newFio [] = isset ( $order [ 'firstName' ]) ? RCrmActions :: fromJSON ( $order [ 'firstName' ]) : ( isset ( $fio [ 'firstName' ]) ? $fio [ 'firstName' ] : '' );
$newFio [] = isset ( $order [ 'patronymic' ]) ? RCrmActions :: fromJSON ( $order [ 'patronymic' ]) : ( isset ( $fio [ 'patronymic' ]) ? $fio [ 'patronymic' ] : '' );
$order [ 'fio' ] = trim ( implode ( ' ' , $newFio ));
2016-10-04 17:57:39 +03:00
} else {
2016-10-12 11:40:18 +03:00
$newFio [] = isset ( $order [ 'lastName' ]) ? RCrmActions :: fromJSON ( $order [ 'lastName' ]) : '' ;
$newFio [] = isset ( $order [ 'firstName' ]) ? RCrmActions :: fromJSON ( $order [ 'firstName' ]) : '' ;
$newFio [] = isset ( $order [ 'patronymic' ]) ? RCrmActions :: fromJSON ( $order [ 'patronymic' ]) : '' ;
$order [ 'fio' ] = trim ( implode ( ' ' , $newFio ));
2016-09-15 16:42:10 +03:00
}
}
//optionsOrderProps
2016-10-04 17:57:39 +03:00
if ( $optionsOrderProps [ $personType ]) {
foreach ( $optionsOrderProps [ $personType ] as $key => $orderProp ) {
if ( array_key_exists ( $key , $order )) {
2016-09-15 16:42:10 +03:00
$somePropValue = $propertyCollection -> getItemByOrderPropertyId ( $propsKey [ $orderProp ][ 'ID' ]);
2016-10-12 11:40:18 +03:00
self :: setProp ( $somePropValue , RCrmActions :: fromJSON ( $order [ $key ]));
2016-10-04 17:57:39 +03:00
} elseif ( array_key_exists ( $key , $order [ 'delivery' ][ 'address' ])) {
if ( $propsKey [ $key ][ 'TYPE' ] == 'LOCATION' ) {
2016-10-12 11:40:18 +03:00
$parameters [ 'filter' ][ 'NAME' ] = RCrmActions :: fromJSON ( $order [ 'delivery' ][ 'address' ][ $key ]);
2016-09-15 16:42:10 +03:00
$parameters [ 'filter' ][ 'LANGUAGE_ID' ] = 'ru' ;
$location = \Bitrix\Sale\Location\LocationTable :: getListFast ( $parameters ) -> fetch ();
$somePropValue = $propertyCollection -> getItemByOrderPropertyId ( $propsKey [ $orderProp ][ 'ID' ]);
self :: setProp ( $somePropValue , $location [ 'CODE' ]);
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$somePropValue = $propertyCollection -> getItemByOrderPropertyId ( $propsKey [ $orderProp ][ 'ID' ]);
2016-10-12 11:40:18 +03:00
self :: setProp ( $somePropValue , RCrmActions :: fromJSON ( $order [ 'delivery' ][ 'address' ][ $key ]));
2016-09-15 16:42:10 +03:00
}
}
}
}
//optionsLegalDetails
2016-10-04 17:57:39 +03:00
if ( $optionsLegalDetails [ $personType ]) {
foreach ( $optionsLegalDetails [ $personType ] as $key => $orderProp ) {
if ( array_key_exists ( $key , $order )) {
2016-10-03 16:56:59 +03:00
$somePropValue = $propertyCollection -> getItemByOrderPropertyId ( $propsKey [ $orderProp ][ 'ID' ]);
2016-09-15 16:42:10 +03:00
self :: setProp ( $somePropValue , $order [ $key ]);
}
}
}
2016-10-04 17:57:39 +03:00
if ( $propsRemove ) {
2016-10-03 16:56:59 +03:00
$order = $orderDump ;
}
2016-09-15 16:42:10 +03:00
//paymentStatus
2016-10-04 17:57:39 +03:00
if ( $optionsPayment [ $order [ 'paymentStatus' ]]) {
2016-10-03 16:56:59 +03:00
$newOrder -> setFieldNoDemand ( 'PAYED' , $optionsPayment [ $order [ 'paymentStatus' ]]);
2016-09-15 16:42:10 +03:00
}
//comments
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'customerComment' , $order )) {
2016-10-12 11:40:18 +03:00
self :: setProp ( $newOrder , RCrmActions :: fromJSON ( $order [ 'customerComment' ]), 'USER_DESCRIPTION' );
2016-09-15 16:42:10 +03:00
}
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'managerComment' , $order )) {
2016-10-12 11:40:18 +03:00
self :: setProp ( $newOrder , RCrmActions :: fromJSON ( $order [ 'managerComment' ]), 'COMMENTS' );
2016-09-15 16:42:10 +03:00
}
2016-10-03 16:56:59 +03:00
2016-09-15 16:42:10 +03:00
//items
$basket = $newOrder -> getBasket ();
2016-10-06 17:34:35 +03:00
if ( isset ( $order [ 'items' ])) {
$itemUpdate = true ;
foreach ( $order [ 'items' ] as $product ) {
$item = self :: getExistsItem ( $basket , 'catalog' , $product [ 'offer' ][ 'externalId' ]);
if ( ! $item ) {
if ( $product [ 'delete' ]){
continue ;
}
$item = $basket -> createItem ( 'catalog' , $product [ 'offer' ][ 'externalId' ]);
2016-10-20 13:16:59 +03:00
if ( $item instanceof \Bitrix\Sale\BasketItem ) {
2016-10-12 11:40:18 +03:00
$elem = self :: getInfoElement ( $product [ 'offer' ][ 'externalId' ]);
2016-10-06 17:34:35 +03:00
$item -> setFields ( array (
'CURRENCY' => \Bitrix\Currency\CurrencyManager :: getBaseCurrency (),
2016-10-20 17:41:07 +03:00
'LID' => $site ,
2016-10-06 17:34:35 +03:00
'BASE_PRICE' => $product [ 'initialPrice' ],
2016-10-12 11:40:18 +03:00
'NAME' => $product [ 'name' ] ? RCrmActions :: fromJSON ( $product [ 'name' ]) : $elem [ 'NAME' ],
2016-10-06 17:34:35 +03:00
'DETAIL_PAGE_URL' => $elem [ 'URL' ]
));
} else {
2016-10-20 13:16:59 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::orderHistory' , 'createItem' , 'Error item id=' . $product [ 'offer' ][ 'externalId' ] . ' add in order id=' . $order [ 'externalId' ]);
2016-10-06 17:34:35 +03:00
continue ;
}
}
if ( $product [ 'delete' ]) {
$item -> delete ();
2016-10-03 16:56:59 +03:00
continue ;
}
2016-09-15 16:42:10 +03:00
2016-10-06 17:34:35 +03:00
if ( $product [ 'quantity' ]) {
$item -> setFieldNoDemand ( 'QUANTITY' , $product [ 'quantity' ]);
2016-09-15 16:42:10 +03:00
}
2016-10-06 17:34:35 +03:00
if ( array_key_exists ( 'discount' , $product ) || array_key_exists ( 'discountPercent' , $product )) {
if ( ! isset ( $orderCrm )) {
try {
$orderCrm = $api -> ordersGet ( $order [ 'id' ], 'id' );
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::ordersGet::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
}
2016-09-15 16:42:10 +03:00
}
2016-10-06 17:34:35 +03:00
foreach ( $orderCrm [ 'order' ][ 'items' ] as $itemCrm ) {
if ( $itemCrm [ 'offer' ][ 'externalId' ] == $product [ 'offer' ][ 'externalId' ]) {
$itemCost = $itemCrm [ 'initialPrice' ] - $itemCrm [ 'discount' ] - round (( $itemCrm [ 'initialPrice' ] / 100 * $itemCrm [ 'discountPercent' ]), 2 );
break ;
}
}
if ( isset ( $itemCost ) && $itemCost > 0 ) {
$item -> setField ( 'CUSTOM_PRICE' , 'Y' );
$item -> setField ( 'PRICE' , $itemCost );
$item -> setField ( 'DISCOUNT_NAME' , '' );
$item -> setField ( 'DISCOUNT_VALUE' , '' );
}
2016-09-15 16:42:10 +03:00
}
2016-10-06 17:34:35 +03:00
$basket -> save ();
2016-09-15 16:42:10 +03:00
}
}
$orderSumm = 0 ;
2016-10-04 17:57:39 +03:00
foreach ( $basket as $item ) {
2016-09-15 16:42:10 +03:00
$orderSumm += $item -> getFinalPrice ();
}
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'cost' , $order [ 'delivery' ])) {
2016-09-15 16:42:10 +03:00
$deliverySumm = $order [ 'delivery' ][ 'cost' ];
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$deliverySumm = $newOrder -> getDeliveryPrice ();
}
$orderSumm += $deliverySumm ;
$newOrder -> setField ( 'PRICE' , $orderSumm );
$order [ 'summ' ] = $orderSumm ;
$newOrder -> save ();
//payment
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'paymentType' , $order )) {
2016-09-15 16:42:10 +03:00
self :: paySystemUpdate ( $order , $optionsPayTypes );
}
//delivery
2016-10-06 17:34:35 +03:00
if ( array_key_exists ( 'code' , $order [ 'delivery' ])) {
$itemUpdate = true ;
2016-09-15 16:42:10 +03:00
//если пусто, удаляем, если нет, update или add
2016-10-04 17:57:39 +03:00
if ( ! isset ( $orderCrm )) {
2016-09-15 16:42:10 +03:00
try {
$orderCrm = $api -> ordersGet ( $order [ 'id' ], 'id' );
} catch ( \RetailCrm\Exception\CurlException $e ) {
RCrmActions :: eventLog (
'RetailCrmHistory::orderHistory' , 'RetailCrm\RestApi::ordersGet2::CurlException' ,
$e -> getCode () . ': ' . $e -> getMessage ()
);
}
}
self :: shipmentUpdate ( $orderCrm [ 'order' ], $optionsDelivTypes );
}
2016-10-04 17:57:39 +03:00
if ( isset ( $orderCrm )) {
2016-09-15 16:42:10 +03:00
unset ( $orderCrm );
}
//delivery cost
2016-10-04 17:57:39 +03:00
if ( array_key_exists ( 'cost' , $order [ 'delivery' ])) {
2016-10-20 13:16:59 +03:00
$shipment = Bitrix\Sale\Internals\ShipmentTable :: getList ( array (
2016-09-15 16:42:10 +03:00
'filter' => array ( 'ORDER_ID' => $order [ 'externalId' ], 'SYSTEM' => 'N' ),
'order' => array ( 'ID' )
)) -> fetch ();
2016-10-04 17:57:39 +03:00
if ( $shipment ) {
2016-09-15 16:42:10 +03:00
Bitrix\Sale\Internals\ShipmentTable :: update ( $shipment [ 'ID' ], array ( 'BASE_PRICE_DELIVERY' => $order [ 'delivery' ][ 'cost' ], 'PRICE_DELIVERY' => $order [ 'delivery' ][ 'cost' ], 'CUSTOM_PRICE_DELIVERY' => 'Y' ));
}
Bitrix\Sale\OrderTable :: update ( $order [ 'externalId' ], array ( 'PRICE_DELIVERY' => $order [ 'delivery' ][ 'cost' ])); //не пишется в историю, надо добавить
}
Bitrix\Sale\OrderTable :: update ( $order [ 'externalId' ], array ( 'MARKED' => 'N' , 'EMP_MARKED_ID' => '' , 'REASON_MARKED' => '' ));
2016-10-04 17:57:39 +03:00
2016-10-06 17:34:35 +03:00
if ( $itemUpdate ) {
self :: updateShipmentItem ( $order [ 'externalId' ]);
}
2016-10-04 17:57:39 +03:00
2016-09-15 16:42:10 +03:00
if ( function_exists ( 'retailCrmAfterOrderSave' )) {
retailCrmAfterOrderSave ( $order );
}
}
}
$GLOBALS [ 'RETAIL_CRM_HISTORY' ] = false ;
//запоминаем номер последнего изменения
$end = array_pop ( $orderH );
COption :: SetOptionString ( self :: $MODULE_ID , self :: $CRM_ORDER_HISTORY , $end [ 'id' ]);
2016-10-04 17:57:39 +03:00
if ( $orderHistory [ 'pagination' ][ 'totalPageCount' ] == 1 ) {
2016-09-15 16:42:10 +03:00
return true ;
}
//новый фильтр для истории
$historyFilter [ 'sinceId' ] = $end [ 'id' ];
}
}
2016-10-04 17:57:39 +03:00
public static function assemblyCustomer ( $customerHistory )
{
2016-09-15 16:42:10 +03:00
$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' );
2016-10-04 17:57:39 +03:00
foreach ( $objects -> fields -> field as $object ) {
2016-09-15 16:42:10 +03:00
$fields [( string ) $object [ " group " ]][( string ) $object [ " id " ]] = ( string ) $object ;
}
}
$customers = array ();
foreach ( $customerHistory as $change ) {
$change [ 'customer' ] = self :: removeEmpty ( $change [ 'customer' ]);
2016-10-04 17:57:39 +03:00
if ( $customers [ $change [ 'customer' ][ 'id' ]]) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]] = array_merge ( $customers [ $change [ 'customer' ][ 'id' ]], $change [ 'customer' ]);
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]] = $change [ 'customer' ];
}
2016-10-04 17:57:39 +03:00
if ( $change [ 'customer' ][ 'contragent' ][ 'contragentType' ]) {
2016-09-15 16:42:10 +03:00
$change [ 'customer' ][ 'contragentType' ] = self :: newValue ( $change [ 'customer' ][ 'contragent' ][ 'contragentType' ]);
unset ( $change [ 'customer' ][ 'contragent' ]);
}
2016-10-04 17:57:39 +03:00
if ( $fields [ 'customer' ][ $change [ 'field' ]] == 'phones' ) {
2016-09-15 16:42:10 +03:00
$key = count ( $customers [ $change [ 'customer' ][ 'id' ]][ 'phones' ]);
2016-10-04 17:57:39 +03:00
if ( isset ( $change [ 'oldValue' ])) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ 'phones' ][ $key ][ 'old_number' ] = $change [ 'oldValue' ];
}
2016-10-04 17:57:39 +03:00
if ( isset ( $change [ 'newValue' ])) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ 'phones' ][ $key ][ 'number' ] = $change [ 'newValue' ];
}
2016-10-04 17:57:39 +03:00
} else {
if ( $fields [ 'customerAddress' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ 'address' ][ $fields [ 'customerAddress' ][ $change [ 'field' ]]] = $change [ 'newValue' ];
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'customerContragent' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ 'contragent' ][ $fields [ 'customerContragent' ][ $change [ 'field' ]]] = $change [ 'newValue' ];
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'customer' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ $fields [ 'customer' ][ $change [ 'field' ]]] = self :: newValue ( $change [ 'newValue' ]);
}
2016-10-04 17:57:39 +03:00
if ( isset ( $change [ 'created' ])) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ 'create' ] = 1 ;
}
2016-10-04 17:57:39 +03:00
if ( isset ( $change [ 'deleted' ])) {
2016-09-15 16:42:10 +03:00
$customers [ $change [ 'customer' ][ 'id' ]][ 'deleted' ] = 1 ;
}
}
}
2016-10-04 17:57:39 +03:00
2016-09-15 16:42:10 +03:00
return $customers ;
}
2016-10-04 17:57:39 +03:00
public static function assemblyOrder ( $orderHistory )
{
2016-09-15 16:42:10 +03:00
$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' );
2016-10-04 17:57:39 +03:00
foreach ( $objects -> fields -> field as $object ) {
2016-09-15 16:42:10 +03:00
$fields [( string ) $object [ " group " ]][( string ) $object [ " id " ]] = ( string ) $object ;
}
}
$orders = array ();
foreach ( $orderHistory as $change ) {
$change [ 'order' ] = self :: removeEmpty ( $change [ 'order' ]);
2016-10-04 17:57:39 +03:00
if ( $change [ 'order' ][ 'items' ]) {
2016-09-15 16:42:10 +03:00
$items = array ();
2016-10-04 17:57:39 +03:00
foreach ( $change [ 'order' ][ 'items' ] as $item ) {
if ( isset ( $change [ 'created' ])) {
2016-09-15 16:42:10 +03:00
$item [ 'create' ] = 1 ;
}
$items [ $item [ 'id' ]] = $item ;
}
$change [ 'order' ][ 'items' ] = $items ;
}
2016-10-04 17:57:39 +03:00
if ( $change [ 'order' ][ 'contragent' ][ 'contragentType' ]) {
2016-09-15 16:42:10 +03:00
$change [ 'order' ][ 'contragentType' ] = self :: newValue ( $change [ 'order' ][ 'contragent' ][ 'contragentType' ]);
unset ( $change [ 'order' ][ 'contragent' ]);
}
2016-10-04 17:57:39 +03:00
if ( $orders [ $change [ 'order' ][ 'id' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]] = array_merge ( $orders [ $change [ 'order' ][ 'id' ]], $change [ 'order' ]);
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]] = $change [ 'order' ];
}
2016-10-04 17:57:39 +03:00
if ( $change [ 'item' ]) {
if ( $orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]] = array_merge ( $orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]], $change [ 'item' ]);
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]] = $change [ 'item' ];
}
2016-10-04 17:57:39 +03:00
if ( empty ( $change [ 'oldValue' ]) && $change [ 'field' ] == 'order_product' ) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]][ 'create' ] = 1 ;
unset ( $orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]][ 'delete' ]);
}
2016-10-04 17:57:39 +03:00
if ( empty ( $change [ 'newValue' ]) && $change [ 'field' ] == 'order_product' ) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]][ 'delete' ] = 1 ;
}
2016-10-04 17:57:39 +03:00
if ( ! $orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]][ 'create' ] && $fields [ 'item' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'items' ][ $change [ 'item' ][ 'id' ]][ $fields [ 'item' ][ $change [ 'field' ]]] = $change [ 'newValue' ];
}
2016-10-04 17:57:39 +03:00
} else {
if ( $fields [ 'delivery' ][ $change [ 'field' ]] == 'service' ) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'delivery' ][ 'service' ][ 'code' ] = self :: newValue ( $change [ 'newValue' ]);
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'delivery' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'delivery' ][ $fields [ 'delivery' ][ $change [ 'field' ]]] = self :: newValue ( $change [ 'newValue' ]);
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'orderAddress' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'delivery' ][ 'address' ][ $fields [ 'orderAddress' ][ $change [ 'field' ]]] = $change [ 'newValue' ];
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'integrationDelivery' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'delivery' ][ 'service' ][ $fields [ 'integrationDelivery' ][ $change [ 'field' ]]] = self :: newValue ( $change [ 'newValue' ]);
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'customerContragent' ][ $change [ 'field' ]]) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ $fields [ 'customerContragent' ][ $change [ 'field' ]]] = self :: newValue ( $change [ 'newValue' ]);
2016-10-04 17:57:39 +03:00
} elseif ( strripos ( $change [ 'field' ], 'custom_' ) !== false ) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'customFields' ][ str_replace ( 'custom_' , '' , $change [ 'field' ])] = self :: newValue ( $change [ 'newValue' ]);
2016-10-04 17:57:39 +03:00
} elseif ( $fields [ 'order' ][ $change [ 'field' ]]){
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ $fields [ 'order' ][ $change [ 'field' ]]] = self :: newValue ( $change [ 'newValue' ]);
}
2016-10-04 17:57:39 +03:00
if ( isset ( $change [ 'created' ])) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'create' ] = 1 ;
}
2016-10-04 17:57:39 +03:00
if ( isset ( $change [ 'deleted' ])) {
2016-09-15 16:42:10 +03:00
$orders [ $change [ 'order' ][ 'id' ]][ 'deleted' ] = 1 ;
}
}
}
2016-10-04 17:57:39 +03:00
2016-09-15 16:42:10 +03:00
return $orders ;
}
2016-10-04 17:57:39 +03:00
public static function shipmentUpdate ( $orderCrm , $optionsDelivTypes )
{
if ( isset ( $orderCrm [ 'delivery' ][ 'code' ])) {
2016-09-15 16:42:10 +03:00
$crmCode = $orderCrm [ 'delivery' ][ 'code' ];
2016-10-04 17:57:39 +03:00
if ( isset ( $orderCrm [ 'delivery' ][ 'data' ][ 'deliveryType' ])) {
2016-09-15 16:42:10 +03:00
$crmService = $orderCrm [ 'delivery' ][ 'data' ][ 'deliveryType' ];
2016-10-04 17:57:39 +03:00
} elseif ( isset ( $orderCrm [ 'delivery' ][ 'service' ])) {
2016-09-15 16:42:10 +03:00
$crmService = $orderCrm [ 'delivery' ][ 'service' ];
}
//подбираем код битриксового сервиса
$arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager :: getActiveList ();
2016-10-04 17:57:39 +03:00
foreach ( $arDeliveryServiceAll as $arDeliveryService ) {
2016-09-15 16:42:10 +03:00
$arDeliveryCode [ $arDeliveryService [ 'CODE' ]] = $arDeliveryService [ 'ID' ];
$arDeliveryID [ $arDeliveryService [ 'ID' ]] = $arDeliveryService ;
2016-10-04 17:57:39 +03:00
if ( $arDeliveryService [ 'ID' ] == $optionsDelivTypes [ $crmCode ]) {
2016-09-15 16:42:10 +03:00
$dCode = $arDeliveryService [ 'CODE' ] . ':' . $crmService ;
}
}
//будем менять доставку на этот id
2016-10-04 17:57:39 +03:00
if ( $crmService && $arDeliveryCode [ $dCode ]) {
2016-09-15 16:42:10 +03:00
$nowDelivery = $arDeliveryCode [ $dCode ];
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$nowDelivery = $optionsDelivTypes [ $crmCode ];
}
//найти текущую доставку в заказе
$cnt = Bitrix\Sale\Internals\ShipmentTable :: getCount ( array ( 'ORDER_ID' => $orderCrm [ 'externalId' ]));
2016-10-04 17:57:39 +03:00
if ( $cnt > 0 ) { //обновляем
2016-10-20 13:16:59 +03:00
$obDeliverys = \Bitrix\Sale\Internals\ShipmentTable :: getList ( array ( 'filter' => array ( 'ORDER_ID' => $orderCrm [ 'externalId' ]),
2016-09-15 16:42:10 +03:00
'order' => array ( 'ID' )));
2016-10-04 17:57:39 +03:00
while ( $arDelivery = $obDeliverys -> fetch ()) {
if ( $arDelivery [ 'DELIVERY_ID' ] != $nowDelivery ) {
2016-09-15 16:42:10 +03:00
\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' ]));
}
}
2016-10-04 17:57:39 +03:00
} else { //создаем
2016-09-15 16:42:10 +03:00
\Bitrix\Sale\OrderTable :: update ( $orderCrm [ 'externalId' ], array ( 'DELIVERY_ID' => $nowDelivery ));
$shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable :: add ( array (
'ORDER_ID' => $orderCrm [ 'externalId' ],
'STATUS_ID' => 'DN' ,
'CUSTOM_PRICE_DELIVERY' => 'N' ,
'ALLOW_DELIVERY' => 'N' ,
'DEDUCTED' => 'N' ,
'RESERVED' => 'N' ,
'DELIVERY_ID' => $nowDelivery ,
'DELIVERY_NAME' => $nowDelivery [ $nowDelivery ][ 'NAME' ],
'CANCELED' => 'N' ,
'MARKED' => 'N' ,
'SYSTEM' => 'Y' ,
'ACCOUNT_NUMBER' => $orderCrm [ 'externalId' ] . '/1' ,
'EXTERNAL_DELIVERY' => 'N' ,
'UPDATED_1C' => 'N' ,
'DATE_INSERT' => new \Bitrix\Main\Type\DateTime ()
));
$shipment = Bitrix\Sale\Internals\ShipmentTable :: add ( array (
'ORDER_ID' => $orderCrm [ 'externalId' ],
'STATUS_ID' => 'DN' ,
'PRICE_DELIVERY' => 0 ,
'BASE_PRICE_DELIVERY' => 0 ,
'CUSTOM_PRICE_DELIVERY' => 'N' ,
'ALLOW_DELIVERY' => 'N' ,
'DEDUCTED' => 'N' ,
'RESERVED' => 'N' ,
'DELIVERY_ID' => $nowDelivery ,
'DELIVERY_NAME' => $arDeliveryID [ $nowDelivery ][ 'NAME' ],
'CANCELED' => 'N' ,
'MARKED' => 'N' ,
'CURRENCY' => \Bitrix\Currency\CurrencyManager :: getBaseCurrency (),
'SYSTEM' => 'N' ,
'ACCOUNT_NUMBER' => $orderCrm [ 'externalId' ] . '/2' ,
'EXTERNAL_DELIVERY' => 'N' ,
'UPDATED_1C' => 'N' ,
'DATE_INSERT' => new \Bitrix\Main\Type\DateTime ()
));
}
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
//ищем у заказа на сайте доставки и удаляем/заменяем на без доставки
$noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService :: getEmptyDeliveryServiceId ();
\Bitrix\Sale\OrderTable :: update ( $orderCrm [ 'externalId' ], array ( 'DELIVERY_ID' => $noOrderId ));
2016-10-20 13:16:59 +03:00
$obDeliverys = Bitrix\Sale\Internals\ShipmentTable :: getList ( array ( 'filter' => array ( 'ORDER_ID' => $orderCrm [ 'externalId' ]),
2016-09-15 16:42:10 +03:00
'order' => array ( 'ID' )));
$create = true ;
2016-10-04 17:57:39 +03:00
while ( $arDelivery = $obDeliverys -> fetch ()) {
2016-09-15 16:42:10 +03:00
\Bitrix\Sale\Internals\ShipmentTable :: update ( $arDelivery [ 'ID' ], array ( 'DELIVERY_ID' => $noOrderId , 'DELIVERY_NAME' => 'Без доставки' ));
$create = false ;
}
2016-10-04 17:57:39 +03:00
if ( $create ) {
2016-09-15 16:42:10 +03:00
$shipmentSystem = \Bitrix\Sale\Internals\ShipmentTable :: add ( array (
'ORDER_ID' => $orderCrm [ 'externalId' ],
'STATUS_ID' => 'DN' ,
'CUSTOM_PRICE_DELIVERY' => 'N' ,
'ALLOW_DELIVERY' => 'N' ,
'DEDUCTED' => 'N' ,
'RESERVED' => 'N' ,
'DELIVERY_ID' => $nowDelivery ,
'DELIVERY_NAME' => $nowDelivery [ $nowDelivery ][ 'NAME' ],
'CANCELED' => 'N' ,
'MARKED' => 'N' ,
'SYSTEM' => 'Y' ,
'ACCOUNT_NUMBER' => $orderCrm [ 'externalId' ] . '/1' ,
'EXTERNAL_DELIVERY' => 'N' ,
'UPDATED_1C' => 'N' ,
'DATE_INSERT' => new \Bitrix\Main\Type\DateTime ()
));
$shipment = Bitrix\Sale\Internals\ShipmentTable :: add ( array (
'ORDER_ID' => $orderCrm [ 'externalId' ],
'STATUS_ID' => 'DN' ,
'PRICE_DELIVERY' => 0 ,
'BASE_PRICE_DELIVERY' => 0 ,
'CUSTOM_PRICE_DELIVERY' => 'N' ,
'ALLOW_DELIVERY' => 'N' ,
'DEDUCTED' => 'N' ,
'RESERVED' => 'N' ,
'DELIVERY_ID' => $nowDelivery ,
'DELIVERY_NAME' => $arDeliveryID [ $nowDelivery ][ 'NAME' ],
'CANCELED' => 'N' ,
'MARKED' => 'N' ,
'CURRENCY' => \Bitrix\Currency\CurrencyManager :: getBaseCurrency (),
'SYSTEM' => 'N' ,
'ACCOUNT_NUMBER' => $orderCrm [ 'externalId' ] . '/2' ,
'EXTERNAL_DELIVERY' => 'N' ,
'UPDATED_1C' => 'N' ,
'DATE_INSERT' => new \Bitrix\Main\Type\DateTime ()
));
}
}
return true ;
}
2016-10-04 17:57:39 +03:00
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' ]]) {
2016-09-15 16:42:10 +03:00
$paymentList = RCrmActions :: PaymentList ();
$arPayments = array ();
$arPaymentsName = array ();
2016-10-04 17:57:39 +03:00
foreach ( $paymentList as $payment ) {
2016-09-15 16:42:10 +03:00
$arPayments [] = $payment [ 'ID' ];
$arPaymentsName [ $payment [ 'ID' ]] = $payment [ 'NAME' ];
}
2016-10-04 17:57:39 +03:00
if ( in_array ( $optionsPayment [ $order [ 'paymentType' ]], $arPayments )) {
2016-09-15 16:42:10 +03:00
\Bitrix\Sale\OrderTable :: update ( $order [ 'externalId' ], array ( 'PAY_SYSTEM_ID' => $optionsPayment [ $order [ 'paymentType' ]]));
2016-10-20 13:16:59 +03:00
$payment = \Bitrix\Sale\Internals\PaymentTable :: getList ( array (
2016-09-15 16:42:10 +03:00
'filter' => array ( 'ORDER_ID' => $order [ 'externalId' ]),
'order' => array ( 'ID' )
)) -> fetch ();
2016-10-04 17:57:39 +03:00
if ( $payment ) { //если уже существует, update
2016-09-15 16:42:10 +03:00
\Bitrix\Sale\Internals\PaymentTable :: update ( $payment [ 'ID' ], array ( 'PAY_SYSTEM_ID' => $optionsPayment [ $order [ 'paymentType' ]], 'PAY_SYSTEM_NAME' => $arPaymentsName [ $optionsPayment [ $order [ 'paymentType' ]]], 'SUM' => $order [ 'summ' ]));
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
\Bitrix\Sale\Internals\PaymentTable :: add ( array (
'ORDER_ID' => $order [ 'externalId' ],
'PAID' => 'N' ,
'PAY_SYSTEM_ID' => $optionsPayment [ $order [ 'paymentType' ]],
'SUM' => $order [ 'summ' ],
'CURRENCY' => \Bitrix\Currency\CurrencyManager :: getBaseCurrency (),
'PAY_SYSTEM_NAME' => $arPaymentsName [ $optionsPayment [ $order [ 'paymentType' ]]],
'IS_RETURN' => 'N' ,
'ACCOUNT_NUMBER' => $order [ 'externalId' ] . '/1' ,
'PRICE_COD' => '0.00' ,
'EXTERNAL_PAYMENT' => 'N' ,
'UPDATED_1C' => 'N'
));
}
//запись в историю
2016-10-04 17:57:39 +03:00
} else { //ошибка, нет такой активной платежной системы
2016-10-20 17:41:07 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::paySystemUpdate' , 'RCrmActions::PaymentList()' , 'Error paySystem not found in order id=' . $order [ 'externalId' ]);
2016-09-15 16:42:10 +03:00
}
2016-10-04 17:57:39 +03:00
} else { //ошибка, возможно платежная система не сопоставлена
2016-10-20 17:41:07 +03:00
RCrmActions :: eventLog ( 'RetailCrmHistory::paySystemUpdate' , 'RCrmActions::PaymentList()' , 'Error paySystem not found in option in order id=' . $order [ 'externalId' ]);;
2016-09-15 16:42:10 +03:00
}
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
\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 ();
2016-10-04 17:57:39 +03:00
if ( $payment [ 'ID' ]) {
2016-09-15 16:42:10 +03:00
\Bitrix\Sale\Internals\PaymentTable :: delete ( $payment [ 'ID' ]);
}
//запись в историю
}
}
2016-10-04 17:57:39 +03:00
public static function newValue ( $value )
{
2016-10-12 11:40:18 +03:00
if ( array_key_exists ( 'code' , $value )) {
2016-09-15 16:42:10 +03:00
return $value [ 'code' ];
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
return $value ;
}
}
2016-10-04 17:57:39 +03:00
public static function removeEmpty ( $inputArray )
{
2016-09-15 16:42:10 +03:00
$outputArray = array ();
2016-10-04 17:57:39 +03:00
if ( ! empty ( $inputArray )) {
foreach ( $inputArray as $key => $element ) {
if ( ! empty ( $element ) || $element === 0 || $element === '0' ) {
if ( is_array ( $element )) {
2016-09-15 16:42:10 +03:00
$element = self :: removeEmpty ( $element );
}
$outputArray [ $key ] = $element ;
}
}
}
return $outputArray ;
}
2016-10-14 15:25:02 +03:00
public static function setProp ( $obj , $value = '' , $prop )
2016-10-04 17:57:39 +03:00
{
if ( ! isset ( $obj )) {
2016-10-03 16:56:59 +03:00
return false ;
}
2016-10-14 15:25:02 +03:00
if ( $prop ) {
2016-09-15 16:42:10 +03:00
$obj -> setField ( $prop , $value );
2016-10-04 17:57:39 +03:00
} elseif ( $value ) {
2016-09-15 16:42:10 +03:00
$obj -> setValue ( $value );
2016-10-04 17:57:39 +03:00
} else {
2016-09-15 16:42:10 +03:00
$obj -> delete ();
}
return true ;
}
2016-10-04 17:57:39 +03:00
public static function getExistsItem ( $basket , $moduleId , $productId )
{
foreach ( $basket as $basketItem ) {
2016-09-15 16:42:10 +03:00
$itemExists = ( $basketItem -> getField ( 'PRODUCT_ID' ) == $productId && $basketItem -> getField ( 'MODULE' ) == $moduleId );
2016-10-04 17:57:39 +03:00
if ( $itemExists ) {
2016-09-15 16:42:10 +03:00
return $basketItem ;
}
}
return false ;
}
2016-10-04 17:57:39 +03:00
public static function getInfoElement ( $offerId )
{
2016-10-03 16:56:59 +03:00
$elementInfo = CIBlockElement :: GetByID ( $offerId ) -> fetch ();
$url = CAllIBlock :: ReplaceDetailUrl ( $elementInfo [ 'DETAIL_PAGE_URL' ], $elementInfo , false , 'E' );
$info = array (
'NAME' => $elementInfo [ 'NAME' ],
'URL' => $url ,
);
2016-10-04 17:57:39 +03:00
2016-10-03 16:56:59 +03:00
return $info ;
2016-09-15 16:42:10 +03:00
}
}
class RetailUser extends CUser
{
public function GetID ()
{
$rsUser = CUser :: GetList (( $by = 'ID' ), ( $order = 'DESC' ), array ( 'LOGIN' => 'retailcrm%' ));
if ( $arUser = $rsUser -> Fetch ()) {
return $arUser [ 'ID' ];
} else {
$retailUser = new CUser ;
$userPassword = uniqid ();
$arFields = array (
" NAME " => 'retailcrm' ,
" LAST_NAME " => 'retailcrm' ,
" EMAIL " => 'retailcrm@retailcrm.com' ,
" LOGIN " => 'retailcrm' ,
" LID " => " ru " ,
" ACTIVE " => " Y " ,
" GROUP_ID " => array ( 2 ),
" PASSWORD " => $userPassword ,
" CONFIRM_PASSWORD " => $userPassword
);
$id = $retailUser -> Add ( $arFields );
if ( ! $id ) {
return null ;
} else {
return $id ;
}
}
}
}