1
0
mirror of synced 2024-11-22 21:36:10 +03:00
bitrix-module/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php

1994 lines
87 KiB
PHP
Raw Normal View History

2016-09-15 16:42:10 +03:00
<?php
use Bitrix\Main\ArgumentException;
use Bitrix\Main\ArgumentNullException;
use Bitrix\Main\ArgumentOutOfRangeException;
use Bitrix\Main\Context;
use Bitrix\Main\NotSupportedException;
use Bitrix\Main\SystemException;
use Bitrix\Sale\Basket;
use Bitrix\Sale\Delivery\Services\EmptyDeliveryService;
use Bitrix\Sale\Delivery\Services\Manager;
use Bitrix\Sale\Fuser;
use Bitrix\Sale\Internals\PaymentTable;
use Bitrix\Sale\Location\Search\Finder;
use Bitrix\Sale\Order;
use Bitrix\Sale\OrderUserProperties;
use Bitrix\Sale\Payment;
use Intaro\RetailCrm\Service\ManagerService;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Component\Constants;
use Intaro\RetailCrm\Component\Handlers\EventsHandlers;
2016-09-15 16:42:10 +03:00
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';
2020-04-24 13:18:18 +03:00
public static $CRM_CUSTOMER_CORPORATE_HISTORY = 'customer_corp_history';
2016-09-15 16:42:10 +03:00
public static $CRM_CATALOG_BASE_PRICE = 'catalog_base_price';
public static $CRM_ORDER_NUMBERS = 'order_numbers';
public static $CRM_CANSEL_ORDER = 'cansel_order';
public static $CRM_CURRENCY = 'currency';
2020-02-18 10:54:42 +03:00
public static $CRM_DISCOUNT_ROUND = 'discount_round';
2016-09-15 16:42:10 +03:00
const CANCEL_PROPERTY_CODE = 'INTAROCRM_IS_CANCELED';
2016-10-04 17:57:39 +03:00
public static function customerHistory()
{
2020-04-24 13:18:18 +03:00
if (!RetailcrmDependencyLoader::loadDependencies()) {
2016-09-15 16:42:10 +03:00
return false;
}
$historyFilter = array();
$historyStart = RetailcrmConfigProvider::getCustomersHistorySinceId();
$api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey());
2017-09-04 11:36:04 +03:00
2016-10-04 17:57:39 +03:00
if ($historyStart && $historyStart > 0) {
2016-09-15 16:42:10 +03:00
$historyFilter['sinceId'] = $historyStart;
}
2017-09-04 11:36:04 +03:00
while (true) {
2017-09-07 13:27:28 +03:00
$customerHistory = RCrmActions::apiMethod($api, 'customersHistory', __METHOD__, $historyFilter);
2016-09-15 16:42:10 +03:00
$customerH = isset($customerHistory['history']) ? $customerHistory['history'] : array();
2020-04-24 13:18:18 +03:00
Logger::getInstance()->write($customerH, 'customerHistory');
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
if (count($customerH) == 0) {
if ($customerHistory['history']['totalPageCount'] > $customerHistory['history']['currentPage']) {
$historyFilter['page'] = $customerHistory['history']['currentPage'] + 1;
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
continue;
}
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
return true;
}
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
$customers = self::assemblyCustomer($customerH);
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
$GLOBALS['RETAIL_CRM_HISTORY'] = true;
2020-04-24 13:18:18 +03:00
$newUser = new CUser();
$customerBuilder = new CustomerBuilder();
2018-09-21 12:22:49 +03:00
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;
2017-09-04 11:36:04 +03:00
} elseif ($newResCustomer === false) {
RCrmActions::eventLog('RetailCrmHistory::customerHistory', 'retailCrmBeforeCustomerSave()', 'UserCrmId = ' . $customer['id'] . '. Sending canceled after retailCrmBeforeCustomerSave');
continue;
2016-09-15 16:42:10 +03:00
}
}
2018-09-21 12:22:49 +03:00
2016-10-04 17:57:39 +03:00
if (isset($customer['deleted'])) {
2016-09-15 16:42:10 +03:00
continue;
}
2018-09-21 12:22:49 +03:00
2020-07-23 14:49:55 +03:00
if (RetailcrmConfigProvider::isPhoneRequired()) {
if (empty($customer['phones'])) {
Logger::getInstance()->write('$customer["phones"] is empty. Customer ' . $customer['id'] . ' cannot be created', 'createCustomerError');
continue;
}
}
2019-01-22 11:39:23 +03:00
if (isset($customer['externalId']) && !is_numeric($customer['externalId'])) {
unset($customer['externalId']);
}
$customerBuilder->setDataCrm($customer)->build();
2016-09-15 16:42:10 +03:00
if (!isset($customer['externalId'])) {
if (!isset($customer['id'])) {
continue;
}
$registerNewUser = true;
2020-04-24 13:18:18 +03:00
2020-07-23 16:28:36 +03:00
if (!empty($customer['email'])) {
2016-09-15 16:42:10 +03:00
$dbUser = CUser::GetList(($by = 'ID'), ($sort = 'ASC'), array('=EMAIL' => $customer['email']));
switch ($dbUser->SelectedRowsCount()) {
case 0:
$login = $customer['email'];
$customerBuilder->setLogin($login);
2016-09-15 16:42:10 +03:00
break;
case 1:
$arUser = $dbUser->Fetch();
$registeredUserID = $arUser['ID'];
$registerNewUser = false;
break;
default:
$login = uniqid('user_' . time()) . '@example.com';
$customerBuilder->setLogin($login);
2016-09-15 16:42:10 +03:00
break;
}
}
if ($registerNewUser === true) {
$registeredUserID = $newUser->Add(
$customerBuilder->getCustomer()->getObjectToArray()
2016-09-15 16:42:10 +03:00
);
2020-04-24 13:18:18 +03:00
2016-09-15 16:42:10 +03:00
if ($registeredUserID === false) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'CUser::Register',
'Error register user: ' . $newUser->LAST_ERROR
);
2016-09-15 16:42:10 +03:00
continue;
}
2020-04-24 13:18:18 +03:00
if(RCrmActions::apiMethod(
$api,
'customersFixExternalIds',
__METHOD__,
array(array('id' => $customer['id'], 'externalId' => $registeredUserID))) == false
2020-04-24 13:18:18 +03:00
) {
continue;
2016-09-15 16:42:10 +03:00
}
}
$customer['externalId'] = $registeredUserID;
}
2018-09-21 12:22:49 +03:00
2016-10-04 17:57:39 +03:00
if (isset($customer['externalId'])) {
$customerBuilder->setDataCrm($customer);
2016-10-04 17:57:39 +03:00
if (isset($customer['phones'])) {
$customerBuilder->setUser(
CUser::GetList(
($by = "ID"),
($order = "desc"),
array('ID' => $customer['externalId']),
array('FIELDS' => array('PERSONAL_PHONE', 'PERSONAL_MOBILE'))
)->fetch()
);
2016-10-31 17:56:11 +03:00
}
2016-09-15 16:42:10 +03:00
$u = $newUser->Update($customer['externalId'], $customerBuilder->getCustomer()->getObjectToArray());
2016-10-04 17:57:39 +03:00
if (!$u) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::customerHistory',
'Error update user',
$newUser->LAST_ERROR
);
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
if (function_exists('retailCrmAfterCustomerSave')) {
retailCrmAfterCustomerSave($customer);
}
}
$customerBuilder->reset();
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
$GLOBALS['RETAIL_CRM_HISTORY'] = false;
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
//last id
2016-09-15 16:42:10 +03:00
$end = array_pop($customerH);
RetailcrmConfigProvider::setCustomersHistorySinceId($end['id']);
2018-09-21 12:22:49 +03:00
2016-10-04 17:57:39 +03:00
if ($customerHistory['pagination']['totalPageCount'] == 1) {
2016-09-15 16:42:10 +03:00
return true;
}
2017-09-04 11:36:04 +03:00
//new filter
2016-09-15 16:42:10 +03:00
$historyFilter['sinceId'] = $end['id'];
}
}
2018-09-21 12:22:49 +03:00
/**
* @return bool
* @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ArgumentNullException
* @throws \Bitrix\Main\ArgumentOutOfRangeException
* @throws \Bitrix\Main\ArgumentTypeException
* @throws \Bitrix\Main\NotImplementedException
* @throws \Bitrix\Main\NotSupportedException
* @throws \Bitrix\Main\ObjectException
* @throws \Bitrix\Main\ObjectNotFoundException
* @throws \Bitrix\Main\ObjectPropertyException
* @throws \Bitrix\Main\SystemException
*/
public static function orderHistory(): bool
2016-10-04 17:57:39 +03:00
{
2016-09-15 16:42:10 +03:00
global $USER;
2017-09-04 11:36:04 +03:00
if (is_object($USER) === false) {
2020-04-24 13:18:18 +03:00
$USER = new RetailUser();
2016-09-15 16:42:10 +03:00
}
2017-09-04 11:36:04 +03:00
2020-04-24 13:18:18 +03:00
if (!RetailcrmDependencyLoader::loadDependencies()) {
2016-09-15 16:42:10 +03:00
return false;
}
2020-04-24 13:18:18 +03:00
$optionsOrderTypes = RetailcrmConfigProvider::getOrderTypes();
$optionsDelivTypes = array_flip(RetailcrmConfigProvider::getDeliveryTypes());
$optionsPayStatuses = array_flip(RetailcrmConfigProvider::getPaymentStatuses()); // --statuses
$optionsOrderProps = RetailcrmConfigProvider::getOrderProps();
$optionsLegalDetails = RetailcrmConfigProvider::getLegalDetails();
$optionsOrderNumbers = RetailcrmConfigProvider::getOrderNumbers();
$optionsCanselOrder = RetailcrmConfigProvider::getCancellableOrderPaymentStatuses();
$currency = RetailcrmConfigProvider::getCurrencyOrDefault();
$contragentTypes = array_flip(RetailcrmConfigProvider::getContragentTypes());
2020-07-23 16:28:36 +03:00
$shipmentDeducted = RetailcrmConfigProvider::getShipmentDeducted();
2016-09-15 16:42:10 +03:00
2020-04-24 13:18:18 +03:00
$api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey());
2016-09-15 16:42:10 +03:00
$historyFilter = array();
$historyStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY);
2020-04-24 13:18:18 +03:00
2016-10-04 17:57:39 +03:00
if ($historyStart && $historyStart > 0) {
2016-09-15 16:42:10 +03:00
$historyFilter['sinceId'] = $historyStart;
2018-09-21 12:22:49 +03:00
}
2016-09-15 16:42:10 +03:00
2016-10-04 17:57:39 +03:00
while (true) {
2017-09-04 11:36:04 +03:00
$orderHistory = RCrmActions::apiMethod($api, 'ordersHistory', __METHOD__, $historyFilter);
$orderH = $orderHistory['history'] ?? [];
2016-09-15 16:42:10 +03:00
2020-04-24 13:18:18 +03:00
Logger::getInstance()->write($orderH, 'orderHistory');
2018-02-27 15:29:43 +03:00
if (count($orderH) === 0) {
2017-09-04 11:36:04 +03:00
if ($orderHistory['history']['totalPageCount'] > $orderHistory['history']['currentPage']) {
$historyFilter['page'] = $orderHistory['history']['currentPage'] + 1;
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
continue;
}
2018-02-27 15:29:43 +03:00
2016-09-15 16:42:10 +03:00
return true;
}
2018-02-27 15:29:43 +03:00
2016-09-15 16:42:10 +03:00
$orders = self::assemblyOrder($orderH);
$GLOBALS['RETAIL_CRM_HISTORY'] = true;
2018-02-27 15:29:43 +03:00
2017-09-04 11:36:04 +03:00
//orders with changes
2016-09-15 16:42:10 +03:00
foreach ($orders as $order) {
if (function_exists('retailCrmBeforeOrderSave')) {
$newResOrder = retailCrmBeforeOrderSave($order);
2020-04-24 13:18:18 +03:00
2016-09-15 16:42:10 +03:00
if (is_array($newResOrder) && !empty($newResOrder)) {
$order = $newResOrder;
2017-09-04 11:36:04 +03:00
} elseif ($newResOrder === false) {
2018-06-13 13:05:58 +03:00
RCrmActions::eventLog('RetailCrmHistory::orderHistory',
'retailCrmBeforeOrderSave()',
'OrderCrmId = ' . $order['id'] . '. Sending canceled after retailCrmBeforeOrderSave'
);
2017-09-04 11:36:04 +03:00
continue;
2016-09-15 16:42:10 +03:00
}
}
2018-02-27 15:29:43 +03:00
2020-04-24 13:18:18 +03:00
Logger::getInstance()->write($order, 'assemblyOrderHistory');
2018-02-27 15:29:43 +03:00
2017-09-04 11:36:04 +03:00
if (isset($order['deleted'])) {
if (isset($order['externalId'])) {
self::cancelOrder($order['externalId']);
2017-09-04 11:36:04 +03:00
}
2016-09-15 16:42:10 +03:00
continue;
}
2021-09-08 10:19:29 +03:00
$site = self::getSite($order['site']);
2020-04-24 13:18:18 +03:00
if (empty($site)) {
RCrmActions::eventLog(
__CLASS__ . '::' . __METHOD__,
'Bitrix\Sale\Order::create',
'Site = ' . $order['site'] . ' not found in setting. Order crm id=' . $order['id']
);
continue;
}
2019-01-22 11:39:23 +03:00
if (isset($order['customer']['externalId']) && !is_numeric($order['customer']['externalId'])) {
unset($order['customer']['externalId']);
}
$corporateCustomerBuilder = new CorporateCustomerBuilder();
2020-04-24 13:18:18 +03:00
$corporateContact = array();
$orderCustomerExtId = $order['customer']['externalId'] ?? null;
$corporateCustomerBuilder->setOrderCustomerExtId($orderCustomerExtId)
->setContragentTypes($contragentTypes)
->setDataCrm($order)
->build();
2020-04-24 13:18:18 +03:00
if (RetailCrmOrder::isOrderCorporate($order)) {
// Fetch contact only if we think it's data is not fully present in order
if (!empty($order['contact'])) {
if (isset($order['contact']['email'])) {
$corporateContact = $order['contact'];
$orderCustomerExtId = $corporateContact['externalId'] ?? null;
$corporateCustomerBuilder->setCorporateContact($corporateContact)
->setOrderCustomerExtId($orderCustomerExtId);
2020-04-24 13:18:18 +03:00
} else {
$response = false;
if (isset($order['contact']['externalId'])) {
$response = RCrmActions::apiMethod(
$api,
'customersGet',
__METHOD__,
$order['contact']['externalId'],
$order['site']
);
} elseif (isset($order['contact']['id'])) {
$response = RCrmActions::apiMethod(
$api,
'customersGetById',
__METHOD__,
$order['contact']['id'],
$order['site']
);
}
if ($response && isset($response['customer'])) {
$corporateContact = $response['customer'];
$orderCustomerExtId = $corporateContact['externalId'] ?? null;
$corporateCustomerBuilder->setCorporateContact($corporateContact)
->setOrderCustomerExtId($orderCustomerExtId);
2020-04-24 13:18:18 +03:00
}
}
}
}
2016-09-15 16:42:10 +03:00
if (!isset($order['externalId'])) {
2020-04-24 13:18:18 +03:00
if (empty($orderCustomerExtId)) {
if (!isset($order['customer']['id'])
|| (RetailCrmOrder::isOrderCorporate($order)
&& (!isset($order['contact']['id']) || !isset($order['customer']['id'])))
) {
2016-09-15 16:42:10 +03:00
continue;
}
2020-07-23 14:49:55 +03:00
if (RetailcrmConfigProvider::isPhoneRequired()) {
if (empty($order['customer']['phones'])) {
Logger::getInstance()->write('$customer["phones"] is empty. Order ' . $order['id'] . ' cannot be created', 'createCustomerError');
continue;
}
}
2020-04-24 13:18:18 +03:00
$login = null;
2016-09-15 16:42:10 +03:00
$registerNewUser = true;
2020-04-24 13:18:18 +03:00
if (!isset($order['customer']['email']) || empty($order['customer']['email'])) {
if (RetailCrmOrder::isOrderCorporate($order) && !empty($corporateContact['email'])) {
$login = $corporateContact['email'];
$order['customer']['email'] = $corporateContact['email'];
$corporateCustomerBuilder->setLogin($login)
->setEmail($corporateContact['email']);
2020-04-24 13:18:18 +03:00
} else {
$login = uniqid('user_' . time()) . '@example.com';
2020-04-24 13:18:18 +03:00
$order['customer']['email'] = $login;
$corporateCustomerBuilder->setLogin($login)
->setEmail($login);
2016-09-15 16:42:10 +03:00
}
}
2020-04-24 13:18:18 +03:00
$dbUser = CUser::GetList(
($by = 'ID'),
($sort = 'ASC'),
array('=EMAIL' => $order['customer']['email'])
);
switch ($dbUser->SelectedRowsCount()) {
case 0:
$login = $order['customer']['email'];
$corporateCustomerBuilder->setLogin($login);
2020-04-24 13:18:18 +03:00
break;
case 1:
$arUser = $dbUser->Fetch();
$registeredUserID = $arUser['ID'];
$registerNewUser = false;
break;
default:
$login = uniqid('user_' . time()) . '@example.com';
$corporateCustomerBuilder->setLogin($login);
2020-04-24 13:18:18 +03:00
break;
}
2016-09-15 16:42:10 +03:00
if ($registerNewUser === true) {
2020-04-24 13:18:18 +03:00
$userData = RetailCrmOrder::isOrderCorporate($order)
? $corporateContact
: $order['customer'];
2016-09-15 16:42:10 +03:00
$corporateCustomerBuilder->setCorporateContact($userData);
2020-04-24 13:18:18 +03:00
$newUser = new CUser();
$registeredUserID = $newUser->Add(
$corporateCustomerBuilder->getCustomer()->getObjectToArray()
2016-09-15 16:42:10 +03:00
);
2020-04-24 13:18:18 +03:00
2016-09-15 16:42:10 +03:00
if ($registeredUserID === false) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'CUser::Register',
'Error register user' . $newUser->LAST_ERROR
);
2016-09-15 16:42:10 +03:00
continue;
2017-09-04 11:36:04 +03:00
}
2016-09-15 16:42:10 +03:00
2020-04-24 13:18:18 +03:00
if(RCrmActions::apiMethod(
$api,
'customersFixExternalIds',
__METHOD__,
array(array(
'id' => $order['customer']['id'],
'externalId' => $registeredUserID
))) == false
2020-04-24 13:18:18 +03:00
) {
2018-09-21 12:22:49 +03:00
continue;
2016-09-15 16:42:10 +03:00
}
}
2020-04-24 13:18:18 +03:00
$orderCustomerExtId = isset($registeredUserID) ? $registeredUserID : null;
$corporateCustomerBuilder->setOrderCustomerExtId($orderCustomerExtId);
2016-09-15 16:42:10 +03:00
}
2020-04-24 13:18:18 +03:00
$buyerProfileToAppend = array();
2018-09-21 12:22:49 +03:00
2020-04-24 13:18:18 +03:00
if (RetailCrmOrder::isOrderCorporate($order) && !empty($order['company'])) {
$buyerProfile = $corporateCustomerBuilder->getBuyerProfile()->getObjectToArray();
$buyerProfileToAppend = OrderUserProperties::getList(array(
2020-04-24 13:18:18 +03:00
"filter" => $buyerProfile
))->fetch();
if (empty($buyerProfileToAppend)) {
$buyerProfileInstance = new CSaleOrderUserProps();
if ($buyerProfileInstance->Add($buyerProfile)) {
$buyerProfileToAppend = OrderUserProperties::getList(array(
2020-04-24 13:18:18 +03:00
"filter" => $buyerProfile
))->fetch();
}
}
2017-09-04 11:36:04 +03:00
}
2018-01-12 11:14:33 +03:00
$newOrder = Order::create($site, $orderCustomerExtId, $currency);
if (array_key_exists('managerId', $order)) {
$service = ManagerService::getInstance();
$newOrder->setField('RESPONSIBLE_ID', $service->getManagerBitrixId($order['managerId']));
}
2020-04-24 13:18:18 +03:00
if (isset($buyerProfileToAppend['ID']) && isset($optionsLegalDetails['legalName'])) {
$newOrder->setFields([
2020-04-24 13:18:18 +03:00
$optionsLegalDetails['legalName'] => $buyerProfileToAppend['NAME'],
'PERSON_TYPE_ID' => $buyerProfileToAppend['PERSON_TYPE_ID'],
]);
2020-04-24 13:18:18 +03:00
}
2018-01-12 11:14:33 +03:00
if (!is_object($newOrder) || !$newOrder instanceof Order) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::create',
'Error order create'
);
2018-01-12 11:14:33 +03:00
continue;
}
2016-09-15 16:42:10 +03:00
$externalId = $newOrder->getId();
$order['externalId'] = $externalId;
}
if (isset($order['externalId'])) {
2016-10-06 17:34:35 +03:00
$itemUpdate = false;
2019-09-17 18:10:30 +03:00
if ($order['externalId'] && is_numeric($order['externalId'])) {
try {
$newOrder = Order::load($order['externalId']);
} catch (ArgumentNullException $e) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::load',
$e->getMessage() . ': ' . $order['externalId']
);
continue;
}
2017-09-04 11:36:04 +03:00
}
2016-10-03 16:56:59 +03:00
if (!isset($newOrder)) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::load',
'Error order load number=' . $order['number']
);
2018-02-27 15:29:43 +03:00
2016-09-15 16:42:10 +03:00
continue;
}
2021-09-08 10:19:29 +03:00
$site = self::getSite($order['site']);
2021-09-08 10:19:29 +03:00
if (null === $site) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::edit',
sprintf(
'Site = %s not found in settings. Order number = %s',
$order['site'],
$order['number']
)
);
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
continue;
}
2016-09-15 16:42:10 +03:00
2020-04-24 13:18:18 +03:00
$propsRemove = false;
2016-10-03 16:56:59 +03:00
$personType = $newOrder->getField('PERSON_TYPE_ID');
2020-04-24 13:18:18 +03:00
if (RetailCrmOrder::isOrderCorporate($order)
|| (!empty($order['contragentType']) && $order['contragentType'] == 'legal-entity')
) {
2020-04-24 13:18:18 +03:00
$personType = $contragentTypes['legal-entity'];
$newOrder->setField('PERSON_TYPE_ID', $personType);
$propsRemove = true;
2020-04-24 13:18:18 +03:00
} else {
if (isset($order['orderType']) && $order['orderType']) {
$nType = array();
$tList = RCrmActions::OrderTypesList(array(array('LID' => $site)));
foreach ($tList as $type) {
2020-04-24 13:18:18 +03:00
if (isset($optionsOrderTypes[$type['ID']])) {
$nType[$optionsOrderTypes[$type['ID']]] = $type['ID'];
}
}
2017-09-04 11:36:04 +03:00
2020-04-24 13:18:18 +03:00
$newOptionsOrderTypes = $nType;
if ($newOptionsOrderTypes[$order['orderType']]) {
if ($personType != $newOptionsOrderTypes[$order['orderType']] && $personType != 0) {
$propsRemove = true;
}
$personType = $newOptionsOrderTypes[$order['orderType']];
$newOrder->setField('PERSON_TYPE_ID', $personType);
} elseif ($personType == 0) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'orderType not found',
'PERSON_TYPE_ID = 0'
);
}
2016-10-03 16:56:59 +03:00
}
2017-09-04 11:36:04 +03:00
}
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']]);
2020-04-24 13:18:18 +03:00
2016-10-04 17:57:39 +03:00
if (in_array($optionsPayStatuses[$order['status']], $optionsCanselOrder)) {
2018-02-27 15:29:43 +03:00
self::unreserveShipment($newOrder);
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
}
}
2017-09-04 11:36:04 +03:00
if (array_key_exists('statusComment', $order)) {
2020-04-24 13:18:18 +03:00
self::setProp(
$newOrder,
RCrmActions::fromJSON($order['statusComment']),
'REASON_CANCELED'
);
2017-09-04 11:36:04 +03:00
}
2016-10-03 16:56:59 +03:00
2017-09-04 11:36:04 +03:00
//props
2016-09-15 16:42:10 +03:00
$propertyCollection = $newOrder->getPropertyCollection();
$propertyCollectionArr = $propertyCollection->getArray();
2016-10-03 16:56:59 +03:00
$nProps = array();
2020-04-24 13:18:18 +03:00
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);
2019-01-16 10:28:11 +03:00
$property = $propertyCollection->getItemById($orderProp['ID']);
if ($property) {
$orderProp['ID'] = $property->getField('ORDER_PROPS_ID');
} else {
continue;
}
2016-10-03 16:56:59 +03:00
}
2020-04-24 13:18:18 +03:00
2016-10-03 16:56:59 +03:00
$nProps[] = $orderProp;
}
2020-04-24 13:18:18 +03:00
$orderDump = array();
2016-10-03 16:56:59 +03:00
$propertyCollectionArr['properties'] = $nProps;
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
if ($propsRemove) {//delete props
2016-10-04 17:57:39 +03:00
foreach ($propertyCollectionArr['properties'] as $orderProp) {
2017-10-24 11:41:11 +03:00
if ($orderProp['PROPS_GROUP_ID'] == 0) {
$somePropValue = $propertyCollection->getItemByOrderPropertyId($orderProp['ID']);
self::setProp($somePropValue);
}
2016-10-03 16:56:59 +03:00
}
2020-04-24 13:18:18 +03:00
2017-09-04 11:36:04 +03:00
$orderCrm = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
2016-10-03 16:56:59 +03:00
$orderDump = $order;
$order = $orderCrm['order'];
}
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
$propsKey = array();
2020-04-24 13:18:18 +03:00
2016-10-04 17:57:39 +03:00
foreach ($propertyCollectionArr['properties'] as $prop) {
2017-10-24 11:41:11 +03:00
if ($prop['PROPS_GROUP_ID'] != 0) {
$propsKey[$prop['CODE']]['ID'] = $prop['ID'];
$propsKey[$prop['CODE']]['TYPE'] = $prop['TYPE'];
}
2016-09-15 16:42:10 +03:00
}
2020-04-24 13:18:18 +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']);
2016-10-14 15:25:02 +03:00
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) {
2020-04-24 13:18:18 +03:00
$newFio[] = isset($order['lastName'])
? RCrmActions::fromJSON($order['lastName'])
: ($fio['lastName'] ?? '');
2020-04-24 13:18:18 +03:00
$newFio[] = isset($order['firstName'])
? RCrmActions::fromJSON($order['firstName'])
: ($fio['firstName'] ?? '');
2020-04-24 13:18:18 +03:00
$newFio[] = isset($order['patronymic'])
? RCrmActions::fromJSON($order['patronymic'])
: ($fio['patronymic'] ?? '');
2020-04-24 13:18:18 +03:00
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']) : '';
2016-09-15 16:42:10 +03:00
}
$order['fio'] = trim(implode(' ', $newFio));
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
if (array_key_exists('fio', $order)) {
$order['fio'] = str_replace("clear", "", $order['fio']);
}
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)) {
2020-04-24 13:18:18 +03:00
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
if ($key == 'fio' && '' !== trim($order['fio'])) {
2016-10-25 17:56:50 +03:00
self::setProp($somePropValue, $order[$key]);
} else {
self::setProp($somePropValue, RCrmActions::fromJSON($order[$key]));
}
2016-10-04 17:57:39 +03:00
} elseif (array_key_exists($key, $order['delivery']['address'])) {
2016-10-25 17:56:50 +03:00
if ($propsKey[$orderProp]['TYPE'] == 'LOCATION') {
2019-09-17 18:10:30 +03:00
if( $order['delivery']['address']['index'] ) {
$location = CSaleLocation::GetByZIP($order['delivery']['address']['index']);
}
2020-04-24 13:18:18 +03:00
2017-09-04 11:36:04 +03:00
$order['delivery']['address'][$key] = trim($order['delivery']['address'][$key]);
2016-11-15 17:17:09 +03:00
if(!empty($order['delivery']['address'][$key])){
$parameters = array();
$loc = explode('.', $order['delivery']['address'][$key]);
if (count($loc) == 1) {
2017-09-04 11:36:04 +03:00
$parameters['filter']['PHRASE'] = RCrmActions::fromJSON(trim($loc[0]));
2016-11-15 17:17:09 +03:00
} elseif (count($loc) == 2) {
2017-09-04 11:36:04 +03:00
$parameters['filter']['PHRASE'] = RCrmActions::fromJSON(trim($loc[1]));
2018-05-23 12:19:59 +03:00
} else {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'RetailCrmHistory::setProp',
sprintf(
'Error location. %s not found add in order number = %s',
$order['delivery']['address'][$key],
$order['number']
)
);
2016-11-15 17:17:09 +03:00
continue;
}
2018-05-23 12:19:59 +03:00
2017-09-04 11:36:04 +03:00
$parameters['filter']['NAME.LANGUAGE_ID'] = 'ru';
2018-05-23 12:19:59 +03:00
try {
if (!isset($location)) {
$location = Finder::find(
2020-04-24 13:18:18 +03:00
$parameters,
['USE_INDEX' => false, 'USE_ORM' => false]
2020-04-24 13:18:18 +03:00
)->fetch();
2019-09-17 18:10:30 +03:00
}
2020-04-24 13:18:18 +03:00
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
2018-05-23 12:19:59 +03:00
self::setProp($somePropValue, $location['CODE']);
} catch (ArgumentException $argumentException) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'RetailCrmHistory::setProp',
'Location parameter is incorrect in order number=' . $order['number']
);
2018-05-23 12:19:59 +03:00
}
} else {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'RetailCrmHistory::setProp',
sprintf(
'Error location. %s is empty in order number=%s',
$order['delivery']['address'][$key],
$order['number']
)
);
2017-09-04 11:36:04 +03:00
continue;
2016-10-25 17:56:50 +03:00
}
2016-10-04 17:57:39 +03:00
} else {
2020-04-24 13:18:18 +03:00
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp(
$somePropValue,
RCrmActions::fromJSON($order['delivery']['address'][$key])
);
2016-09-15 16:42:10 +03:00
}
}
}
}
2017-10-24 11:41:11 +03:00
if (isset($order['company']['id'])) {
if (!empty($order['company']['name'])) {
$order["legalName"] = $order['company']['name'];
}
}
2020-04-24 13:18:18 +03:00
// Corporate clients section
2016-10-04 17:57:39 +03:00
if ($optionsLegalDetails[$personType]) {
foreach ($optionsLegalDetails[$personType] as $key => $orderProp) {
2019-03-28 14:35:26 +03:00
if (array_key_exists($key, $order)) {
2020-04-24 13:18:18 +03:00
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
2019-09-17 18:10:30 +03:00
self::setProp($somePropValue, RCrmActions::fromJSON($order[$key]));
} elseif(array_key_exists($key, $order['contragent'])) {
2020-04-24 13:18:18 +03:00
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, RCrmActions::fromJSON($order['contragent'][$key]));
2020-04-24 13:18:18 +03:00
} elseif (isset($order['company']) && (array_key_exists($key, $order['company'])
|| array_key_exists(
lcfirst(str_replace('legal', '', $key)),
$order['company'])
)
) {
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
// fallback for order[company][name]
if ($key == 'legalName') {
$key = 'name';
}
self::setProp(
$somePropValue,
RCrmActions::fromJSON(
$key == 'legalAddress'
? ($order['company']['address']['text'] ?? '')
2020-04-24 13:18:18 +03:00
: $order['company'][$key]
)
);
} elseif (isset($order['company']['contragent'])
&& array_key_exists($key, $order['company']['contragent'])
) {
$somePropValue = $propertyCollection
->getItemByOrderPropertyId($propsKey[$orderProp]['ID']);
self::setProp($somePropValue, RCrmActions::fromJSON($order['company']['contragent'][$key]));
2016-09-15 16:42:10 +03:00
}
}
}
2017-10-24 11:41:11 +03:00
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
//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();
2018-01-12 11:14:33 +03:00
if (!$basket) {
$basket = Basket::create($site);
$newOrder->setBasket($basket);
}
2018-02-27 15:29:43 +03:00
$fUserId = $basket->getFUserId(true);
2018-07-16 16:01:19 +03:00
if (!$fUserId) {
$fUserId = Fuser::getIdByUserId($order['customer']['externalId']);
2018-02-27 15:29:43 +03:00
$basket->setFUserId($fUserId);
}
if (isset($order['contact']['id'])) {
$ExtId = null;
$response = RCrmActions::apiMethod(
$api,
'customersGetById',
__METHOD__,
$order['contact']['id'],
$order['site']
);
if (isset($order['contact']['externalId'])) {
$ExtId = $order['contact']['externalId'];
}
if (isset($ExtId)) {
$newOrder->setFieldNoDemand('USER_ID', $ExtId);
} else {
$newUser = new CUser();
$customerBuilder = new CustomerBuilder();
$customerBuilder->setDataCrm($response['customer'])->build();
if (!empty($response['customer']['email'])) {
$registerNewUser = true;
$dbUser = CUser::GetList(
($by = 'ID'),
($sort = 'ASC'),
array('=EMAIL' => $response['customer']['email'])
);
switch ($dbUser->SelectedRowsCount()) {
case 0:
$login = $response['customer']['email'];
$customerBuilder->setLogin($login);
break;
case 1:
$arUser = $dbUser->Fetch();
$registeredUserID = $arUser['ID'];
$registerNewUser = false;
break;
default:
$login = uniqid('user_' . time()) . '@example.com';
$customerBuilder->setLogin($login);
break;
}
if ($registerNewUser === true) {
$registeredUserID = $newUser->Add(
$customerBuilder->getCustomer()->getObjectToArray()
);
if ($registeredUserID === false) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'CUser::Register',
'Error register user: ' . $newUser->LAST_ERROR
);
continue;
}
if(RCrmActions::apiMethod(
$api,
'customersFixExternalIds',
__METHOD__,
array(array(
'id' => $response['customer']['id'],
'externalId' => $registeredUserID
))
) == false
) {
continue;
}
}
$newOrder->setFieldNoDemand('USER_ID', $registeredUserID);
}
}
}
2016-10-06 17:34:35 +03:00
if (isset($order['items'])) {
$itemUpdate = true;
$response = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
if (isset($response['order'])) {
$orderTemp = $response['order'];
2020-02-18 10:54:42 +03:00
$duplicateItems = [];
foreach ($orderTemp['items'] as $item) {
2020-02-18 10:54:42 +03:00
$duplicateItems[$item['id']]['externalId'] += $item['offer']['externalId'];
$duplicateItems[$item['id']]['quantity'] += $item['quantity'];
$duplicateItems[$item['id']]['discountTotal'] +=
$item['quantity'] * $item['discountTotal'];
$duplicateItems[$item['id']]['initialPrice'] = (float) $item['initialPrice'];
$duplicateItems[$item['id']]['price_sum'] = ($item['quantity'] * $item['initialPrice'])
- ($item['quantity'] * $item['discountTotal']);
}
unset($orderTemp);
} else {
continue;
}
2020-02-18 10:54:42 +03:00
$collectItems = [];
2020-02-18 10:54:42 +03:00
foreach ($duplicateItems as $it) {
$collectItems[$it['externalId']]['quantity'] += $it['quantity'];
$collectItems[$it['externalId']]['price_sum'] += $it['price_sum'];
$collectItems[$it['externalId']]['discountTotal_sum'] += $it['discountTotal'];
if (isset($collectItems[$it['externalId']]['initialPrice_max'])) {
if ($collectItems[$it['externalId']]['initialPrice_max'] < $it['initialPrice']) {
$collectItems[$it['externalId']]['initialPrice_max'] = $it['initialPrice'];
}
} else {
$collectItems[$it['externalId']]['initialPrice_max'] = $it['initialPrice'];
}
$collectItems[$it['externalId']]['initialPricesList'][] = $it['initialPrice'];
}
foreach ($collectItems as $key => $itemData) {
if (count($itemData['initialPricesList']) > 1) {
$discountDelta = 0;
foreach ($itemData['initialPrices'] as $initialPriceItem) {
$delta = $itemData['initialPrice_max'] - (float) $initialPriceItem;
if ($delta !== 0) {
$discountDelta += $delta;
}
}
$collectItems[$key]['discountTotal_sum'] += $discountDelta;
}
2020-02-18 10:54:42 +03:00
}
2020-04-24 13:18:18 +03:00
Logger::getInstance()->write($duplicateItems, 'duplicateItemsOrderHistory');
Logger::getInstance()->write($collectItems, 'collectItemsOrderHistory');
2020-02-18 10:54:42 +03:00
$optionDiscRound = COption::GetOptionString(self::$MODULE_ID, self::$CRM_DISCOUNT_ROUND, 0);
2016-10-06 17:34:35 +03:00
foreach ($order['items'] as $product) {
2020-02-18 10:54:42 +03:00
if ($collectItems[$product['offer']['externalId']]['quantity']) {
$product['quantity'] = $collectItems[$product['offer']['externalId']]['quantity'];
}
2016-10-06 17:34:35 +03:00
$item = self::getExistsItem($basket, 'catalog', $product['offer']['externalId']);
2018-01-12 11:14:33 +03:00
2016-10-06 17:34:35 +03:00
if (!$item) {
2018-02-27 15:29:43 +03:00
if ($product['delete']) {
2016-10-06 17:34:35 +03:00
continue;
}
2018-01-12 11:14:33 +03:00
2016-10-06 17:34:35 +03:00
$item = $basket->createItem('catalog', $product['offer']['externalId']);
2018-01-12 11:14:33 +03:00
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' => $newOrder->getCurrency(),
2016-10-20 17:41:07 +03:00
'LID' => $site,
'BASE_PRICE' => $collectItems[$product['offer']['externalId']]['initialPrice_max'],
2017-11-13 11:05:11 +03:00
'NAME' => $product['offer']['name'] ? RCrmActions::fromJSON($product['offer']['name']) : $elem['NAME'],
2017-09-04 11:36:04 +03:00
'DETAIL_PAGE_URL' => $elem['URL'],
'PRODUCT_PROVIDER_CLASS' => 'CCatalogProductProvider',
'DIMENSIONS' => $elem['DIMENSIONS'],
'WEIGHT' => $elem['WEIGHT'],
'NOTES' => GetMessage('PRICE_TYPE'),
'PRODUCT_XML_ID' => $elem["XML_ID"],
'CATALOG_XML_ID' => $elem["IBLOCK_XML_ID"]
2016-10-06 17:34:35 +03:00
));
} else {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'createItem',
'Error item add'
);
2018-02-27 15:29:43 +03:00
2016-10-06 17:34:35 +03:00
continue;
}
}
2018-01-12 11:14:33 +03:00
2016-10-06 17:34:35 +03:00
if ($product['delete']) {
2020-02-18 10:54:42 +03:00
if ($collectItems[$product['offer']['externalId']]['quantity'] <= 0) {
$item->delete();
2018-09-21 12:22:49 +03:00
continue;
}
2016-10-03 16:56:59 +03:00
}
2016-09-15 16:42:10 +03:00
2016-10-06 17:34:35 +03:00
if ($product['quantity']) {
$item->setFieldNoDemand('QUANTITY', $product['quantity']);
}
if (array_key_exists('initialPrice_max', $collectItems[$product['offer']['externalId']])) {
$item->setField(
'BASE_PRICE',
$collectItems[$product['offer']['externalId']]['initialPrice_max']
);
2016-09-15 16:42:10 +03:00
}
2020-02-18 10:54:42 +03:00
if (array_key_exists('discountTotal_sum', $collectItems[$product['offer']['externalId']])) {
$item->setField('CUSTOM_PRICE', 'Y');
$item->setField('DISCOUNT_NAME', '');
$item->setField('DISCOUNT_VALUE', '');
// Полную цену позиции с учётом скидок делим на количество - получаем цену каждой единицы
// товара с учётом скидок.
$price = $collectItems[
$product['offer']['externalId']
]['price_sum'] / $collectItems[$product['offer']['externalId']]['quantity'];
2018-07-16 16:01:19 +03:00
2020-02-18 10:54:42 +03:00
if ('Y' == $optionDiscRound) {
$price = self::truncate($price, 2);
2016-10-06 17:34:35 +03:00
}
2020-02-18 10:54:42 +03:00
$item->setField('PRICE', $price);
2016-09-15 16:42:10 +03:00
}
}
}
2018-01-12 11:14:33 +03:00
2016-09-15 16:42:10 +03:00
$orderSumm = 0;
2020-04-24 13:18:18 +03:00
2016-10-04 17:57:39 +03:00
foreach ($basket as $item) {
2018-09-21 12:22:49 +03:00
$orderSumm += $item->getFinalPrice();
2016-09-15 16:42:10 +03:00
}
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;
$order['summ'] = $orderSumm;
2018-01-12 11:14:33 +03:00
2016-09-15 16:42:10 +03:00
//payment
2018-01-12 11:14:33 +03:00
$newHistoryPayments = array();
2017-09-04 11:36:04 +03:00
if (array_key_exists('payments', $order)) {
if (!isset($orderCrm)) {
$orderCrm = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
}
if ($orderCrm) {
2018-03-22 16:11:04 +03:00
self::paymentsUpdate($newOrder, $orderCrm['order'], $newHistoryPayments);
2017-09-04 11:36:04 +03:00
}
2016-09-15 16:42:10 +03:00
}
2016-09-15 16:42:10 +03:00
//delivery
if (array_key_exists('delivery', $order)) {
2016-10-06 17:34:35 +03:00
$itemUpdate = true;
2020-04-24 13:18:18 +03:00
2017-09-04 11:36:04 +03:00
//delete empty
2016-10-04 17:57:39 +03:00
if (!isset($orderCrm)) {
2017-09-04 11:36:04 +03:00
$orderCrm = RCrmActions::apiMethod($api, 'orderGet', __METHOD__, $order['id']);
}
2020-04-24 13:18:18 +03:00
2017-09-04 11:36:04 +03:00
if ($orderCrm) {
2018-01-12 11:14:33 +03:00
self::deliveryUpdate($newOrder, $optionsDelivTypes, $orderCrm['order']);
2016-09-15 16:42:10 +03:00
}
}
if ($itemUpdate === true && $newOrder->getField('CANCELED') !== 'Y') {
2018-01-12 11:14:33 +03:00
self::shipmentItemReset($newOrder);
}
2016-10-04 17:57:39 +03:00
if (isset($orderCrm)) {
2018-09-21 12:22:49 +03:00
unset($orderCrm);
2016-09-15 16:42:10 +03:00
}
2018-01-12 11:14:33 +03:00
2020-07-23 16:28:36 +03:00
if (isset($order['fullPaidAt']) && is_string($order['fullPaidAt'])) {
$newOrder->setFieldNoDemand('PAYED', 'Y');
2020-07-23 16:28:36 +03:00
}
if ($shipmentDeducted === 'Y') {
$collection = $newOrder->getShipmentCollection()->getNotSystemItems();
if (isset($order['shipped'])) {
if ($order['shipped']) {
if ($collection->count() === 0) {
$collection = $newOrder->getShipmentCollection();
$shipment = $collection->createItem();
$shipment->setField('DEDUCTED', 'Y');
} else {
foreach ($collection as $shipment) {
$shipment->setField('DEDUCTED', 'Y');
}
}
} else {
foreach ($collection as $shipment) {
$shipment->setField('DEDUCTED', 'N');
}
}
}
}
2018-01-12 11:14:33 +03:00
$newOrder->setField('PRICE', $orderSumm);
2018-09-21 12:22:49 +03:00
self::orderSave($newOrder);
if ($optionsOrderNumbers === 'Y' && isset($order['number'])) {
2018-01-23 17:24:32 +03:00
$newOrder->setField('ACCOUNT_NUMBER', $order['number']);
2018-09-21 12:22:49 +03:00
self::orderSave($newOrder);
2018-01-23 17:24:32 +03:00
}
if (!empty($newHistoryPayments)) {
2018-01-12 11:14:33 +03:00
foreach ($newOrder->getPaymentCollection() as $orderPayment) {
if (array_key_exists($orderPayment->getField('XML_ID'), $newHistoryPayments)) {
$paymentId = $orderPayment->getId();
$paymentExternalId = RCrmActions::generatePaymentExternalId($paymentId);
2019-09-10 13:29:23 +03:00
if (is_null($paymentId)) {
2020-04-24 13:18:18 +03:00
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'paymentsUpdate',
'Save payment error, order=' . $order['number']
);
2019-09-10 13:29:23 +03:00
continue;
}
2021-01-13 17:51:36 +03:00
$newHistoryPayments[$orderPayment->getField('XML_ID')]['externalId'] = $paymentExternalId;
RCrmActions::apiMethod(
$api,
'paymentEditById',
__METHOD__,
$newHistoryPayments[$orderPayment->getField('XML_ID')]
);
2020-04-24 13:18:18 +03:00
2021-01-13 17:51:36 +03:00
if ($paymentId) {
PaymentTable::update($paymentId, array('XML_ID' => ''));
2018-09-21 12:22:49 +03:00
}
2018-01-12 11:14:33 +03:00
}
}
}
if (!$order['externalId']) {
$order["externalId"] = $newOrder->getId();
2020-04-24 13:18:18 +03:00
if (RCrmActions::apiMethod(
$api,
'ordersFixExternalIds',
__METHOD__,
array(array('id' => $order['id'], 'externalId' => $newOrder->getId()))) == false
2020-04-24 13:18:18 +03:00
) {
continue;
2016-09-15 16:42:10 +03:00
}
2016-10-06 17:34:35 +03:00
}
2016-09-15 16:42:10 +03:00
if (function_exists('retailCrmAfterOrderSave')) {
retailCrmAfterOrderSave($order);
}
}
2018-07-16 16:01:19 +03:00
unset($newOrder);
2016-09-15 16:42:10 +03:00
}
2016-09-15 16:42:10 +03:00
$GLOBALS['RETAIL_CRM_HISTORY'] = false;
2017-09-04 11:36:04 +03:00
//end id
2016-09-15 16:42:10 +03:00
$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;
}
2017-09-04 11:36:04 +03:00
//new filter
2016-09-15 16:42:10 +03:00
$historyFilter['sinceId'] = $end['id'];
}
2020-04-24 13:18:18 +03:00
return false;
2016-09-15 16:42:10 +03:00
}
2021-09-08 10:19:29 +03:00
/**
* @param string $shopCode
*
* @return string|null
*/
public static function getSite(string $shopCode): ?string
{
$optionsSitesList = RetailcrmConfigProvider::getSitesList();
2021-09-08 10:19:29 +03:00
if ($optionsSitesList) {
$searchResult = array_search($shopCode, $optionsSitesList, true);
2021-09-08 10:19:29 +03:00
return is_string($searchResult) ? $searchResult : null;
}
2021-09-08 10:19:29 +03:00
$defaultSite = CSite::GetDefSite();
2021-09-08 10:19:29 +03:00
return is_string($defaultSite) ? $defaultSite : null;
}
/**
* @param $array
* @param $value
*
* @return array
*/
public static function search_array_by_value($array, $value)
{
$results = array();
if (is_array($array)) {
$found = array_search($value,$array);
if ($found) {
$results[] = $found;
}
foreach ($array as $subarray)
$results = array_merge($results, static::search_array_by_value($subarray, $value));
}
return $results;
}
2016-10-04 17:57:39 +03:00
public static function assemblyCustomer($customerHistory)
{
2020-08-25 11:14:47 +03:00
$customerHistory = self::filterHistory($customerHistory, 'customer');
$server = Context::getCurrent()->getServer()->getDocumentRoot();
2016-09-15 16:42:10 +03:00
$fields = array();
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
2018-09-21 12:22:49 +03:00
$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']);
2018-09-21 12:22:49 +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'];
}
2018-09-21 12:22:49 +03:00
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']);
}
2018-09-21 12:22:49 +03:00
2020-04-24 13:18:18 +03:00
if ($change['field'] == 'segments') {
if ($change['newValue']['code'] == "genshchini") {
$customers[$change['customer']['id']]["sex"] = "F";
}
}
if ($change['field'] == 'segments') {
if ($change['newValue']['code'] == "mugchini") {
$customers[$change['customer']['id']]["sex"] = "M";
}
}
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']);
} elseif (strripos($change['field'], 'custom_') !== false) {
$customers[$change['customer']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
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-09-15 16:42:10 +03:00
return $customers;
}
2018-09-21 12:22:49 +03:00
2016-10-04 17:57:39 +03:00
public static function assemblyOrder($orderHistory)
{
2020-08-25 11:14:47 +03:00
$orderHistory = self::filterHistory($orderHistory, 'order');
$server = Context::getCurrent()->getServer()->getDocumentRoot();
2020-04-24 13:18:18 +03:00
2016-09-15 16:42:10 +03:00
if (file_exists($server . '/bitrix/modules/intaro.retailcrm/classes/general/config/objects.xml')) {
2020-04-24 13:18:18 +03:00
$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;
}
}
2020-04-24 13:18:18 +03:00
2016-09-15 16:42:10 +03:00
$orders = array();
2020-04-24 13:18:18 +03:00
2016-09-15 16:42:10 +03:00
foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']);
2016-10-04 17:57:39 +03:00
if ($change['order']['items']) {
$items = [];
2016-10-04 17:57:39 +03:00
foreach ($change['order']['items'] as $item) {
if (isset($change['created'])) {
2018-09-21 12:22:49 +03:00
$item['create'] = 1;
2016-09-15 16:42:10 +03:00
}
$items[$item['id']] = $item;
}
$change['order']['items'] = $items;
}
2018-09-21 12:22:49 +03:00
2020-04-24 13:18:18 +03:00
if ($change['field'] == 'number') {
$orders[$change['order']['id']]['number'] = $change['newValue'];
}
if ($change['field'] == 'manager') {
$orders[$change['order']['id']]['managerId'] = $change['newValue'];
}
if (isset($change['oldValue']) && $change['field'] == 'customer') {
$orders[$change['order']['id']]['customer'] = $change['newValue'];
}
if (isset($change['oldValue']) && $change['field'] == 'contact') {
$orders[$change['order']['id']]['contact'] = $change['newValue'];
}
if (isset($change['oldValue']) && $change['field'] == 'company') {
$orders[$change['order']['id']]['company'] = $change['newValue'];
}
2017-09-04 11:36:04 +03:00
if ($change['order']['payments']) {
$payments = array();
foreach ($change['order']['payments'] as $payment) {
$payments[$payment['id']] = $payment;
}
$change['order']['payments'] = $payments;
}
2018-09-21 12:22:49 +03:00
if (isset($change['order']['contragent']) && count($change['order']['contragent']) > 0) {
foreach ($change['order']['contragent'] as $name => $value) {
$change['order'][$name] = self::newValue($value);
}
2016-09-15 16:42:10 +03:00
unset($change['order']['contragent']);
}
2018-09-21 12:22:49 +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'];
2018-09-21 12:22:49 +03:00
}
2016-09-15 16:42:10 +03:00
2016-10-04 17:57:39 +03:00
if ($change['item']) {
2018-09-21 12:22:49 +03:00
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;
}
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'];
}
2017-09-04 11:36:04 +03:00
} elseif ($change['payment']) {
2018-09-21 12:22:49 +03:00
if ($orders[$change['order']['id']]['payments'][$change['payment']['id']]) {
2017-09-04 11:36:04 +03:00
$orders[$change['order']['id']]['payments'][$change['payment']['id']] = array_merge($orders[$change['order']['id']]['payments'][$change['payment']['id']], $change['payment']);
} else {
$orders[$change['order']['id']]['payments'][$change['payment']['id']] = $change['payment'];
}
if (empty($change['oldValue']) && $change['field'] == 'payments') {
$orders[$change['order']['id']]['payments'][$change['payment']['id']]['create'] = 1;
unset($orders[$change['order']['id']]['payments'][$change['payment']['id']]['delete']);
}
if (empty($change['newValue']) && $change['field'] == 'payments') {
$orders[$change['order']['id']]['payments'][$change['payment']['id']]['delete'] = 1;
}
if (!$orders[$change['order']['id']]['payments'][$change['payment']['id']]['create'] && $fields['payment'][$change['field']]) {
$orders[$change['order']['id']]['payments'][$change['payment']['id']][$fields['payment'][$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;
}
2018-09-21 12:22:49 +03:00
}
if ($change['field'] == 'last_name') {
if (true == is_null($change['newValue'])) {
$orders[$change['order']['id']]['lastName'] = 'clear';
}
}
if ($change['field'] == 'first_Name') {
if (true == is_null($change['newValue'])) {
$orders[$change['order']['id']]['firstName'] = 'clear';
}
}
if ($change['field'] == 'patronymic') {
if (true == is_null($change['newValue'])) {
$orders[$change['order']['id']]['patronymic'] = 'clear';
}
}
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
2016-09-15 16:42:10 +03:00
return $orders;
}
2020-08-25 11:14:47 +03:00
/**
* Filters out history by these terms:
* - Changes from current API key will be added only if CMS changes are more actual than history.
* - All other changes will be merged as usual.
* It fixes these problems:
* - Changes from current API key are merged when it's not needed.
* - Changes from CRM can overwrite more actual changes from CMS due to ignoring current API key changes.
*
* @param array $historyEntries Raw history from CRM
* @param string $recordType Entity field name, e.g. `customer` or `order`.
*
* @return array
*/
private static function filterHistory($historyEntries, $recordType)
{
$history = [];
$organizedHistory = [];
$notOurChanges = [];
2020-08-25 11:14:47 +03:00
foreach ($historyEntries as $entry) {
if (!isset($entry[$recordType]['externalId'])) {
if ($entry['source'] == 'api'
&& isset($change['apiKey']['current'])
&& $entry['apiKey']['current'] == true
&& $entry['field'] != 'externalId'
) {
continue;
}
2020-08-25 11:14:47 +03:00
$history[] = $entry;
2020-08-25 11:14:47 +03:00
continue;
}
2020-08-25 11:14:47 +03:00
$externalId = $entry[$recordType]['externalId'];
$field = $entry['field'];
2020-08-25 11:14:47 +03:00
if (!isset($organizedHistory[$externalId])) {
$organizedHistory[$externalId] = [];
}
2020-08-25 11:14:47 +03:00
if (!isset($notOurChanges[$externalId])) {
$notOurChanges[$externalId] = [];
}
2020-08-25 11:14:47 +03:00
if ($entry['source'] == 'api'
&& isset($entry['apiKey']['current'])
&& $entry['apiKey']['current'] == true
) {
if (isset($notOurChanges[$externalId][$field]) || $entry['field'] == 'externalId') {
$organizedHistory[$externalId][] = $entry;
} else {
continue;
}
} else {
$organizedHistory[$externalId][] = $entry;
$notOurChanges[$externalId][$field] = true;
}
}
2020-08-25 11:14:47 +03:00
unset($notOurChanges);
2020-08-25 11:14:47 +03:00
foreach ($organizedHistory as $historyChunk) {
$history = array_merge($history, $historyChunk);
}
2020-08-25 11:14:47 +03:00
return $history;
}
/**
* Update shipment in order
*
* @param \Bitrix\Sale\Order $bitrixOrder
* @param array $optionsDelivTypes
* @param array $crmOrder
2018-09-21 12:22:49 +03:00
*
* @return bool|null
* @throws \Bitrix\Main\ArgumentException
* @throws \Bitrix\Main\ArgumentNullException
* @throws \Bitrix\Main\ObjectNotFoundException
* @throws \Bitrix\Main\SystemException
*/
public static function deliveryUpdate(Bitrix\Sale\Order $bitrixOrder, $optionsDelivTypes, $crmOrder)
2016-10-04 17:57:39 +03:00
{
if (!$bitrixOrder instanceof Bitrix\Sale\Order) {
2017-09-04 11:36:04 +03:00
return false;
}
2016-09-15 16:42:10 +03:00
if ($bitrixOrder->getId()) {
$update = true;
2016-10-04 17:57:39 +03:00
} else {
$update = false;
2016-10-04 17:57:39 +03:00
}
$crmCode = $crmOrder['delivery']['code'] ?? false;
$noDeliveryId = EmptyDeliveryService::getEmptyDeliveryServiceId();
if ($crmCode === false || !isset($optionsDelivTypes[$crmCode])) {
$deliveryId = $noDeliveryId;
} else {
$deliveryId = $optionsDelivTypes[$crmCode];
2016-10-04 17:57:39 +03:00
if (isset($crmOrder['delivery']['service']['code'])) {
$deliveryCode = Manager::getCodeById($deliveryId);
$serviceCode = $crmOrder['delivery']['service']['code'];
2019-09-17 18:10:30 +03:00
$service = Manager::getService($deliveryId);
2019-10-08 16:23:18 +03:00
if (is_object($service)) {
$services = $service->getProfilesList();
if (!array_key_exists($serviceCode, $services)) {
$serviceCode = strtoupper($serviceCode);
$serviceCode = str_replace(array('-'), "_", $serviceCode);
}
2019-04-18 09:52:35 +03:00
}
if ($deliveryCode) {
try {
$deliveryService = Manager::getObjectByCode($deliveryCode . ':' . $serviceCode);
} catch (SystemException $systemException) {
RCrmActions::eventLog('RetailCrmHistory::deliveryEdit', '\Bitrix\Sale\Delivery\Services\Manager::getObjectByCode', $systemException->getMessage());
2016-10-04 17:57:39 +03:00
}
if (isset($deliveryService)) {
$deliveryId = $deliveryService->getId();
2016-10-04 17:57:39 +03:00
}
}
}
}
$delivery = Manager::getObjectById($deliveryId);
$shipmentColl = $bitrixOrder->getShipmentCollection();
if ($delivery) {
//В коллекции всегда есть одна скрытая системная доставка, к которой относятся нераспределенные товары
//Поэтому, если есть только системная доставка, то нужно создать новую
if (!$update || $shipmentColl->count() === 1) {
$shipment = $shipmentColl->createItem($delivery);
$shipment->setFields([
'BASE_PRICE_DELIVERY' => $crmOrder['delivery']['cost'],
'PRICE_DELIVERY' => $crmOrder['delivery']['cost'],
'CURRENCY' => $bitrixOrder->getCurrency(),
'DELIVERY_NAME' => $delivery->getName(),
'CUSTOM_PRICE_DELIVERY' => 'Y'
]);
} else {
foreach ($shipmentColl as $shipment) {
if (!$shipment->isSystem()) {
$shipment->setFields([
'BASE_PRICE_DELIVERY' => $crmOrder['delivery']['cost'],
'PRICE_DELIVERY' => $crmOrder['delivery']['cost'],
'CURRENCY' => $bitrixOrder->getCurrency(),
'DELIVERY_ID' => $deliveryId,
'DELIVERY_NAME' => $delivery->getName(),
2018-02-27 15:29:43 +03:00
'CUSTOM_PRICE_DELIVERY' => 'Y'
]);
}
2016-10-04 17:57:39 +03:00
}
}
}
return true;
2018-01-12 11:14:33 +03:00
}
2018-01-12 11:14:33 +03:00
/**
* Update shipment item colletion
2018-09-21 12:22:49 +03:00
*
2018-02-27 15:29:43 +03:00
* @param \Bitrix\Sale\Order $order
2018-09-21 12:22:49 +03:00
*
2018-01-12 11:14:33 +03:00
* @return void | boolean
*/
public static function shipmentItemReset($order)
{
$shipmentCollection = $order->getShipmentCollection();
$basket = $order->getBasket();
foreach ($shipmentCollection as $shipment) {
if (!$shipment->isSystem()) {
2018-02-27 15:29:43 +03:00
$reserved = false;
2018-03-22 16:11:04 +03:00
if ($shipment->needReservation()) {
2018-02-27 15:29:43 +03:00
$reserved = true;
}
2018-01-12 11:14:33 +03:00
$shipmentItemColl = $shipment->getShipmentItemCollection();
2018-02-27 15:29:43 +03:00
if ($reserved === true) {
$shipment->tryUnreserve();
}
2018-01-12 11:14:33 +03:00
try {
2018-02-27 15:29:43 +03:00
$shipmentItemColl->resetCollection($basket);
if ($reserved === true) {
$shipment->tryReserve();
}
2018-01-12 11:14:33 +03:00
} catch (\Bitrix\Main\NotSupportedException $NotSupportedException) {
RCrmActions::eventLog('RetailCrmHistory::shipmentItemReset', '\Bitrix\Sale\ShipmentItemCollection::resetCollection()', $NotSupportedException->getMessage());
return false;
}
}
}
2016-10-04 17:57:39 +03:00
}
2018-02-27 15:29:43 +03:00
/**
* Unreserve items if order canceled
2018-09-21 12:22:49 +03:00
*
2018-02-27 15:29:43 +03:00
* @param \Bitrix\Sale\Order $order
2018-09-21 12:22:49 +03:00
*
2018-02-27 15:29:43 +03:00
* @return void | boolean
*/
public static function unreserveShipment($order)
{
$shipmentCollection = $order->getShipmentCollection();
foreach ($shipmentCollection as $shipment) {
if (!$shipment->isSystem()) {
try {
$shipment->tryUnreserve();
} catch (ArgumentOutOfRangeException $ArgumentOutOfRangeException) {
2018-02-27 15:29:43 +03:00
RCrmActions::eventLog('RetailCrmHistory::unreserveShipment', '\Bitrix\Sale\Shipment::tryUnreserve()', $ArgumentOutOfRangeException->getMessage());
return false;
} catch (NotSupportedException $NotSupportedException) {
2018-02-27 15:29:43 +03:00
RCrmActions::eventLog('RetailCrmHistory::unreserveShipment', '\Bitrix\Sale\Shipment::tryUnreserve()', $NotSupportedException->getMessage());
return false;
}
}
}
}
2018-01-12 11:14:33 +03:00
/**
* Update payment in order
2018-09-21 12:22:49 +03:00
*
2018-01-12 11:14:33 +03:00
* @param object $order
* @param array $paymentsCrm
* @param array $newHistoryPayments
2018-09-21 12:22:49 +03:00
*
2018-01-12 11:14:33 +03:00
* @return void
*/
2018-03-22 16:11:04 +03:00
public static function paymentsUpdate($order, $paymentsCrm, &$newHistoryPayments = array())
2016-10-04 17:57:39 +03:00
{
2017-09-04 11:36:04 +03:00
$optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0)));
$optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)));
$allPaymentSystems = RCrmActions::PaymentList();
foreach ($allPaymentSystems as $allPaymentSystem) {
$arPaySysmems[$allPaymentSystem['ID']] = $allPaymentSystem['NAME'];
}
$paymentsList = array();
$paymentColl = $order->getPaymentCollection();
foreach ($paymentColl as $paymentData) {
$data = $paymentData->getFields()->getValues();
$paymentsList[$data['ID']] = $paymentData;
}
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
//data from crm
$paySumm = 0;
foreach ($paymentsCrm['payments'] as $paymentCrm) {
2017-11-13 11:05:11 +03:00
if (isset($paymentCrm['externalId']) && !empty($paymentCrm['externalId'])) {
2017-09-04 11:36:04 +03:00
//find the payment
2019-09-17 18:10:30 +03:00
$nowPaymentId = RCrmActions::getFromPaymentExternalId($paymentCrm['externalId']);
$nowPayment = $paymentsList[$nowPaymentId];
2017-09-04 11:36:04 +03:00
//update data
if ($nowPayment instanceof Payment) {
2017-09-04 11:36:04 +03:00
$nowPayment->setField('SUM', $paymentCrm['amount']);
if ($optionsPayTypes[$paymentCrm['type']] != $nowPayment->getField('PAY_SYSTEM_ID')) {
$nowPayment->setField('PAY_SYSTEM_ID', $optionsPayTypes[$paymentCrm['type']]);
$nowPayment->setField('PAY_SYSTEM_NAME', $arPaySysmems[$optionsPayTypes[$paymentCrm['type']]]);
2016-09-15 16:42:10 +03:00
}
2017-09-04 11:36:04 +03:00
if (isset($optionsPayment[$paymentCrm['status']])) {
$nowPayment->setField('PAID', $optionsPayment[$paymentCrm['status']]);
}
2019-09-17 18:10:30 +03:00
unset($paymentsList[$nowPaymentId]);
2016-09-15 16:42:10 +03:00
}
2019-09-10 13:23:51 +03:00
} elseif (array_key_exists($paymentCrm['type'], $optionsPayTypes)) {
2018-01-12 11:14:33 +03:00
$newHistoryPayments[$paymentCrm['id']] = $paymentCrm;
2017-09-04 11:36:04 +03:00
$newPayment = $paymentColl->createItem();
$newPayment->setField('SUM', $paymentCrm['amount']);
$newPayment->setField('PAY_SYSTEM_ID', $optionsPayTypes[$paymentCrm['type']]);
$newPayment->setField('PAY_SYSTEM_NAME', $arPaySysmems[$optionsPayTypes[$paymentCrm['type']]]);
$newPayment->setField('PAID', $optionsPayment[$paymentCrm['status']] ? $optionsPayment[$paymentCrm['status']] : 'N');
$newPayment->setField('CURRENCY', $order->getCurrency());
2017-09-04 11:36:04 +03:00
$newPayment->setField('IS_RETURN', 'N');
$newPayment->setField('PRICE_COD', '0.00');
$newPayment->setField('EXTERNAL_PAYMENT', 'N');
$newPayment->setField('UPDATED_1C', 'N');
2018-01-12 11:14:33 +03:00
$newPayment->setField('XML_ID', $paymentCrm['id']);
2017-09-04 11:36:04 +03:00
$newPaymentId = $newPayment->getId();
unset($paymentsList[$newPaymentId]);
2019-09-10 13:29:23 +03:00
} else {
RCrmActions::eventLog('RetailCrmHistory::orderHistory', 'paymentsUpdate', 'Save payment error, incorrect type: ' . $paymentCrm['type']);
2016-09-15 16:42:10 +03:00
}
2017-11-13 11:05:11 +03:00
2017-09-04 11:36:04 +03:00
if ($optionsPayment[$paymentCrm['status']] == 'Y') {
$paySumm += $paymentCrm['amount'];
}
}
foreach ($paymentsList as $payment) {
if ($payment->isPaid()) {
$payment->setPaid("N");
2016-09-15 16:42:10 +03:00
}
2017-09-04 11:36:04 +03:00
$payment->delete();
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
2017-09-04 11:36:04 +03:00
if ($paymentsCrm['totalSumm'] == $paySumm) {
$order->setFieldNoDemand('PAYED', 'Y');
} else {
$order->setFieldNoDemand('PAYED', 'N');
}
2016-09-15 16:42:10 +03:00
}
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();
2017-09-04 11:36:04 +03:00
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);
}
2017-09-04 11:36:04 +03:00
2016-09-15 16:42:10 +03:00
$outputArray[$key] = $element;
}
}
}
return $outputArray;
}
2018-09-21 12:22:49 +03:00
2020-04-24 13:18:18 +03:00
/**
* setProp
*
* @param \Bitrix\Sale\PropertyValueBase|\Bitrix\Sale\Order $obj
* @param string $value
* @param string $prop
*
* @return bool
* @throws \Bitrix\Main\ArgumentNullException
* @throws \Bitrix\Main\ArgumentOutOfRangeException
* @throws \Bitrix\Main\NotImplementedException
* @throws \Bitrix\Main\ObjectNotFoundException
* @throws \Bitrix\Main\ArgumentException
*/
2017-11-13 11:05:11 +03:00
public static function setProp($obj, $value = '', $prop = '')
2016-10-04 17:57:39 +03:00
{
2020-04-24 13:18:18 +03:00
if (!isset($obj) || empty($obj)) {
2016-10-03 16:56:59 +03:00
return false;
}
2022-04-13 17:07:58 +03:00
if ($prop && $value || $prop && !$value) {
2016-09-15 16:42:10 +03:00
$obj->setField($prop, $value);
2017-11-13 11:05:11 +03:00
} elseif ($value && !$prop) {
2016-09-15 16:42:10 +03:00
$obj->setValue($value);
2017-11-13 11:05:11 +03:00
} elseif (!$value && !$prop) {
2016-09-15 16:42:10 +03:00
$obj->delete();
}
return true;
}
2018-09-21 12:22:49 +03:00
2016-10-04 17:57:39 +03:00
public static function getExistsItem($basket, $moduleId, $productId)
{
2017-09-04 11:36:04 +03:00
foreach ($basket as $basketItem) {
$itemExists = ($basketItem->getField('PRODUCT_ID') == $productId && $basketItem->getField('MODULE') == $moduleId);
2016-09-15 16:42:10 +03:00
2017-09-04 11:36:04 +03:00
if ($itemExists) {
2016-09-15 16:42:10 +03:00
return $basketItem;
2017-09-04 11:36:04 +03:00
}
}
2016-09-15 16:42:10 +03:00
2017-09-04 11:36:04 +03:00
return false;
}
2018-09-21 12:22:49 +03:00
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');
2017-09-04 11:36:04 +03:00
$catalog = CCatalogProduct::GetByID($offerId);
2016-10-03 16:56:59 +03:00
$info = array(
'NAME' => $elementInfo['NAME'],
'URL' => $url,
2018-02-27 15:29:43 +03:00
'DIMENSIONS' => serialize(array(
2017-09-04 11:36:04 +03:00
'WIDTH' => $catalog['WIDTH'],
'HEIGHT' => $catalog['HEIGHT'],
'LENGTH' => $catalog['LENGTH'],
2018-02-27 15:29:43 +03:00
)),
'WEIGHT' => $catalog['WEIGHT'],
'XML_ID' => $elementInfo["XML_ID"],
'IBLOCK_XML_ID' => $elementInfo["IBLOCK_EXTERNAL_ID"]
2016-10-03 16:56:59 +03:00
);
2018-09-21 12:22:49 +03:00
2016-10-03 16:56:59 +03:00
return $info;
2016-09-15 16:42:10 +03:00
}
2018-09-21 12:22:49 +03:00
/**
* @param $order
*
* @return boolean
*/
private static function orderSave($order)
{
try {
$order->save();
return true;
} catch (\Exception $exception) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Order saving',
$exception->getMessage()
);
return false;
}
}
2020-02-18 10:54:42 +03:00
/**
* Truncate a float number
*
* @param float $val
* @param int f Number of precision
*
* @return float
*/
public static function truncate($val, $precision = "0")
{
if(($p = strpos($val, '.')) !== false
|| ($p = strpos($val, ',')) !== false
) {
$val = floatval(substr($val, 0, $p + 1 + $precision));
}
return $val;
}
2016-09-15 16:42:10 +03:00
/**
* @param int $externalId
*
* @return void
*/
public static function cancelOrder(int $externalId)
2016-09-15 16:42:10 +03:00
{
try {
$newOrder = Order::load($externalId);
} catch (ArgumentNullException $e) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::load',
$e->getMessage() . ': ' . $externalId
);
2017-09-04 11:36:04 +03:00
return;
}
if (!$newOrder instanceof Order) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::load',
'Error order load: ' . $externalId
2017-09-04 11:36:04 +03:00
);
return;
}
try {
$newOrder->setField('CANCELED', 'Y');
$newOrder->save();
} catch (Exception $exception) {
RCrmActions::eventLog(
'RetailCrmHistory::orderHistory',
'Bitrix\Sale\Order::cancelOrder',
'Error order canceled: ' . $externalId
);
2016-09-15 16:42:10 +03:00
}
}
}