From 9354bca0b31dfb6273ca263b9c8fba9c6352dd78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B5=D1=80=D0=B3=D0=B5=D0=B9=20=D0=A7=D0=B0=D0=B7?= =?UTF-8?q?=D0=BE=D0=B2?= <45812598+Chazovs@users.noreply.github.com> Date: Wed, 8 Sep 2021 10:19:29 +0300 Subject: [PATCH] multisite order export bug (#208) --- .../classes/general/RCrmActions.php | 61 +-- .../classes/general/events/RetailCrmEvent.php | 367 +++++++++--------- .../general/history/RetailCrmHistory_v5.php | 45 ++- .../general/order/RetailCrmOrder_v5.php | 171 ++++---- intaro.retailcrm/install/index.php | 11 +- intaro.retailcrm/install/step2.php | 67 ++-- intaro.retailcrm/install/step3.php | 181 +++++---- intaro.retailcrm/options.php | 5 +- .../general/order/RetailCrmOrderTest.php | 0 9 files changed, 475 insertions(+), 433 deletions(-) create mode 100644 tests/classes/general/order/RetailCrmOrderTest.php diff --git a/intaro.retailcrm/classes/general/RCrmActions.php b/intaro.retailcrm/classes/general/RCrmActions.php index 971c7583..2c5f3230 100644 --- a/intaro.retailcrm/classes/general/RCrmActions.php +++ b/intaro.retailcrm/classes/general/RCrmActions.php @@ -1,5 +1,11 @@ 'Y')); + $arSites = []; + $rsSites = CSite::GetList($by, $sort, ['ACTIVE' => 'Y']); + while ($ar = $rsSites->Fetch()) { $arSites[] = $ar; } @@ -44,7 +53,7 @@ class RCrmActions { $bitrixDeliveryTypesList = array(); $arDeliveryServiceAll = \Bitrix\Sale\Delivery\Services\Manager::getActiveList(); - $noOrderId = \Bitrix\Sale\Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId(); + $noOrderId = EmptyDeliveryService::getEmptyDeliveryServiceId(); $groups = array(); foreach ($arDeliveryServiceAll as $arDeliveryService) { if ($arDeliveryService['CLASS_NAME'] == '\Bitrix\Sale\Delivery\Services\Group') { @@ -69,7 +78,7 @@ class RCrmActions public static function PaymentList() { $bitrixPaymentTypesList = array(); - $dbPaymentAll = \Bitrix\Sale\PaySystem\Manager::getList(array( + $dbPaymentAll = Manager::getList(array( 'select' => array('ID', 'NAME'), 'filter' => array('ACTIVE' => 'Y') )); @@ -83,9 +92,9 @@ class RCrmActions public static function StatusesList() { $bitrixPaymentStatusesList = array(); - $obStatuses = \Bitrix\Sale\Internals\StatusTable::getList(array( + $obStatuses = StatusTable::getList(array( 'filter' => array('TYPE' => 'O', '=Bitrix\Sale\Internals\StatusLangTable:STATUS.LID' => LANGUAGE_ID), - 'select' => array('ID', "NAME" => 'Bitrix\Sale\Internals\StatusLangTable:STATUS.NAME') + 'select' => array('ID', 'NAME' => 'Bitrix\Sale\Internals\StatusLangTable:STATUS.NAME') )); while ($arStatus = $obStatuses->fetch()) { $bitrixPaymentStatusesList[$arStatus['ID']] = array( @@ -100,7 +109,7 @@ class RCrmActions public static function OrderPropsList() { $bitrixPropsList = array(); - $arPropsAll = \Bitrix\Sale\Internals\OrderPropsTable::getList(array( + $arPropsAll = OrderPropsTable::getList(array( 'select' => array('*'), 'filter' => array('CODE' => '_%') )); @@ -133,7 +142,7 @@ class RCrmActions public static function StoresExportList() { $catalogExportStores = array(); - $dbStores = CCatalogStore::GetList(array(), array("ACTIVE" => "Y"), false, false, array('ID', 'TITLE')); + $dbStores = CCatalogStore::GetList(array(), array('ACTIVE' => 'Y'), false, false, array('ID', 'TITLE')); while ($stores = $dbStores->Fetch()) { $catalogExportStores[] = $stores; } @@ -144,10 +153,10 @@ class RCrmActions public static function IblocksExportList() { $catalogExportIblocks = array(); - $dbIblocks = CIBlock::GetList(array("IBLOCK_TYPE" => "ASC", "NAME" => "ASC"), array('CHECK_PERMISSIONS' => 'Y','MIN_PERMISSION' => 'W')); + $dbIblocks = CIBlock::GetList(array('IBLOCK_TYPE' => 'ASC', 'NAME' => 'ASC'), array('CHECK_PERMISSIONS' => 'Y', 'MIN_PERMISSION' => 'W')); while ($iblock = $dbIblocks->Fetch()) { - if ($arCatalog = CCatalog::GetByIDExt($iblock["ID"])) { - if($arCatalog['CATALOG_TYPE'] == "D" || $arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") { + if ($arCatalog = CCatalog::GetByIDExt($iblock['ID'])) { + if($arCatalog['CATALOG_TYPE'] == 'D' || $arCatalog['CATALOG_TYPE'] == 'X' || $arCatalog['CATALOG_TYPE'] == 'P') { $catalogExportIblocks[$iblock['ID']] = array( 'ID' => $iblock['ID'], 'IBLOCK_TYPE_ID' => $iblock['IBLOCK_TYPE_ID'], @@ -156,8 +165,8 @@ class RCrmActions 'NAME' => $iblock['NAME'], ); - if ($arCatalog['CATALOG_TYPE'] == "X" || $arCatalog['CATALOG_TYPE'] == "P") { - $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock["ID"]); + if ($arCatalog['CATALOG_TYPE'] == 'X' || $arCatalog['CATALOG_TYPE'] == 'P') { + $iblockOffer = CCatalogSKU::GetInfoByProductIBlock($iblock['ID']); $catalogExportIblocks[$iblock['ID']]['SKU'] = $iblockOffer; } } @@ -175,11 +184,11 @@ class RCrmActions public static function eventLog($auditType, $itemId, $description) { CEventLog::Add(array( - "SEVERITY" => "SECURITY", - "AUDIT_TYPE_ID" => $auditType, - "MODULE_ID" => self::$MODULE_ID, - "ITEM_ID" => $itemId, - "DESCRIPTION" => $description, + 'SEVERITY' => 'SECURITY', + 'AUDIT_TYPE_ID' => $auditType, + 'MODULE_ID' => self::$MODULE_ID, + 'ITEM_ID' => $itemId, + 'DESCRIPTION' => $description, )); } @@ -373,7 +382,7 @@ class RCrmActions if (empty($fio)) { return $result; } else { - $newFio = explode(" ", $fio, 3); + $newFio = explode(' ', $fio, 3); } switch (count($newFio)) { @@ -490,7 +499,7 @@ class RCrmActions if (!$result) { $err = new RuntimeException( - $methodApi . ": Got null instead of valid result!" + $methodApi . ': Got null instead of valid result!' ); Logger::getInstance()->write(sprintf( '%s%s%s', @@ -548,7 +557,7 @@ class RCrmActions return false; } - } catch (\RetailCrm\Exception\CurlException $e) { + } catch (CurlException $e) { static::logException( $method, $methodApi, @@ -572,7 +581,7 @@ class RCrmActions ); return false; - } catch (\RetailCrm\Exception\InvalidJsonException $e) { + } catch (InvalidJsonException $e) { static::logException( $method, $methodApi, diff --git a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php index 45f6d2eb..15b5e74b 100644 --- a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php +++ b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php @@ -1,6 +1,8 @@ getParameter("ENTITY"); + $obOrder = $event->getParameter('ENTITY'); } else { RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error'); - + return false; } + $arOrder = RetailCrmOrder::orderObjToArr($obOrder); - + $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); - + //params $optionsOrderTypes = RetailcrmConfigProvider::getOrderTypes(); $optionsDelivTypes = RetailcrmConfigProvider::getDeliveryTypes(); @@ -157,23 +151,23 @@ class RetailCrmEvent $optionsLegalDetails = RetailcrmConfigProvider::getLegalDetails(); $optionsContragentType = RetailcrmConfigProvider::getContragentTypes(); $optionsCustomFields = RetailcrmConfigProvider::getCustomFields(); - + //corp cliente swich $optionCorpClient = RetailcrmConfigProvider::getCorporateClientStatus(); - - $arParams = RCrmActions::clearArr(array( - 'optionsOrderTypes' => $optionsOrderTypes, - 'optionsDelivTypes' => $optionsDelivTypes, - 'optionsPayTypes' => $optionsPayTypes, - 'optionsPayStatuses' => $optionsPayStatuses, - 'optionsPayment' => $optionsPayment, - 'optionsOrderProps' => $optionsOrderProps, - 'optionsLegalDetails' => $optionsLegalDetails, + + $arParams = RCrmActions::clearArr([ + 'optionsOrderTypes' => $optionsOrderTypes, + 'optionsDelivTypes' => $optionsDelivTypes, + 'optionsPayTypes' => $optionsPayTypes, + 'optionsPayStatuses' => $optionsPayStatuses, + 'optionsPayment' => $optionsPayment, + 'optionsOrderProps' => $optionsOrderProps, + 'optionsLegalDetails' => $optionsLegalDetails, 'optionsContragentType' => $optionsContragentType, - 'optionsSitesList' => $optionsSitesList, - 'optionsCustomFields' => $optionsCustomFields - )); - + 'optionsSitesList' => $optionsSitesList, + 'optionsCustomFields' => $optionsCustomFields, + ]); + //many sites? if ($optionsSitesList) { if (array_key_exists($arOrder['LID'], $optionsSitesList) && $optionsSitesList[$arOrder['LID']] !== null) { @@ -184,7 +178,7 @@ class RetailCrmEvent } elseif (!$optionsSitesList) { $site = null; } - + //new order? $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site); if (isset($orderCrm['order'])) { @@ -193,9 +187,8 @@ class RetailCrmEvent } else { $methodApi = 'ordersCreate'; } - + $orderCompany = null; - if ('Y' === $optionCorpClient) { if (true === RetailCrmCorporateClient::isCorpTookExternalId((string) $arOrder['USER_ID'], $api)) { RetailCrmCorporateClient::setPrefixForExternalId((string) $arOrder['USER_ID'], $api); @@ -204,62 +197,62 @@ class RetailCrmEvent //TODO эта управляющая конструкция по функционалу дублирует RetailCrmOrder::createCustomerForOrder. // Необходимо устранить дублирование, вынеся логику в обособленный класс-сервис - if ("Y" === $optionCorpClient && $optionsContragentType[$arOrder['PERSON_TYPE_ID']] == 'legal-entity') { + if ('Y' === $optionCorpClient && $optionsContragentType[$arOrder['PERSON_TYPE_ID']] === 'legal-entity') { //corparate cliente $nickName = ''; $address = ''; $corpAddress = ''; - $contragent = array(); - $userCorp = array(); + $contragent = []; + $userCorp = []; $corpName = RetailcrmConfigProvider::getCorporateClientName(); $corpAddress = RetailcrmConfigProvider::getCorporateClientAddress(); - + foreach ($arOrder['PROPS']['properties'] as $prop) { - if ($prop['CODE'] == $corpName) { + if ($prop['CODE'] === $corpName) { $nickName = $prop['VALUE'][0]; } - - if ($prop['CODE'] == $corpAddress) { + + if ($prop['CODE'] === $corpAddress) { $address = $prop['VALUE'][0]; } - + if (!empty($optionsLegalDetails) && $search = array_search($prop['CODE'], $optionsLegalDetails[$arOrder['PERSON_TYPE_ID']]) ) { $contragent[$search] = $prop['VALUE'][0];//legal order data } } - + if (!empty($contragentType)) { $contragent['contragentType'] = $contragentType; } - + $customersCorporate = false; - $response = $api->customersCorporateList(array('companyName' => $nickName)); - + $response = $api->customersCorporateList(['companyName' => $nickName]); + if ($response && $response->getStatusCode() == 200) { $customersCorporate = $response['customersCorporate']; $singleCorp = reset($customersCorporate); - + if (!empty($singleCorp)) { $userCorp['customerCorporate'] = $singleCorp; $companiesResponse = $api->customersCorporateCompanies( $singleCorp['id'], - array(), + [], null, null, 'id', $site ); - + if ($companiesResponse && $companiesResponse->isSuccessful()) { $orderCompany = array_reduce( $companiesResponse['companies'], function ($carry, $item) use ($nickName) { - if (is_array($item) && $item['name'] == $nickName) { + if (is_array($item) && $item['name'] === $nickName) { $carry = $item; } - + return $carry; }, null @@ -272,35 +265,35 @@ class RetailCrmEvent 'ApiClient::customersCorporateList', 'error during fetching corporate customers' ); - + return false; } - + //user $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site); - + if (!isset($userCrm['customer'])) { $arUser = Bitrix\Main\UserTable::getById($arOrder['USER_ID'])->fetch(); - + if (!empty($address)) { $arUser['PERSONAL_STREET'] = $address; } - - $resultUser = RetailCrmUser::customerSend($arUser, $api, "individual", true, $site); - + + $resultUser = RetailCrmUser::customerSend($arUser, $api, 'individual', true, $site); + if (!$resultUser) { RCrmActions::eventLog( __CLASS__ . '::' . __METHOD__, 'RetailCrmUser::customerSend', 'error during creating customer' ); - + return false; } - - $userCrm = array('customer' => array('externalId' => $arOrder['USER_ID'])); + + $userCrm = ['customer' => ['externalId' => $arOrder['USER_ID']]]; } - + if (!isset($userCorp['customerCorporate'])) { $resultUserCorp = RetailCrmCorporateClient::clientSend( $arOrder, @@ -310,78 +303,78 @@ class RetailCrmEvent false, $site ); - + Logger::getInstance()->write($resultUserCorp, 'resultUserCorp'); - + if (!$resultUserCorp) { RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmCorporateClient::clientSend', 'error during creating client'); - + return false; } - + $arParams['customerCorporate'] = $resultUserCorp; - $arParams['orderCompany'] = isset($resultUserCorp['mainCompany']) ? $resultUserCorp['mainCompany'] : null; - - $customerCorporateAddress = array(); - $customerCorporateCompany = array(); + $arParams['orderCompany'] = $resultUserCorp['mainCompany'] ?? null; + + $customerCorporateAddress = []; + $customerCorporateCompany = []; $addressResult = null; $companyResult = null; - + if (!empty($address)) { //TODO address builder add - $customerCorporateAddress = array( - 'name' => $nickName, + $customerCorporateAddress = [ + 'name' => $nickName, 'isMain' => true, - 'text' => $address - ); - + 'text' => $address, + ]; + $addressResult = $api->customersCorporateAddressesCreate($resultUserCorp['id'], $customerCorporateAddress, 'id', $site); } - - $customerCorporateCompany = array( - 'name' => $nickName, - 'isMain' => true, - 'contragent' => $contragent - ); - + + $customerCorporateCompany = [ + 'name' => $nickName, + 'isMain' => true, + 'contragent' => $contragent, + ]; + if (!empty($addressResult)) { - $customerCorporateCompany['address'] = array( - 'id' => $addressResult['id'] - ); + $customerCorporateCompany['address'] = [ + 'id' => $addressResult['id'], + ]; } - + $companyResult = $api->customersCorporateCompaniesCreate($resultUserCorp['id'], $customerCorporateCompany, 'id', $site); - - $customerCorporateContact = array( - 'isMain' => true, - 'customer' => array( + + $customerCorporateContact = [ + 'isMain' => true, + 'customer' => [ 'externalId' => $arOrder['USER_ID'], - 'site' => $site - ) - ); - + 'site' => $site, + ], + ]; + if (!empty($companyResult)) { - $orderCompany = array( - 'id' => $companyResult['id'] - ); - - $customerCorporateContact['companies'] = array( - array( - 'company' => $orderCompany - ) - ); + $orderCompany = [ + 'id' => $companyResult['id'], + ]; + + $customerCorporateContact['companies'] = [ + [ + 'company' => $orderCompany, + ], + ]; } - + $api->customersCorporateContactsCreate( $resultUserCorp['id'], $customerCorporateContact, 'id', $site ); - + $arParams['orderCompany'] = array_merge( $customerCorporateCompany, - array('id' => $companyResult['id']) + ['id' => $companyResult['id']] ); } else { RetailCrmCorporateClient::addCustomersCorporateAddresses( @@ -391,14 +384,14 @@ class RetailCrmEvent $api, $site = null ); - + $arParams['customerCorporate'] = $userCorp['customerCorporate']; - + if (!empty($orderCompany)) { $arParams['orderCompany'] = $orderCompany; } } - + $arParams['contactExId'] = $userCrm['customer']['externalId']; } else { //user @@ -408,29 +401,27 @@ class RetailCrmEvent $resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site); if (!$resultUser) { RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer'); - + return false; } } } - if (isset($arOrder['RESPONSIBLE_ID']) && !empty($arOrder['RESPONSIBLE_ID'])) { $managerService = ManagerService::getInstance(); $arParams['managerId'] = $managerService->getManagerCrmId($arOrder['RESPONSIBLE_ID']); } - //order $resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi); - + if (!$resultOrder) { RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order'); - + return false; } - + return true; } - + /** * @param \Bitrix\Sale\Payment $event * @@ -438,35 +429,35 @@ class RetailCrmEvent * @throws InvalidArgumentException * */ - function paymentSave($event) + public function paymentSave(Payment $event) { $apiVersion = COption::GetOptionString(self::$MODULE_ID, 'api_version', 0); - + /** @var \Bitrix\Sale\Order $order */ $order = $event->getCollection()->getOrder(); - + if ((isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) - || $apiVersion != 'v5' + || $apiVersion !== 'v5' || $order->isNew() ) { return false; } - + $optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsPaymentTypes = RetailcrmConfigProvider::getPaymentTypes(); $optionsPayStatuses = RetailcrmConfigProvider::getPayment(); $integrationPaymentTypes = RetailcrmConfigProvider::getIntegrationPaymentTypes(); - - $arPayment = array( - 'ID' => $event->getId(), - 'ORDER_ID' => $event->getField('ORDER_ID'), - 'PAID' => $event->getField('PAID'), + + $arPayment = [ + 'ID' => $event->getId(), + 'ORDER_ID' => $event->getField('ORDER_ID'), + 'PAID' => $event->getField('PAID'), 'PAY_SYSTEM_ID' => $event->getField('PAY_SYSTEM_ID'), - 'SUM' => $event->getField('SUM'), - 'LID' => $order->getSiteId(), - 'DATE_PAID' => $event->getField('DATE_PAID'), - ); - + 'SUM' => $event->getField('SUM'), + 'LID' => $order->getSiteId(), + 'DATE_PAID' => $event->getField('DATE_PAID'), + ]; + if ($optionsSitesList) { if (array_key_exists($arPayment['LID'], $optionsSitesList) && $optionsSitesList[$arPayment['LID']] !== null) { $site = $optionsSitesList[$arPayment['LID']]; @@ -476,14 +467,14 @@ class RetailCrmEvent } elseif (!$optionsSitesList) { $site = null; } - + $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arPayment['ORDER_ID'], $site); - + if (isset($orderCrm['order'])) { $payments = $orderCrm['order']['payments']; } - + if ($payments) { foreach ($payments as $payment) { if (isset($payment['externalId'])) { @@ -496,33 +487,33 @@ class RetailCrmEvent } } } - + if (!empty($arPayment['PAY_SYSTEM_ID']) && isset($optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']])) { - $paymentToCrm = array( - 'type' => $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']] - ); - + $paymentToCrm = [ + 'type' => $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']], + ]; + if (!empty($arPayment['ID'])) { $paymentToCrm['externalId'] = RCrmActions::generatePaymentExternalId($arPayment['ID']); } - + if (!empty($arPayment['DATE_PAID'])) { if (is_object($arPayment['DATE_PAID'])) { - $culture = new Bitrix\Main\Context\Culture(array("FORMAT_DATETIME" => "YYYY-MM-DD HH:MI:SS")); + $culture = new Bitrix\Main\Context\Culture(['FORMAT_DATETIME' => 'YYYY-MM-DD HH:MI:SS']); $paymentToCrm['paidAt'] = $arPayment['DATE_PAID']->toString($culture); } elseif (is_string($arPayment['DATE_PAID'])) { $paymentToCrm['paidAt'] = $arPayment['DATE_PAID']; } } - + if (!empty($optionsPayStatuses[$arPayment['PAID']])) { $paymentToCrm['status'] = $optionsPayStatuses[$arPayment['PAID']]; } - + if (!empty($arPayment['ORDER_ID'])) { $paymentToCrm['order']['externalId'] = $arPayment['ORDER_ID']; } - + if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { $paymentToCrm['amount'] = $arPayment['SUM']; } @@ -530,17 +521,17 @@ class RetailCrmEvent RCrmActions::eventLog('RetailCrmEvent::paymentSave', 'payments', 'OrderID = ' . $arPayment['ID'] . '. Payment not found.'); return false; } - + $arPaymentExtId = RCrmActions::generatePaymentExternalId($arPayment['ID']); - + if (array_key_exists($arPaymentExtId, $paymentsExternalIds)) { $paymentData = $paymentsExternalIds[$arPaymentExtId]; } elseif (array_key_exists($arPayment['ID'], $paymentsExternalIds)) { $paymentData = $paymentsExternalIds[$arPayment['ID']]; } else { - $paymentData = array(); + $paymentData = []; } - + if (empty($paymentData)) { RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $paymentToCrm, $site); } elseif ($paymentData['type'] == $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']]) { @@ -552,7 +543,7 @@ class RetailCrmEvent ); return false; } - + $paymentToCrm['externalId'] = $paymentData['externalId']; RCrmActions::apiMethod($api, 'paymentEditByExternalId', __METHOD__, $paymentToCrm, $site); } elseif ($paymentData['type'] != $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']]) { @@ -564,34 +555,34 @@ class RetailCrmEvent ); RCrmActions::apiMethod($api, 'ordersPaymentCreate', __METHOD__, $paymentToCrm, $site); } - + return true; } - + /** * @param \Bitrix\Sale\Payment $event * * @throws InvalidArgumentException */ - function paymentDelete($event) + public function paymentDelete(Payment $event): void { $apiVersion = COption::GetOptionString(self::$MODULE_ID, 'api_version', 0); - + if ((isset($GLOBALS['RETAIL_CRM_HISTORY']) && $GLOBALS['RETAIL_CRM_HISTORY']) || $apiVersion != 'v5' || !$event->getId() ) { return; } - - $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0)); - - $arPayment = array( - 'ID' => $event->getId(), + + $optionsSitesList = RetailcrmConfigProvider::getSitesList(); + + $arPayment = [ + 'ID' => $event->getId(), 'ORDER_ID' => $event->getField('ORDER_ID'), - 'LID' => $event->getCollection()->getOrder()->getSiteId() - ); - + 'LID' => $event->getCollection()->getOrder()->getSiteId(), + ]; + if ($optionsSitesList) { if (array_key_exists($arPayment['LID'], $optionsSitesList) && $optionsSitesList[$arPayment['LID']] !== null) { $site = $optionsSitesList[$arPayment['LID']]; @@ -601,12 +592,12 @@ class RetailCrmEvent } elseif (!$optionsSitesList) { $site = null; } - + $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); + $api = new ApiClient($api_host, $api_key); $orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arPayment['ORDER_ID'], $site); - + if (isset($orderCrm['order']['payments']) && $orderCrm['order']['payments']) { foreach ($orderCrm['order']['payments'] as $payment) { if (isset($payment['externalId']) diff --git a/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php b/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php index d2f6c872..19a90222 100644 --- a/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php +++ b/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php @@ -236,7 +236,6 @@ class RetailCrmHistory $optionsPayStatuses = array_flip(RetailcrmConfigProvider::getPaymentStatuses()); // --statuses $optionsOrderProps = RetailcrmConfigProvider::getOrderProps(); $optionsLegalDetails = RetailcrmConfigProvider::getLegalDetails(); - $optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsOrderNumbers = RetailcrmConfigProvider::getOrderNumbers(); $optionsCanselOrder = RetailcrmConfigProvider::getCancellableOrderPaymentStatuses(); $currency = RetailcrmConfigProvider::getCurrencyOrDefault(); @@ -298,11 +297,7 @@ class RetailCrmHistory continue; } - if ($optionsSitesList) { - $site = array_search($order['site'], $optionsSitesList); - } else { - $site = CSite::GetDefSite(); - } + $site = self::getSite($order['site']); if (empty($site)) { RCrmActions::eventLog( @@ -537,20 +532,10 @@ class RetailCrmHistory continue; } + + $site = self::getSite($order['site']); - if (array_key_exists('managerId', $order)) { - $service = ManagerService::getInstance(); - - $newOrder->setField('RESPONSIBLE_ID', $service->getManagerBitrixId($order['managerId'])); - } - - if ($optionsSitesList) { - $site = array_search($order['site'], $optionsSitesList); - } else { - $site = CSite::GetDefSite(); - } - - if (empty($site)) { + if (null === $site) { RCrmActions::eventLog( 'RetailCrmHistory::orderHistory', 'Bitrix\Sale\Order::edit', @@ -1244,7 +1229,27 @@ class RetailCrmHistory return false; } - + + /** + * @param string $shopCode + * + * @return string|null + */ + public static function getSite(string $shopCode): ?string + { + $optionsSitesList = RetailcrmConfigProvider::getSitesList(); + + if ($optionsSitesList) { + $searchResult = array_search($shopCode, $optionsSitesList, true); + + return is_string($searchResult) ? $searchResult : null; + } + + $defaultSite = CSite::GetDefSite(); + + return is_string($defaultSite) ? $defaultSite : null; + } + /** * @param $array * @param $value diff --git a/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php b/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php index a16e2bc9..d7ba19f7 100644 --- a/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php +++ b/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php @@ -5,9 +5,9 @@ use Bitrix\Main\Context\Culture; use Bitrix\Main\UserTable; use Bitrix\Sale\Delivery\Services\Manager; use Bitrix\Sale\Internals\Fields; +use Bitrix\Sale\Internals\OrderTable; use Bitrix\Sale\Location\LocationTable; use Bitrix\Sale\Order; -use Bitrix\Sale\OrderTable; use RetailCrm\ApiClient; use Intaro\RetailCrm\Service\ManagerService; use RetailCrm\Response\ApiResponse; @@ -20,7 +20,6 @@ IncludeModuleLangFile(__FILE__); class RetailCrmOrder { /** - * * Creates order or returns order for mass upload * * @param array $arOrder @@ -93,7 +92,7 @@ class RetailCrmOrder $order['contragent']['contragentType'] = $arParams['optionsContragentType'][$arOrder['PERSON_TYPE_ID']]; - if ($methodApi == 'ordersEdit') { + if ($methodApi === 'ordersEdit') { $order['discountManualAmount'] = 0; $order['discountManualPercent'] = 0; } @@ -109,10 +108,10 @@ class RetailCrmOrder ) { $order['customFields'][$search] = $prop['VALUE'][0];//custom properties } elseif ($search = array_search($prop['CODE'], $arParams['optionsOrderProps'][$arOrder['PERSON_TYPE_ID']])) {//other - if (in_array($search, array('fio', 'phone', 'email'))) {//fio, phone, email - if ($search == 'fio') { + if (in_array($search, ['fio', 'phone', 'email'])) {//fio, phone, email + if ($search === 'fio') { $order = array_merge($order, RCrmActions::explodeFio($prop['VALUE'][0]));//add fio fields - } elseif ($search == 'email' && mb_strlen($prop['VALUE'][0]) > 100) { + } elseif ($search === 'email' && mb_strlen($prop['VALUE'][0]) > 100) { continue; } else { // ignoring a property with a non-set group if the field value is already set @@ -123,7 +122,7 @@ class RetailCrmOrder $order[$search] = $prop['VALUE'][0];//phone, email } } else {//address - if ($prop['TYPE'] == 'LOCATION' && isset($prop['VALUE'][0]) && $prop['VALUE'][0] != '') { + if ($prop['TYPE'] === 'LOCATION' && isset($prop['VALUE'][0]) && $prop['VALUE'][0] != '') { $arLoc = LocationTable::getByCode($prop['VALUE'][0])->fetch(); if ($arLoc) { $server = Context::getCurrent()->getServer()->getDocumentRoot(); @@ -136,14 +135,14 @@ class RetailCrmOrder } } - $location = \Bitrix\Sale\Location\Name\LocationTable::getList([ - 'filter' => ['=LOCATION_ID' => $arLoc['CITY_ID'], 'LANGUAGE_ID' => 'ru'], + $location = LocationTable::getList([ + 'filter' => ['=LOCATION_ID' => $arLoc['CITY_ID'], 'LANGUAGE_ID' => 'ru'] ])->fetch(); if (count($countrys) > 0) { - $countryOrder = \Bitrix\Sale\Location\Name\LocationTable::getList(array( - 'filter' => array('=LOCATION_ID' => $arLoc['COUNTRY_ID'], 'LANGUAGE_ID' => 'ru') - ))->fetch(); + $countryOrder = LocationTable::getList([ + 'filter' => ['=LOCATION_ID' => $arLoc['COUNTRY_ID'], 'LANGUAGE_ID' => 'ru'] + ])->fetch(); if(isset($countrys[$countryOrder['NAME']])){ $order['countryIso'] = $countrys[$countryOrder['NAME']]; } @@ -162,6 +161,7 @@ class RetailCrmOrder //deliverys if (array_key_exists($arOrder['DELIVERYS'][0]['id'], $arParams['optionsDelivTypes'])) { $order['delivery']['code'] = $arParams['optionsDelivTypes'][$arOrder['DELIVERYS'][0]['id']]; + if (isset($arOrder['DELIVERYS'][0]['service']) && $arOrder['DELIVERYS'][0]['service'] != '') { $order['delivery']['service']['code'] = $arOrder['DELIVERYS'][0]['service']; } @@ -172,7 +172,7 @@ class RetailCrmOrder $height = 0; $length = 0; - if ('ordersEdit' == $methodApi) { + if ('ordersEdit' === $methodApi) { $response = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $order['externalId']); if (isset($response['order'])) { foreach ($response['order']['items'] as $k => $item) { @@ -185,31 +185,32 @@ class RetailCrmOrder //basket foreach ($arOrder['BASKET'] as $position => $product) { $itemId = null; - $externalId = $position . "_" . $product['PRODUCT_ID']; + $externalId = $position . '_' . $product['PRODUCT_ID']; if (isset($orderItems[$externalId])) { //update $externalIds = $orderItems[$externalId]['externalIds']; $itemId = $orderItems[$externalId]['id']; - $key = array_search("bitrix", array_column($externalIds, 'code')); - if ($externalIds[$key]['code'] == "bitrix") { - $externalIds[$key] = array( + $key = array_search('bitrix', array_column($externalIds, 'code')); + + if ($externalIds[$key]['code'] === 'bitrix') { + $externalIds[$key] = [ 'code' => 'bitrix', 'value' => $externalId, - ); + ]; } else { - $externalIds[] = array( + $externalIds[] = [ 'code' => 'bitrix', 'value' => $externalId, - ); + ]; } } else { //create - $externalIds = array( - array( + $externalIds = [ + [ 'code' => 'bitrix', 'value' => $externalId, - ) - ); + ] + ]; } $item = [ @@ -226,16 +227,17 @@ class RetailCrmOrder $item['id'] = $itemId; } - $pp = CCatalogProduct::GetByID($product['PRODUCT_ID']); - if (is_null($pp['PURCHASING_PRICE']) == false) { - if ($pp['PURCHASING_CURRENCY'] && $currency != $pp['PURCHASING_CURRENCY']) { + $catalogProduct = CCatalogProduct::GetByID($product['PRODUCT_ID']); + + if (is_null($catalogProduct['PURCHASING_PRICE']) === false) { + if ($catalogProduct['PURCHASING_CURRENCY'] && $currency != $catalogProduct['PURCHASING_CURRENCY']) { $purchasePrice = CCurrencyRates::ConvertCurrency( - (double) $pp['PURCHASING_PRICE'], - $pp['PURCHASING_CURRENCY'], + (double) $catalogProduct['PURCHASING_PRICE'], + $catalogProduct['PURCHASING_CURRENCY'], $currency ); } else { - $purchasePrice = $pp['PURCHASING_PRICE']; + $purchasePrice = $catalogProduct['PURCHASING_PRICE']; } $item['purchasePrice'] = $purchasePrice; @@ -253,7 +255,7 @@ class RetailCrmOrder $order['items'][] = $item; - if ($send && $dimensionsSetting == 'Y') { + if ($send && $dimensionsSetting === 'Y') { $dimensions = RCrmActions::unserializeArrayRecursive($product['DIMENSIONS']); if ($dimensions !== false) { @@ -265,7 +267,7 @@ class RetailCrmOrder } } - if ($send && $dimensionsSetting == 'Y') { + if ($send && $dimensionsSetting === 'Y') { $order['width'] = $width; $order['height'] = $height; $order['length'] = $length; @@ -275,12 +277,12 @@ class RetailCrmOrder $integrationPayment = RetailcrmConfigProvider::getIntegrationPaymentTypes(); //payments $payments = []; - + foreach ($arOrder['PAYMENTS'] as $payment) { if (!empty($payment['PAY_SYSTEM_ID']) && isset($arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']])) { - $pm = array( + $pm = [ 'type' => $arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']] - ); + ]; if (!empty($payment['ID'])) { $pm['externalId'] = RCrmActions::generatePaymentExternalId($payment['ID']); @@ -290,10 +292,11 @@ class RetailCrmOrder $pm['paidAt'] = new \DateTime($payment['DATE_PAID']); } - if (!empty($arParams['optionsPayment'][$payment['PAID']])) { - if (array_search($arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']], $integrationPayment) === false) { - $pm['status'] = $arParams['optionsPayment'][$payment['PAID']]; - } + if ( + !empty($arParams['optionsPayment'][$payment['PAID']]) + && !in_array($arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']], $integrationPayment) + ) { + $pm['status'] = $arParams['optionsPayment'][$payment['PAID']]; } if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { @@ -339,10 +342,8 @@ class RetailCrmOrder Logger::getInstance()->write($order, 'orderSend'); - if ($send) { - if (!RCrmActions::apiMethod($api, $methodApi, __METHOD__, $order, $site)) { - return false; - } + if ($send && !RCrmActions::apiMethod($api, $methodApi, __METHOD__, $order, $site)) { + return false; } return $order; @@ -397,7 +398,6 @@ class RetailCrmOrder return false; } - $optionsSitesList = RetailcrmConfigProvider::getSitesList(); $optionsOrderTypes = RetailcrmConfigProvider::getOrderTypes(); $optionsDelivTypes = RetailcrmConfigProvider::getDeliveryTypes(); $optionsPayTypes = RetailcrmConfigProvider::getPaymentTypes(); @@ -408,9 +408,9 @@ class RetailCrmOrder $optionsContragentType = RetailcrmConfigProvider::getContragentTypes(); $optionsCustomFields = RetailcrmConfigProvider::getCustomFields(); - $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); + $api = new ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); - $arParams = array( + $arParams = [ 'optionsOrderTypes' => $optionsOrderTypes, 'optionsDelivTypes' => $optionsDelivTypes, 'optionsPayTypes' => $optionsPayTypes, @@ -419,27 +419,26 @@ class RetailCrmOrder 'optionsOrderProps' => $optionsOrderProps, 'optionsLegalDetails' => $optionsLegalDetails, 'optionsContragentType' => $optionsContragentType, - 'optionsSitesList' => $optionsSitesList, + 'optionsSitesList' => RetailcrmConfigProvider::getSitesList(), 'optionsCustomFields' => $optionsCustomFields, - ); + ]; - $recOrders = array(); + $recOrders = []; foreach ($orderIds as $orderId) { - $site = null; - $orderObj = Order::load($orderId); + $bitrixOrder = Order::load($orderId); - if (!$orderObj) { + if (!$bitrixOrder) { continue; } $arCustomer = []; $arCustomerCorporate = []; - $order = self::orderObjToArr($orderObj); + $order = self::orderObjToArr($bitrixOrder); $user = UserTable::getById($order['USER_ID'])->fetch(); - $site = RetailCrmOrder::getSite($order['LID'], $optionsSitesList); + $site = self::getCrmShopCodeByLid($order['LID'], $arParams['optionsSitesList']); - if (true === $site) { + if (null === $site && count($arParams['optionsSitesList']) > 0) { continue; } @@ -473,7 +472,7 @@ class RetailCrmOrder } if (count($ordersPack) > 0) { - if (false === RetailCrmOrder::uploadCustomersList($resCustomers, $api, $optionsSitesList)) { + if (false === RetailCrmOrder::uploadCustomersList($resCustomers, $api, $arParams['optionsSitesList'])) { return false; } @@ -494,7 +493,7 @@ class RetailCrmOrder } } - if (false === RetailCrmOrder::uploadOrdersList($ordersPack, $api, $optionsSitesList)) { + if (false === RetailCrmOrder::uploadOrdersList($ordersPack, $api, $arParams['optionsSitesList'])) { return false; } @@ -651,9 +650,9 @@ class RetailCrmOrder * * @return array|false */ - public static function uploadCustomersList($resCustomers, $api, $optionsSitesList) + public static function uploadCustomersList(array $resCustomers, ApiClient $api, array $optionsSitesList) { - return RetailCrmOrder::uploadItems( + return self::uploadItems( $resCustomers, 'customersUpload', 'uploadedCustomers', @@ -669,9 +668,9 @@ class RetailCrmOrder * * @return array|false */ - public static function uploadOrdersList($resOrders, $api, $optionsSitesList) + public static function uploadOrdersList(array $resOrders, ApiClient $api, array $optionsSitesList) { - return RetailCrmOrder::uploadItems( + return self::uploadItems( $resOrders, 'ordersUpload', 'uploadedOrders', @@ -681,42 +680,39 @@ class RetailCrmOrder } /** - * @param string $key + * @param string $orderLid * @param array $optionsSitesList * - * @return false|mixed|null + * @return string|null */ - public static function getSite(string $key, array $optionsSitesList) + public static function getCrmShopCodeByLid(string $orderLid, array $optionsSitesList): ?string { - if ($optionsSitesList) { - if (array_key_exists($key, $optionsSitesList) && $optionsSitesList[$key] != null) { - return $optionsSitesList[$key]; - } else { - return false; - } - } - - return null; + return $optionsSitesList[$orderLid] ?? null; } /** - * @param array $pack - * @param string $method - * @param string $keyResponse + * @param array $pack + * @param string $method + * @param string $keyResponse * @param RetailCrm\ApiClient $api - * @param array $optionsSitesList + * @param array $optionsSitesList * * @return array|false */ - public static function uploadItems(array $pack, string $method, string $keyResponse, ApiClient $api, array $optionsSitesList) - { + public static function uploadItems( + array $pack, + string $method, + string $keyResponse, + ApiClient $api, + array $optionsSitesList + ) { $uploaded = []; $sizePack = 50; foreach ($pack as $key => $itemLoad) { - $site = RetailCrmOrder::getSite($key, $optionsSitesList); - - if (true === $site) { + $site = self::getCrmShopCodeByLid($key, $optionsSitesList); + + if (null === $site && count($optionsSitesList) > 0) { continue; } @@ -738,10 +734,8 @@ class RetailCrmOrder return false; } - if ($response instanceof ApiResponse) { - if ($response->offsetExists($keyResponse)) { - $uploaded = array_merge($uploaded, $response[$keyResponse]); - } + if (($response instanceof ApiResponse) && $response->offsetExists($keyResponse)) { + $uploaded = array_merge($uploaded, $response[$keyResponse]); } } } @@ -758,9 +752,8 @@ class RetailCrmOrder */ public static function isOrderCorporate($order): bool { - return (is_array($order) || $order instanceof ArrayAccess) - && isset($order['customer']) - && isset($order['customer']['type']) + return isset($order['customer'], $order['customer']['type']) + && (is_array($order) || $order instanceof ArrayAccess) && $order['customer']['type'] === 'customer_corporate'; } diff --git a/intaro.retailcrm/install/index.php b/intaro.retailcrm/install/index.php index 960cab1b..2d90474a 100644 --- a/intaro.retailcrm/install/index.php +++ b/intaro.retailcrm/install/index.php @@ -219,7 +219,7 @@ class intaro_retailcrm extends CModule } if ($step == 11) { - $arResult['arSites'] = RCrmActions::SitesList(); + $arResult['arSites'] = RCrmActions::getSitesList(); if (count($arResult['arSites']) < 2) { $step = 2; } @@ -329,7 +329,7 @@ class intaro_retailcrm extends CModule return; } - $arResult['arSites'] = RCrmActions::SitesList(); + $arResult['arSites'] = RCrmActions::getSitesList(); if (count($arResult['arSites']) > 1) { @@ -374,7 +374,8 @@ class intaro_retailcrm extends CModule return; } - $ping = self::ping($api_host, $api_key); + $ping = $this->ping($api_host, $api_key); + if (isset($ping['sitesList'])) { $arResult['sitesList'] = $ping['sitesList']; } elseif (isset($ping['errCode'])) { @@ -482,7 +483,7 @@ class intaro_retailcrm extends CModule $this->RETAIL_CRM_API = new ApiClient($api_host, $api_key); //bitrix orderTypesList - $arResult['arSites'] = RCrmActions::SitesList(); + $arResult['arSites'] = RCrmActions::getSitesList(); $arResult['bitrixOrderTypesList'] = RCrmActions::OrderTypesList($arResult['arSites']); $orderTypesArr = array(); @@ -658,7 +659,7 @@ class intaro_retailcrm extends CModule } //bitrix orderTypesList - $orderTypesList = RCrmActions::OrderTypesList(RCrmActions::SitesList()); + $orderTypesList = RCrmActions::OrderTypesList(RCrmActions::getSitesList()); $orderTypesArr = array(); foreach ($orderTypesList as $orderType) { diff --git a/intaro.retailcrm/install/step2.php b/intaro.retailcrm/install/step2.php index abb23c7a..05331780 100644 --- a/intaro.retailcrm/install/step2.php +++ b/intaro.retailcrm/install/step2.php @@ -1,4 +1,9 @@ 'eshop-individual', - 2 => 'eshop-legal' - ); + 2 => 'eshop-legal', + ]; } -if(isset($arResult['DELIVERY_TYPES'])){ +if (isset($arResult['DELIVERY_TYPES'])) { $defaultDelivTypes = $arResult['DELIVERY_TYPES']; -} -else{ - $defaultDelivTypes = array ( +} else { + $defaultDelivTypes = [ 1 => 'courier', - 2 => 'self-delivery' - ); + 2 => 'self-delivery', + ]; } -if(isset($arResult['PAYMENT_TYPES'])){ +if (isset($arResult['PAYMENT_TYPES'])) { $defaultPayTypes = $arResult['PAYMENT_TYPES']; -} -else{ - $defaultPayTypes = array ( +} else { + $defaultPayTypes = [ 1 => 'cash', 4 => 'e-money', 5 => 'bank-card', - 9 => 'bank-transfer' - ); + 9 => 'bank-transfer', + ]; } -if(isset($arResult['PAYMENT_STATUSES'])){ +if (isset($arResult['PAYMENT_STATUSES'])) { $defaultPayStatuses = $arResult['PAYMENT_STATUSES']; -} -else{ - $defaultPayStatuses = array ( +} else { + $defaultPayStatuses = [ 'N' => 'new', 'P' => 'prepayed', 'F' => 'complete', - ); + ]; } -if(isset($arResult['PAYMENT'])){ +if (isset($arResult['PAYMENT'])) { $defaultPayment = $arResult['PAYMENT']; -} -else{ - $defaultPayment = array( +} else { + $defaultPayment = [ 'Y' => 'paid', - 'N' => 'not-paid' - ); + 'N' => 'not-paid', + ]; } - ?>