From 367680804609473220396538bb1c758ae28ca911 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: Thu, 8 Jul 2021 16:29:34 +0300 Subject: [PATCH] Corp uploading fix (#210) --- .../classes/general/ApiClient_v5.php | 187 ++++++------ .../classes/general/RCrmActions.php | 18 +- .../classes/general/events/RetailCrmEvent.php | 8 + .../general/order/RetailCrmOrder_v5.php | 275 +++++++++++------- .../general/user/RetailCrmCorporateClient.php | 105 +++++-- .../classes/general/user/RetailCrmUser.php | 132 ++++----- 6 files changed, 414 insertions(+), 311 deletions(-) diff --git a/intaro.retailcrm/classes/general/ApiClient_v5.php b/intaro.retailcrm/classes/general/ApiClient_v5.php index 9d113c39..3dcf4e61 100644 --- a/intaro.retailcrm/classes/general/ApiClient_v5.php +++ b/intaro.retailcrm/classes/general/ApiClient_v5.php @@ -11,6 +11,7 @@ namespace RetailCrm; +use InvalidArgumentException; use RetailCrm\Http\Client; use RetailCrm\Response\ApiResponse; @@ -131,7 +132,7 @@ class ApiClient $statuses = array("free", "busy", "dinner", "break"); if (empty($status) || !in_array($status, $statuses)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `status` must be not empty & must be equal one of these values: free|busy|dinner|break' ); } @@ -209,7 +210,7 @@ class ApiClient public function customersCorporateCreate(array $customer, $site = null) { if (! count($customer)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customer` must contains a data' ); } @@ -235,7 +236,7 @@ class ApiClient public function customersCorporateFixExternalIds(array $ids) { if (! count($ids)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); } @@ -262,7 +263,7 @@ class ApiClient public function customersCorporateUpload(array $customers, $site = null) { if (! count($customers)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customers` must contains array of the customers' ); } @@ -391,7 +392,7 @@ class ApiClient public function customersCorporateContactsCreate($id, array $contact = [], $by = 'externalId', $site = null) { if (! count($contact)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `contact` must contains a data' ); } @@ -528,7 +529,7 @@ class ApiClient public function customersCorporateNotesCreate($note, $site = null) { if (empty($note['customer']['id']) && empty($note['customer']['externalId'])) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Customer identifier must be set' ); } @@ -554,7 +555,7 @@ class ApiClient public function customersCorporateNotesDelete($id) { if (empty($id)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Note id must be set' ); } @@ -662,7 +663,7 @@ class ApiClient || (isset($addressFiltered['text']) && empty($addressFiltered['text'])) ) ) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `address` must contain address text or all other address field' ); } @@ -777,36 +778,46 @@ class ApiClient /** * Edit a corporate customer * - * @param array $customerCorporate corporate customer data - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException + * @param array $params corporate customer data + * @param string $by (default: 'externalId') + * @param null $site (default: null) * * @return \RetailCrm\Response\ApiResponse */ - public function customersCorporateEdit(array $customerCorporate, $by = 'externalId', $site = null) - { - if (!count($customerCorporate)) { - throw new \InvalidArgumentException( + public function customersCorporateEdit( + array $params, + $by = 'externalId', + $site = null + ): ApiResponse { + if (!count($params)) { + throw new InvalidArgumentException( 'Parameter `customerCorporate` must contains a data' ); } + + if (!isset($params['urlId'])) { + throw new InvalidArgumentException( + 'urlId should be in $params' + ); + } + + $urlId = $params['urlId']; + + unset($params['urlId']); $this->checkIdParameter($by); - if (!array_key_exists($by, $customerCorporate)) { - throw new \InvalidArgumentException( + + if (!array_key_exists($by, $params)) { + throw new InvalidArgumentException( sprintf('Corporate customer array must contain the "%s" parameter.', $by) ); } /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( - sprintf('/customers-corporate/%s/edit', $customerCorporate[$by]), + sprintf('/customers-corporate/%s/edit', $urlId), Client::METHOD_POST, $this->fillSite( $site, - ['customerCorporate' => json_encode($customerCorporate), 'by' => $by] + ['customerCorporate' => json_encode($params), 'by' => $by] ) ); } @@ -826,7 +837,7 @@ class ApiClient public function ordersCreate(array $order, $site = null) { if (!count($order)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `order` must contains a data' ); } @@ -852,7 +863,7 @@ class ApiClient public function ordersFixExternalIds(array $ids) { if (! count($ids)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); } @@ -910,7 +921,7 @@ class ApiClient public function ordersUpload(array $orders, $site = null) { if (!count($orders)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `orders` must contains array of the orders' ); } @@ -962,7 +973,7 @@ class ApiClient public function ordersEdit(array $order, $by = 'externalId', $site = null) { if (!count($order)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `order` must contains a data' ); } @@ -970,7 +981,7 @@ class ApiClient $this->checkIdParameter($by); if (!array_key_exists($by, $order)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( sprintf('Order array must contain the "%s" parameter.', $by) ); } @@ -1063,7 +1074,7 @@ class ApiClient public function customersCreate(array $customer, $site = null) { if (! count($customer)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customer` must contains a data' ); } @@ -1089,7 +1100,7 @@ class ApiClient public function customersFixExternalIds(array $ids) { if (! count($ids)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); } @@ -1116,7 +1127,7 @@ class ApiClient public function customersUpload(array $customers, $site = null) { if (! count($customers)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customers` must contains array of the customers' ); } @@ -1168,7 +1179,7 @@ class ApiClient public function customersEdit(array $customer, $by = 'externalId', $site = null) { if (!count($customer)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customer` must contains a data' ); } @@ -1176,7 +1187,7 @@ class ApiClient $this->checkIdParameter($by); if (!array_key_exists($by, $customer)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( sprintf('Customer array must contain the "%s" parameter.', $by) ); } @@ -1234,13 +1245,13 @@ class ApiClient $techniques = array('ours', 'summ', 'theirs'); if (!count($order) || !count($resultOrder)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameters `order` & `resultOrder` must contains a data' ); } if (!in_array($technique, $techniques)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `technique` must be on of ours|summ|theirs' ); } @@ -1270,7 +1281,7 @@ class ApiClient public function ordersPaymentCreate(array $payment, $site = null) { if (!count($payment)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `payment` must contains a data' ); } @@ -1297,7 +1308,7 @@ class ApiClient public function ordersPaymentEdit(array $payment, $by = 'id', $site = null) { if (!count($payment)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `payment` must contains a data' ); } @@ -1305,7 +1316,7 @@ class ApiClient $this->checkIdParameter($by); if (!array_key_exists($by, $payment)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( sprintf('Order array must contain the "%s" parameter.', $by) ); } @@ -1330,7 +1341,7 @@ class ApiClient public function ordersPaymentDelete($id) { if (empty($id)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Note id must be set' ); } @@ -1353,7 +1364,7 @@ class ApiClient { if (!count($customers) || !count($resultCustomer)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameters `customers` & `resultCustomer` must contains a data' ); } @@ -1417,7 +1428,7 @@ class ApiClient public function customersNotesCreate($note, $site = null) { if (empty($note['customer']['id']) && empty($note['customer']['externalId'])) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Customer identifier must be set' ); } @@ -1443,7 +1454,7 @@ class ApiClient public function customersNotesDelete($id) { if (empty($id)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Note id must be set' ); } @@ -1499,13 +1510,13 @@ class ApiClient empty($customField['name']) || empty($customField['type']) ) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customField` must contain a data & fields `code`, `name` & `type` must be set' ); } if (empty($entity) || !in_array($entity, array('customer', 'order'))) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `entity` must contain a data & value must be `order` or `customer`' ); } @@ -1528,13 +1539,13 @@ class ApiClient public function customFieldsEdit($entity, $customField) { if (!count($customField) || empty($customField['code'])) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `customField` must contain a data & fields `code` must be set' ); } if (empty($entity) || !in_array($entity, array('customer', 'order'))) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `entity` must contain a data & value must be `order` or `customer`' ); } @@ -1557,13 +1568,13 @@ class ApiClient public function customFieldsGet($entity, $code) { if (empty($code)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `code` must be not empty' ); } if (empty($entity) || !in_array($entity, array('customer', 'order'))) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `entity` must contain a data & value must be `order` or `customer`' ); } @@ -1617,7 +1628,7 @@ class ApiClient empty($customDictionary['code']) || empty($customDictionary['elements']) ) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' ); } @@ -1642,7 +1653,7 @@ class ApiClient empty($customDictionary['code']) || empty($customDictionary['elements']) ) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' ); } @@ -1664,7 +1675,7 @@ class ApiClient public function customDictionariesGet($code) { if (empty($code)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `code` must be not empty' ); } @@ -1717,7 +1728,7 @@ class ApiClient public function tasksCreate($task, $site = null) { if (!count($task)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `task` must contain a data' ); } @@ -1744,7 +1755,7 @@ class ApiClient public function tasksEdit($task, $site = null) { if (!count($task)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `task` must contain a data' ); } @@ -1769,7 +1780,7 @@ class ApiClient public function tasksGet($id) { if (empty($id)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `id` must be not empty' ); } @@ -1829,7 +1840,7 @@ class ApiClient public function ordersPacksCreate(array $pack, $site = null) { if (!count($pack)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `pack` must contains a data' ); } @@ -1889,7 +1900,7 @@ class ApiClient public function ordersPacksGet($id) { if (empty($id)) { - throw new \InvalidArgumentException('Parameter `id` must be set'); + throw new InvalidArgumentException('Parameter `id` must be set'); } return $this->client->makeRequest( @@ -1912,7 +1923,7 @@ class ApiClient public function ordersPacksDelete($id) { if (empty($id)) { - throw new \InvalidArgumentException('Parameter `id` must be set'); + throw new InvalidArgumentException('Parameter `id` must be set'); } return $this->client->makeRequest( @@ -1936,7 +1947,7 @@ class ApiClient public function ordersPacksEdit(array $pack, $site = null) { if (!count($pack) || empty($pack['id'])) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `pack` must contains a data & pack `id` must be set' ); } @@ -1997,7 +2008,7 @@ class ApiClient public function storeInventoriesUpload(array $offers, $site = null) { if (!count($offers)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `offers` must contains array of the offers' ); } @@ -2024,7 +2035,7 @@ class ApiClient public function storePricesUpload(array $prices, $site = null) { if (!count($prices)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `prices` must contains array of the prices' ); } @@ -2084,7 +2095,7 @@ class ApiClient public function integrationModulesGet($code) { if (empty($code)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `code` must be set' ); } @@ -2109,7 +2120,7 @@ class ApiClient public function integrationModulesEdit(array $configuration) { if (!count($configuration) || empty($configuration['code'])) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `configuration` must contains a data & configuration `code` must be set' ); } @@ -2136,11 +2147,11 @@ class ApiClient public function deliveryTracking($code, array $statusUpdate) { if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); + throw new InvalidArgumentException('Parameter `code` must be set'); } if (!count($statusUpdate)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `statusUpdate` must contains a data' ); } @@ -2200,7 +2211,7 @@ class ApiClient public function deliveryServicesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2243,7 +2254,7 @@ class ApiClient public function deliveryTypesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2286,7 +2297,7 @@ class ApiClient public function orderMethodsEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2329,7 +2340,7 @@ class ApiClient public function orderTypesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2372,7 +2383,7 @@ class ApiClient public function paymentStatusesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2415,7 +2426,7 @@ class ApiClient public function paymentTypesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2458,7 +2469,7 @@ class ApiClient public function productStatusesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2535,7 +2546,7 @@ class ApiClient public function sitesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2595,7 +2606,7 @@ class ApiClient public function statusesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } @@ -2638,13 +2649,13 @@ class ApiClient public function storesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } if (!array_key_exists('name', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "name" parameter.' ); } @@ -2686,13 +2697,13 @@ class ApiClient public function pricesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "code" parameter.' ); } if (!array_key_exists('name', $data)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Data must contain "name" parameter.' ); } @@ -2729,15 +2740,15 @@ class ApiClient ) { if (!isset($phone)) { - throw new \InvalidArgumentException('Phone number must be set'); + throw new InvalidArgumentException('Phone number must be set'); } if (!isset($type)) { - throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); + throw new InvalidArgumentException('Type must be set (in|out|hangup)'); } if (empty($codes)) { - throw new \InvalidArgumentException('Codes array must be set'); + throw new InvalidArgumentException('Codes array must be set'); } $parameters['phone'] = $phone; @@ -2769,7 +2780,7 @@ class ApiClient public function telephonyCallsUpload(array $calls) { if (!count($calls)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( 'Parameter `calls` must contains array of the calls' ); } @@ -2796,7 +2807,7 @@ class ApiClient public function telephonyCallManager($phone, $details) { if (!isset($phone)) { - throw new \InvalidArgumentException('Phone number must be set'); + throw new InvalidArgumentException('Phone number must be set'); } $parameters['phone'] = $phone; @@ -2883,19 +2894,19 @@ class ApiClient * * @param string $by identify by * + * @return bool * @throws \InvalidArgumentException * - * @return bool */ - protected function checkIdParameter($by) + protected function checkIdParameter(string $by): bool { - $allowedForBy = array( + $allowedForBy = [ 'externalId', - 'id' - ); + 'id', + ]; if (!in_array($by, $allowedForBy, false)) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( sprintf( 'Value "%s" for "by" param is not valid. Allowed values are %s.', $by, diff --git a/intaro.retailcrm/classes/general/RCrmActions.php b/intaro.retailcrm/classes/general/RCrmActions.php index 586bb64d..932130fe 100644 --- a/intaro.retailcrm/classes/general/RCrmActions.php +++ b/intaro.retailcrm/classes/general/RCrmActions.php @@ -444,28 +444,30 @@ class RCrmActions case 'customersCorporateContacts': case 'customersList': case 'customersCorporateList': - return self::proxy($api, $methodApi, $method, array($params)); + return self::proxy($api, $methodApi, $method, [$params]); case 'orderGet': - return self::proxy($api, 'ordersGet', $method, array($params, 'id', $site)); + return self::proxy($api, 'ordersGet', $method, [$params, 'id', $site]); case 'ordersGet': case 'ordersEdit': case 'customersGet': case 'customersEdit': case 'customersCorporateGet': - return self::proxy($api, $methodApi, $method, array($params, 'externalId', $site)); + return self::proxy($api, $methodApi, $method, [$params, 'externalId', $site]); case 'customersCorporateGetById': - return self::proxy($api, 'customersCorporateGet', $method, array($params, 'id', $site)); + return self::proxy($api, 'customersCorporateGet', $method, [$params, 'id', $site]); case 'customersGetById': - return self::proxy($api, 'customersGet', $method, array($params, 'id', $site)); + return self::proxy($api, 'customersGet', $method, [$params, 'id', $site]); case 'paymentEditById': - return self::proxy($api, 'ordersPaymentEdit', $method, array($params, 'id', $site)); + return self::proxy($api, 'ordersPaymentEdit', $method, [$params, 'id', $site]); case 'paymentEditByExternalId': - return self::proxy($api, 'ordersPaymentEdit', $method, array($params, 'externalId', $site)); + return self::proxy($api, 'ordersPaymentEdit', $method, [$params, 'externalId', $site]); + case 'customersCorporateEdit': + return self::proxy($api, 'customersCorporateEdit', $method, [$params, 'externalId', $site]); default: - return self::proxy($api, $methodApi, $method, array($params, $site)); + return self::proxy($api, $methodApi, $method, array($params, $site)); } } diff --git a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php index e1d7db8d..8d0c0729 100644 --- a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php +++ b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php @@ -195,6 +195,14 @@ class RetailCrmEvent $orderCompany = null; + if ('Y' === $optionCorpClient) { + if (true === RetailCrmCorporateClient::isCorpTookExternalId((string) $arOrder['USER_ID'], $api)) { + RetailCrmCorporateClient::setPrefixForExternalId((string) $arOrder['USER_ID'], $api); + } + } + + //TODO эта управляющая конструкция по функционалу дублирует RetailCrmOrder::createCustomerForOrder. + // Необходимо устранить дублирование, вынеся логику в обособленный класс-сервис if ("Y" === $optionCorpClient && $optionsContragentType[$arOrder['PERSON_TYPE_ID']] == 'legal-entity') { //corparate cliente $nickName = ''; diff --git a/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php b/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php index b2d12387..6eeb73c1 100644 --- a/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php +++ b/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php @@ -1,7 +1,9 @@ fetch(); $site = RetailCrmOrder::getSite($order['LID'], $optionsSitesList); if (true === $site) { continue; } - if ("Y" == RetailcrmConfigProvider::getCorporateClientStatus() - && $optionsContragentType[$order['PERSON_TYPE_ID']] == 'legal-entity' - ) { - // TODO check if order is corporate, and if it IS - make corporate order - $arCustomer = RetailCrmUser::customerSend( - $user, - $api, - 'individual', - false, - $site - ); - - $arCustomerCorporate = RetailCrmCorporateClient::clientSend( - $order, - $api, - 'legal-entity', - false, - true, - $site - ); - - $arParams['orderCompany'] = isset($arCustomerCorporate['companies']) - ? reset($arCustomerCorporate['companies']) : null; - - $arParams['contactExId'] = $user['ID']; - } else { - $arCustomer = RetailCrmUser::customerSend( - $user, - $api, - $optionsContragentType[$order['PERSON_TYPE_ID']], - false, - $site - ); - - if (isset($arParams['contactExId'])) { - unset($arParams['contactExId']); - } - } + self::createCustomerForOrder($api, $arCustomer, $arCustomerCorporate,$arParams, $order, $site); $arOrders = self::orderSend($order, $api, $arParams, false, $site,'ordersCreate'); @@ -475,7 +439,7 @@ class RetailCrmOrder $resCustomersCorporate[$arCustomerCorporate['nickName']] = $arCustomerCorporate; } - $email = isset($arCustomer['email']) ? $arCustomer['email'] : ''; + $email = $arCustomer['email'] ?? ''; if (!in_array($email, $resCustomersAdded)) { $resCustomersAdded[] = $email; @@ -483,79 +447,33 @@ class RetailCrmOrder } $resCustomers[$order['LID']][] = $arCustomer; - $resOrders[$order['LID']][] = $arOrders; + $ordersPack[$order['LID']][] = $arOrders; $recOrders[] = $orderId; } - if (count($resOrders) > 0) { + if (count($ordersPack) > 0) { if (false === RetailCrmOrder::uploadCustomersList($resCustomers, $api, $optionsSitesList)) { return false; } - if ("Y" == RetailcrmConfigProvider::getCorporateClientStatus()) { - $cachedCorporateIds = array(); + if ('Y' == RetailcrmConfigProvider::getCorporateClientStatus()) { + $cachedCorporateIds = []; - foreach ($resOrders as $packKey => $pack) { - foreach ($pack as $key => $orderData) { - if (isset($orderData['contragent']['contragentType']) - && $orderData['contragent']['contragentType'] == 'legal-entity' - && !empty($orderData['contragent']['legalName']) - ) { - if (isset($cachedCorporateIds[$orderData['contragent']['legalName']])) { - $orderData['customer'] = array( - 'id' => $cachedCorporateIds[$orderData['contragent']['legalName']] - ); - } else { - $corpData = $api->customersCorporateList(array( - 'nickName' => array($orderData['contragent']['legalName']) - )); - - if ($corpData - && $corpData->isSuccessful() - && $corpData->offsetExists('customersCorporate') - && !empty($corpData['customersCorporate']) - ) { - $corpData = $corpData['customersCorporate']; - $corpData = reset($corpData); - - $orderData['customer'] = array('id' => $corpData['id']); - $cachedCorporateIds[$orderData['contragent']['legalName']] = $corpData['id']; - - RetailCrmCorporateClient::addCustomersCorporateAddresses( - $orderData['customer']['id'], - $orderData['contragent']['legalName'], - $orderData['delivery']['address']['text'], - $api, - $site = null - ); - } elseif (array_key_exists( - $orderData['contragent']['legalName'], - $resCustomersCorporate - )) { - $createResponse = $api - ->customersCorporateCreate( - $resCustomersCorporate[$orderData['contragent']['legalName']] - ); - - if ($createResponse && $createResponse->isSuccessful()) { - $orderData['customer'] = array('id' => $createResponse['id']); - $cachedCorporateIds[$orderData['contragent']['legalName']] - = $createResponse['id']; - } - } - - time_nanosleep(0, 250000000); - } - - $pack[$key] = $orderData; - } + foreach ($ordersPack as $lid => $lidOrdersList) { + foreach ($lidOrdersList as $key => $orderData) { + $lidOrdersList[$key] = self::addCorporateCustomerToOrder( + $orderData, + $api, + $resCustomersCorporate, + $cachedCorporateIds + ); } - $resOrders[$packKey] = $pack; + $ordersPack[$lid] = $lidOrdersList; } } - if (false === RetailCrmOrder::uploadOrdersList($resOrders, $api, $optionsSitesList)) { + if (false === RetailCrmOrder::uploadOrdersList($ordersPack, $api, $optionsSitesList)) { return false; } @@ -569,6 +487,141 @@ class RetailCrmOrder return true; } + /** + * @param \RetailCrm\ApiClient $api + * @param array $arCustomer + * @param array $arCustomerCorporate + * @param array $arParams + * @param array $order + * @param $site + * + * @throws \Bitrix\Main\ArgumentException + * @throws \Bitrix\Main\ObjectPropertyException + * @throws \Bitrix\Main\SystemException + */ + public static function createCustomerForOrder( + ApiClient $api, + array &$arCustomer, + array &$arCustomerCorporate, + array &$arParams, + array $order, + $site + ): void { + $optionsContragentType = RetailcrmConfigProvider::getContragentTypes(); + $user = UserTable::getById($order['USER_ID'])->fetch(); + + if ('Y' === RetailcrmConfigProvider::getCorporateClientStatus()) { + if (true === RetailCrmCorporateClient::isCorpTookExternalId((string) $user['ID'], $api)) { + RetailCrmCorporateClient::setPrefixForExternalId((string) $user['ID'], $api); + } + } + + if ( + 'Y' === RetailcrmConfigProvider::getCorporateClientStatus() + && $optionsContragentType[$order['PERSON_TYPE_ID']] === 'legal-entity' + ) { + // TODO check if order is corporate, and if it IS - make corporate order + $arCustomer = RetailCrmUser::customerSend( + $user, + $api, + 'individual', + false, + $site + ); + + $arCustomerCorporate = RetailCrmCorporateClient::clientSend( + $order, + $api, + 'legal-entity', + false, + true, + $site + ); + + $arParams['orderCompany'] = isset($arCustomerCorporate['companies']) + ? reset($arCustomerCorporate['companies']) + : null; + $arParams['contactExId'] = $user['ID']; + + return; + } + + $arCustomer = RetailCrmUser::customerSend( + $user, + $api, + $optionsContragentType[$order['PERSON_TYPE_ID']], + false, + $site + ); + + if (isset($arParams['contactExId'])) { + unset($arParams['contactExId']); + } + } + + /** + * @param array $orderData + * @param \RetailCrm\ApiClient $api + * @param array $resCustomersCorporate + * @param array $cachedCorporateIds + * + * @return array + */ + public static function addCorporateCustomerToOrder( + array $orderData, + ApiClient $api, + array $resCustomersCorporate, + array &$cachedCorporateIds + ): array { + $customerLegalName = $orderData['contragent']['legalName']; + + if ( + isset($orderData['contragent']['contragentType']) + && $orderData['contragent']['contragentType'] === 'legal-entity' + && !empty($customerLegalName) + ) { + if (isset($cachedCorporateIds[$customerLegalName])) { + $orderData['customer'] = ['id' => $cachedCorporateIds[$customerLegalName]]; + } else { + $corpListResponse = $api->customersCorporateList(['nickName' => [$customerLegalName]]); + + if ( + $corpListResponse + && $corpListResponse->isSuccessful() + && $corpListResponse->offsetExists('customersCorporate') + && !empty($corpListResponse['customersCorporate']) + ) { + $corpListResponse = $corpListResponse['customersCorporate']; + $corpListResponse = reset($corpListResponse); + + $orderData['customer'] = ['id' => $corpListResponse['id']]; + $cachedCorporateIds[$customerLegalName] = $corpListResponse['id']; + + RetailCrmCorporateClient::addCustomersCorporateAddresses( + $orderData['customer']['id'], + $customerLegalName, + $orderData['delivery']['address']['text'], + $api, + $site = null + ); + } elseif (array_key_exists($customerLegalName, $resCustomersCorporate)) { + $createResponse = $api->customersCorporateCreate( + $resCustomersCorporate[$customerLegalName] + ); + + if ($createResponse && $createResponse->isSuccessful()) { + $orderData['customer'] = ['id' => $createResponse['id']]; + $cachedCorporateIds[$customerLegalName] = $createResponse['id']; + } + } + + time_nanosleep(0, 250000000); + } + } + + return $orderData; + } + /** * @param array $resCustomers * @param RetailCrm\ApiClient $api @@ -681,12 +734,12 @@ class RetailCrmOrder * * @return bool */ - public static function isOrderCorporate($order) + public static function isOrderCorporate($order): bool { return (is_array($order) || $order instanceof ArrayAccess) && isset($order['customer']) && isset($order['customer']['type']) - && $order['customer']['type'] == 'customer_corporate'; + && $order['customer']['type'] === 'customer_corporate'; } /** diff --git a/intaro.retailcrm/classes/general/user/RetailCrmCorporateClient.php b/intaro.retailcrm/classes/general/user/RetailCrmCorporateClient.php index 514feeef..a2d584e3 100644 --- a/intaro.retailcrm/classes/general/user/RetailCrmCorporateClient.php +++ b/intaro.retailcrm/classes/general/user/RetailCrmCorporateClient.php @@ -1,7 +1,14 @@ fetch(); + $arUser = UserTable::getById($arOrder['USER_ID'])->fetch(); if (count($shops) == 0) { RCrmActions::eventLog('RetailCrmCorporateClient::clientSend()', '$shops', 'No stores selected for download'); @@ -45,38 +52,38 @@ class RetailCrmCorporateClient } foreach ($shops as $shop) { - $customerCorporate = array( - 'createdAt' => $arOrder['DATE_INSERT'], - "nickName" => $nickName - ); + $customerCorporate = [ + 'createdAt' => $arOrder['DATE_INSERT'], + "nickName" => $nickName, + ]; if ($fillCorp) { $customerCorporate = array_merge( $customerCorporate, - array( - 'customerContacts' => array( - array( + [ + 'customerContacts' => [ + [ 'isMain' => true, - 'customer' => array( + 'customer' => [ 'externalId' => $arUser['ID'], - 'site' => $shop - ) - ) - ), - 'companies' => array( - array( + 'site' => $shop, + ], + ], + ], + 'companies' => [ + [ 'name' => $nickName, 'isMain' => true, - ) - ), - 'addresses' => array( - array( + ], + ], + 'addresses' => [ + [ 'name' => $nickName, 'isMain' => true, - 'text' => $address - ) - ) - ) + 'text' => $address, + ], + ], + ] ); } } @@ -154,4 +161,56 @@ class RetailCrmCorporateClient } } } + + /** + * Проверяет, существует ли корпоративный клиент с указанным externalId + * + * @param string $bitrixUserId + * @param \RetailCrm\ApiClient $api + * + * @return bool + */ + public static function isCorpTookExternalId(string $bitrixUserId, ApiClient $api): bool + { + $response = RCrmActions::apiMethod( + $api, + 'customersCorporateGet', + __METHOD__, + $bitrixUserId + ); + + if (false === $response) { + return false; + } + + if ($response instanceof ApiResponse && $response->offsetGet('customerCorporate')) { + return true; + } + + return false; + } + + /** + * @param string $externalId + * @param \RetailCrm\ApiClient $api + */ + public static function setPrefixForExternalId(string $externalId, ApiClient $api) + { + $response = RCrmActions::apiMethod( + $api, + 'customersCorporateEdit', + __METHOD__, + [ + 'urlId' => $externalId, + 'externalId' => self::CORP_PREFIX . $externalId + ] + ); + + if (false === $response) { + Logger::getInstance()->write( + sprintf('Не удалось добавить префикс для корпоративного клиента %s', $externalId), + 'clientCorporate' + ); + } + } } diff --git a/intaro.retailcrm/classes/general/user/RetailCrmUser.php b/intaro.retailcrm/classes/general/user/RetailCrmUser.php index 4867945a..00dee6d6 100644 --- a/intaro.retailcrm/classes/general/user/RetailCrmUser.php +++ b/intaro.retailcrm/classes/general/user/RetailCrmUser.php @@ -2,56 +2,33 @@ IncludeModuleLangFile(__FILE__); class RetailCrmUser { - public static function customerSend($arFields, $api, $contragentType, $send = false, $site = null) + + /** + * @param array $arFields + * @param $api + * @param $contragentType + * @param false $send + * @param null $site + * + * @return array|false + * @throws \Exception + */ + public static function customerSend(array $arFields, $api, $contragentType, bool $send = false, $site = null) { if (!$api || empty($contragentType)) { return false; } + if (empty($arFields)) { RCrmActions::eventLog('RetailCrmUser::customerSend', 'empty($arFields)', 'incorrect customer'); + return false; } - $customer = array( - 'externalId' => $arFields['ID'], - 'email' => $arFields['EMAIL'], - 'createdAt' => new \DateTime($arFields['DATE_REGISTER']), - 'subscribed' => false, - 'contragent' => array( - 'contragentType' => $contragentType - ) - ); - - if (!empty($arFields['NAME'])) { - $customer['firstName'] = $arFields['NAME']; - } - if (!empty($arFields['LAST_NAME'])) { - $customer['lastName'] = $arFields['LAST_NAME']; - } - if (!empty($arFields['SECOND_NAME'])) { - $customer['patronymic'] = $arFields['SECOND_NAME']; - } - - if (!empty($arFields['PERSONAL_PHONE'])) { - $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; - } - if (!empty($arFields['WORK_PHONE'])) { - $customer['phones'][]['number'] = $arFields['WORK_PHONE']; - } - - if (!empty($arFields['PERSONAL_CITY'])) { - $customer['address']['city'] = $arFields['PERSONAL_CITY']; - } - if (!empty($arFields['PERSONAL_STREET'])) { - $customer['address']['text'] = $arFields['PERSONAL_STREET']; - } - if (!empty($arFields['PERSONAL_ZIP'])) { - $customer['address']['index'] = $arFields['PERSONAL_ZIP']; - } - - if (mb_strlen($arFields['EMAIL']) > 100 ) { - unset($customer['email']); - } + $customer = self::getSimpleCustomer($arFields); + $customer['createdAt'] = new \DateTime($arFields['DATE_REGISTER']); + $customer['subscribed'] = false; + $customer['contragent'] = ['contragentType' => $contragentType]; if ($send && isset($_COOKIE['_rc']) && $_COOKIE['_rc'] != '') { $customer['browserId'] = $_COOKIE['_rc']; @@ -59,6 +36,7 @@ class RetailCrmUser if (function_exists('retailCrmBeforeCustomerSend')) { $newResCustomer = retailCrmBeforeCustomerSend($customer); + if (is_array($newResCustomer) && !empty($newResCustomer)) { $customer = $newResCustomer; } elseif ($newResCustomer === false) { @@ -73,58 +51,26 @@ class RetailCrmUser Logger::getInstance()->write($customer, 'customerSend'); - if ($send) { - if (!RCrmActions::apiMethod($api, 'customersCreate', __METHOD__, $customer, $site)) { + if ( + $send + && !RCrmActions::apiMethod($api, 'customersCreate', __METHOD__, $customer, $site) + ) { return false; - } } return $customer; } - public static function customerEdit($arFields, $api, $optionsSitesList = array()){ + public static function customerEdit($arFields, $api, $optionsSitesList = array()): bool + { if (empty($arFields)) { RCrmActions::eventLog('RetailCrmUser::customerEdit', 'empty($arFields)', 'incorrect customer'); return false; } - $customer = array( - 'externalId' => $arFields['ID'], - 'email' => $arFields['EMAIL'], - ); - - if (!empty($arFields['NAME'])) { - $customer['firstName'] = $arFields['NAME']; - } - if (!empty($arFields['LAST_NAME'])) { - $customer['lastName'] = $arFields['LAST_NAME']; - } - if (!empty($arFields['SECOND_NAME'])) { - $customer['patronymic'] = $arFields['SECOND_NAME']; - } - - if ( mb_strlen($arFields['EMAIL']) > 100) { - unset($customer['email']); - } - - if (!empty($arFields['PERSONAL_PHONE'])) { - $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE']; - } - if (!empty($arFields['WORK_PHONE'])) { - $customer['phones'][]['number'] = $arFields['WORK_PHONE']; - } - - if (!empty($arFields['PERSONAL_CITY'])) { - $customer['address']['city'] = $arFields['PERSONAL_CITY']; - } - if (!empty($arFields['PERSONAL_STREET'])) { - $customer['address']['text'] = $arFields['PERSONAL_STREET']; - } - if (!empty($arFields['PERSONAL_ZIP'])) { - $customer['address']['index'] = $arFields['PERSONAL_ZIP']; - } - + $customer = self::getSimpleCustomer($arFields); $found = false; + if (count($optionsSitesList) > 0) { foreach ($optionsSitesList as $site) { $userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arFields['ID'], $site); @@ -163,4 +109,28 @@ class RetailCrmUser return true; } + + /** + * @param array $arFields + * + * @return array + */ + private static function getSimpleCustomer(array $arFields): array + { + $customer['externalId'] = $arFields['ID']; + $customer['firstName'] = $arFields['NAME'] ?? null; + $customer['lastName'] = $arFields['LAST_NAME'] ?? null; + $customer['patronymic'] = $arFields['SECOND_NAME'] ?? null; + $customer['phones'][]['number'] = $arFields['PERSONAL_PHONE'] ?? null; + $customer['phones'][]['number'] = $arFields['WORK_PHONE'] ?? null; + $customer['address']['city'] = $arFields['PERSONAL_CITY'] ?? null; + $customer['address']['text'] = $arFields['PERSONAL_STREET'] ?? null; + $customer['address']['index'] = $arFields['PERSONAL_ZIP'] ?? null; + + if (mb_strlen($arFields['EMAIL']) < 100) { + $customer['email'] = $arFields['EMAIL']; + } + + return $customer; + } }