From ad04daa904664d28a6cda548afc9b123c3133add Mon Sep 17 00:00:00 2001 From: Kocmonavtik <61938582+Kocmonavtik@users.noreply.github.com> Date: Wed, 24 Jan 2024 15:01:13 +0300 Subject: [PATCH] =?UTF-8?q?ref=20#92904=20=D0=9F=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B0=D1=87=D0=B0=20=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=B8=D0=BD=D1=82=D0=B5=D0=B3=D1=80=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=BD=D1=8B=D1=85=20=D0=BE=D0=BF=D0=BB=D0=B0=D1=82?= =?UTF-8?q?=20(#335)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 3 + .../classes/general/events/RetailCrmEvent.php | 14 +- .../general/history/RetailCrmHistory_v5.php | 29 +++- .../general/order/RetailCrmOrder_v5.php | 30 ++--- .../general/services/RetailCrmService.php | 31 ++++- intaro.retailcrm/description.ru | 2 +- intaro.retailcrm/install/version.php | 4 +- intaro.retailcrm/lang/en/options.php | 9 ++ intaro.retailcrm/lang/ru/options.php | 9 ++ .../lib/component/configprovider.php | 20 +++ intaro.retailcrm/lib/component/constants.php | 3 + intaro.retailcrm/options.php | 121 ++++++++++++++++- .../general/events/RetailCrmEventTest.php | 126 +++++++++++++++++- .../general/order/RetailCrmOrder_v5Test.php | 33 ++++- .../general/services/RetailCrmServiceTest.php | 6 +- 15 files changed, 397 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d71f2cd1..87b60a28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2024-01-22 v.6.5.7 +- Доработана передача данных интеграционных оплат в систему + ## 2024-01-12 v.6.5.6 - Добавлена передача дополнительных свойств товаров через конфигурируемый файл diff --git a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php index 02b26652..6ddbfd2c 100644 --- a/intaro.retailcrm/classes/general/events/RetailCrmEvent.php +++ b/intaro.retailcrm/classes/general/events/RetailCrmEvent.php @@ -1,6 +1,7 @@ $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']], - ]; + $paymentToCrm = []; if (!empty($arPayment['ID'])) { $paymentToCrm['externalId'] = RCrmActions::generatePaymentExternalId($arPayment['ID']); } - $isIntegrationPayment - = RetailCrmService::isIntegrationPayment($arPayment['PAY_SYSTEM_ID'] ?? null); - - if (!empty($arPayment['DATE_PAID']) && !$isIntegrationPayment) { + if (!empty($arPayment['DATE_PAID'])) { if (is_object($arPayment['DATE_PAID'])) { $culture = new Culture(['FORMAT_DATETIME' => 'YYYY-MM-DD HH:MI:SS']); $paymentToCrm['paidAt'] = $arPayment['DATE_PAID']->toString($culture); @@ -544,7 +540,7 @@ class RetailCrmEvent } } - if (!empty($optionsPayStatuses[$arPayment['PAID']]) && !$isIntegrationPayment) { + if (!empty($optionsPayStatuses[$arPayment['PAID']])) { $paymentToCrm['status'] = $optionsPayStatuses[$arPayment['PAID']]; } @@ -555,6 +551,8 @@ class RetailCrmEvent if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { $paymentToCrm['amount'] = $arPayment['SUM']; } + + $paymentToCrm = RetailCrmService::preparePayment($paymentToCrm, $arPayment, $optionsPaymentTypes); } else { RCrmActions::eventLog('RetailCrmEvent::paymentSave', 'payments', 'OrderID = ' . $arPayment['ID'] . '. Payment not found.'); return false; diff --git a/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php b/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php index a48278c5..805d5963 100644 --- a/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php +++ b/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php @@ -52,6 +52,8 @@ class RetailCrmHistory public static $CUSTOM_FIELDS_IS_ACTIVE = 'N'; const PAGE_LIMIT = 25; + private static $optionsPayment = []; + public static function customerHistory() { if (!RetailcrmDependencyLoader::loadDependencies()) { @@ -280,6 +282,25 @@ class RetailCrmHistory $contragentTypes = array_flip(RetailcrmConfigProvider::getContragentTypes()); $shipmentDeducted = RetailcrmConfigProvider::getShipmentDeducted(); + $optionsPayment = [ + 'payTypes' => array_flip(RetailcrmConfigProvider::getPaymentTypes()), + 'paymentList' => array_flip(RetailcrmConfigProvider::getPayment()), + ]; + + if (RetailcrmConfigProvider::getSyncIntegrationPayment() === 'Y') { + $substitutedPayment = RetailcrmConfigProvider::getSubstitutionPaymentList(); + + foreach ($substitutedPayment as $origCode => $subsCode) { + if (isset($optionsPayment['payTypes'][$origCode])) { + $optionsPayment['payTypes'][$subsCode] = $optionsPayment['payTypes'][$origCode]; + } + } + } + + self::$optionsPayment = $optionsPayment; + + unset($optionsPayment); + $matchedCustomUserFields = RetailcrmConfigProvider::getMatchedUserFields() ?? []; $matchedCustomUserFields = is_array($matchedCustomUserFields) ? array_flip($matchedCustomUserFields) : []; @@ -1941,14 +1962,17 @@ class RetailCrmHistory */ public static function paymentsUpdate($order, $paymentsCrm, &$newHistoryPayments = []) { - $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))); + $optionsPayTypes = self::$optionsPayment['payTypes']; + $optionsPayment = self::$optionsPayment['paymentList']; $allPaymentSystems = RCrmActions::PaymentList(); + foreach ($allPaymentSystems as $allPaymentSystem) { $arPaySysmems[$allPaymentSystem['ID']] = $allPaymentSystem['NAME']; } + $paymentsList = []; $paymentColl = $order->getPaymentCollection(); + foreach ($paymentColl as $paymentData) { $data = $paymentData->getFields()->getValues(); $paymentsList[$data['ID']] = $paymentData; @@ -1956,6 +1980,7 @@ class RetailCrmHistory //data from crm $paySumm = 0; + foreach ($paymentsCrm['payments'] as $paymentCrm) { if (isset($paymentCrm['externalId']) && !empty($paymentCrm['externalId'])) { //find the payment diff --git a/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php b/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php index 970a2df7..9521e218 100644 --- a/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php +++ b/intaro.retailcrm/classes/general/order/RetailCrmOrder_v5.php @@ -9,6 +9,7 @@ use Bitrix\Sale\Internals\OrderTable; use Bitrix\Sale\Location\LocationTable; use Bitrix\Sale\Order; use Intaro\RetailCrm\Component\ApiClient\ClientAdapter; +use Intaro\RetailCrm\Component\Constants; use Intaro\RetailCrm\Component\Factory\ClientFactory; use Intaro\RetailCrm\Component\ServiceLocator; use Intaro\RetailCrm\Service\LoyaltyService; @@ -365,30 +366,27 @@ class RetailCrmOrder $payments = []; foreach ($arOrder['PAYMENTS'] as $payment) { - $isIntegrationPayment = RetailCrmService::isIntegrationPayment($payment['PAY_SYSTEM_ID'] ?? null); - if (!empty($payment['PAY_SYSTEM_ID']) && isset($arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']])) { - $pm = [ - 'type' => $arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']] - ]; + $crmPayment = []; + + if (!empty($payment['DATE_PAID'])) { + $crmPayment['paidAt'] = new \DateTime($payment['DATE_PAID']); + } + + if (!empty($arParams['optionsPayment'][$payment['PAID']])) { + $crmPayment['status'] = $arParams['optionsPayment'][$payment['PAID']]; + } if (!empty($payment['ID'])) { - $pm['externalId'] = RCrmActions::generatePaymentExternalId($payment['ID']); - } - - if (!empty($payment['DATE_PAID']) && !$isIntegrationPayment) { - $pm['paidAt'] = new \DateTime($payment['DATE_PAID']); - } - - if (!empty($arParams['optionsPayment'][$payment['PAID']]) && !$isIntegrationPayment) { - $pm['status'] = $arParams['optionsPayment'][$payment['PAID']]; + $crmPayment['externalId'] = RCrmActions::generatePaymentExternalId($payment['ID']); } if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { - $pm['amount'] = $payment['SUM']; + $crmPayment['amount'] = $payment['SUM']; } - $payments[] = $pm; + $crmPayment = RetailCrmService::preparePayment($crmPayment, $payment, $arParams['optionsPayTypes']); + $payments[] = $crmPayment; } else { RCrmActions::eventLog( 'RetailCrmOrder::orderSend', diff --git a/intaro.retailcrm/classes/general/services/RetailCrmService.php b/intaro.retailcrm/classes/general/services/RetailCrmService.php index 58081426..e533ce44 100644 --- a/intaro.retailcrm/classes/general/services/RetailCrmService.php +++ b/intaro.retailcrm/classes/general/services/RetailCrmService.php @@ -1,5 +1,7 @@ '6.5.6', - 'VERSION_DATE' => '2024-01-12 17:00:00' + 'VERSION' => '6.5.7', + 'VERSION_DATE' => '2024-01-22 11:00:00' ]; diff --git a/intaro.retailcrm/lang/en/options.php b/intaro.retailcrm/lang/en/options.php index 493d7880..bcf743dd 100644 --- a/intaro.retailcrm/lang/en/options.php +++ b/intaro.retailcrm/lang/en/options.php @@ -137,3 +137,12 @@ $MESS ['DELETE_MATCHED'] = 'Delete'; $MESS ['LOCATION_LABEL'] = 'Location'; $MESS ['TEXT_ADDRESS_LABEL'] = 'Address (line)'; + +$MESS ['SYNC_INTEGRATION_PAYMENT'] = 'Activate transfer of integration payment statuses'; +$MESS ['DESCRIPTION_AUTO_PAYMENT_TYPE'] = 'Automatically created payment type for integration substitution (Bitrix)'; +$MESS ['NO_INTEGRATION_PAYMENT'] = '(Non-integrated)'; +$MESS ['ERR_CHECK_JOURNAL'] = 'Error while saving. Details in the event log'; +$MESS ['ERROR_LINK_INTEGRATION_PAYMENT'] = 'Error in comparing integration payments'; +$MESS ['ERROR_UPDATE_PAYMENT_TYPES_DELIVERY'] = 'Error when updating payment methods for deliveries'; +$MESS ['INTEGRATION_PAYMENT_LABEL'] = 'When correlating CMS and CRM integration payments, a regular payment is created on the system side to which orders will be linked.'; +$MESS ['NEED_PERMISSIONS_REFERENCE_LABEL'] = 'For this option to work correctly, the api key needs access to receive and edit reference book'; diff --git a/intaro.retailcrm/lang/ru/options.php b/intaro.retailcrm/lang/ru/options.php index a0505647..818d4087 100644 --- a/intaro.retailcrm/lang/ru/options.php +++ b/intaro.retailcrm/lang/ru/options.php @@ -196,3 +196,12 @@ $MESS ['DELETE_MATCHED'] = 'Удалить'; $MESS ['LOCATION_LABEL'] = 'Местоположение (LOCATION)'; $MESS ['TEXT_ADDRESS_LABEL'] = 'Адрес (строкой)'; + +$MESS ['SYNC_INTEGRATION_PAYMENT'] = 'Активировать передачу статусов интеграционных оплат'; +$MESS ['DESCRIPTION_AUTO_PAYMENT_TYPE'] = 'Автоматически созданный тип оплаты для подмены интеграционной (Bitrix)'; +$MESS ['NO_INTEGRATION_PAYMENT'] = '(Не интеграционная)'; +$MESS ['ERR_CHECK_JOURNAL'] = 'Ошибка при сохранении. Подробности в журнале событий'; +$MESS ['ERROR_LINK_INTEGRATION_PAYMENT'] = 'Ошибка при сопоставлении интеграционных оплат'; +$MESS ['ERROR_UPDATE_PAYMENT_TYPES_DELIVERY'] = 'Ошибка при обновлении способов оплаты для доставок'; +$MESS ['INTEGRATION_PAYMENT_LABEL'] = 'При сопоставлении интеграционных оплат CRM, на стороне системы создаётся обычная оплата, к которой будут привязываться заказы.'; +$MESS ['NEED_PERMISSIONS_REFERENCE_LABEL'] = 'Для корректной работы опции апи-ключу необходимы доступы на получение и редактирование справочников'; diff --git a/intaro.retailcrm/lib/component/configprovider.php b/intaro.retailcrm/lib/component/configprovider.php index 60897498..613037ca 100644 --- a/intaro.retailcrm/lib/component/configprovider.php +++ b/intaro.retailcrm/lib/component/configprovider.php @@ -1171,6 +1171,26 @@ class ConfigProvider return static::getOption(Constants::RECEIVE_TRACK_NUMBER_DELIVERY); } + public static function getSyncIntegrationPayment() + { + return static::getOption(Constants::SYNC_INTEGRATION_PAYMENT); + } + + public static function setSyncIntegrationPayment($syncIntegrationPayment) + { + static::setOption(Constants::SYNC_INTEGRATION_PAYMENT, $syncIntegrationPayment); + } + + public static function getSubstitutionPaymentList() + { + return static::getUnserializedOption(Constants::CRM_SUBSTITUTION_PAYMENT_LIST); + } + + public static function setSubstitutionPaymentList($paymentList) + { + static::setOption(Constants::CRM_SUBSTITUTION_PAYMENT_LIST, serialize($paymentList)); + } + /** * @return string */ diff --git a/intaro.retailcrm/lib/component/constants.php b/intaro.retailcrm/lib/component/constants.php index 7f3eac83..58898a9e 100644 --- a/intaro.retailcrm/lib/component/constants.php +++ b/intaro.retailcrm/lib/component/constants.php @@ -108,4 +108,7 @@ class Constants public const MATCHED_CUSTOM_USER_FIELDS = 'matched_custom_field'; public const USE_CRM_ORDER_METHODS = 'use_crm_order_methods'; public const CRM_ORDER_METHODS = 'crm_order_methods'; + public const SYNC_INTEGRATION_PAYMENT = 'sync_integration_payment'; + public const CRM_PART_SUBSTITUTED_PAYMENT_CODE = '-not-integration'; + public const CRM_SUBSTITUTION_PAYMENT_LIST = 'substitution_payment'; } diff --git a/intaro.retailcrm/options.php b/intaro.retailcrm/options.php index 7edbd098..b7511160 100644 --- a/intaro.retailcrm/options.php +++ b/intaro.retailcrm/options.php @@ -244,6 +244,7 @@ if (!empty($availableSites)) { //update connection settings if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { + $error = null; $api_host = htmlspecialchars(trim($_POST['api_host'])); $api_key = htmlspecialchars(trim($_POST['api_key'])); @@ -835,6 +836,73 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { ConfigProvider::setTrackNumberStatus(htmlspecialchars(trim($_POST['track-number'])) ?: 'N'); + $syncIntegrationPayment = htmlspecialchars(trim($_POST['sync-integration-payment'])) ?: 'N'; + + if ($syncIntegrationPayment === 'Y') { + $substitutionPaymentList = []; + + foreach (RetailcrmConfigProvider::getIntegrationPaymentTypes() as $integrationPayment) { + if (in_array($integrationPayment, $paymentTypesArr)) { + $originalPayment = $arResult['paymentTypesList'][$integrationPayment]; + $codePayment = $integrationPayment . Constants::CRM_PART_SUBSTITUTED_PAYMENT_CODE; + + $response = $api->paymentTypesEdit([ + 'name' => $originalPayment['name'] . ' ' . GetMessage('NO_INTEGRATION_PAYMENT'), + 'code' => $codePayment, + 'active' => true, + 'description' => GetMessage('DESCRIPTION_AUTO_PAYMENT_TYPE'), + 'sites' => $originalPayment['sites'], + 'paymentStatuses' => $originalPayment['paymentStatuses'] + ]); + + $statusCode = $response->getStatusCode(); + + if ($response->isSuccessful()) { + $substitutionPaymentList[$integrationPayment] = $codePayment; + + foreach ($originalPayment['deliveryTypes'] as $codeDelivery) { + if (!isset($arResult['deliveryTypesList'][$codeDelivery])) { + continue; + } + + $currentDelivery = $arResult['deliveryTypesList'][$codeDelivery]; + $deliveryPaymentTypes = $currentDelivery['paymentTypes']; + $deliveryPaymentTypes[] = $codePayment; + + $response = $api->deliveryTypesEdit([ + 'code' => $codeDelivery, + 'paymentTypes' => $deliveryPaymentTypes, + 'name' => $currentDelivery['name'] + ]); + + if (!$response->isSuccessful()) { + RCrmActions::eventLog( + 'Retailcrm::options.php', + 'syncIntegrationPayment::UpdateDelivery', + GetMessage('ERROR_LINK_INTEGRATION_PAYMENT') . ' : ' . $response->getResponseBody() + ); + + $error = 'ERR_CHECK_JOURNAL'; + } + } + } else { + RCrmActions::eventLog( + 'Retailcrm::options.php', + 'syncIntegrationPayment', + GetMessage('ERROR_LINK_INTEGRATION_PAYMENT') . ' : ' . $response->getResponseBody() + ); + + $syncIntegrationPayment = 'N'; + $error = 'ERR_CHECK_JOURNAL'; + } + } + } + + RetailcrmConfigProvider::setSubstitutionPaymentList($substitutionPaymentList); + } + + ConfigProvider::setSyncIntegrationPayment($syncIntegrationPayment); + COption::SetOptionString( $mid, $CRM_COUPON_FIELD, @@ -997,7 +1065,12 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { COption::SetOptionString($mid, $PROTOCOL, 'http://'); } - $uri .= '&ok=Y'; + if ($error !== null) { + $uri .= '&errc=' . $error; + } else { + $uri .= '&ok=Y'; + } + LocalRedirect($uri); } else { $api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0); @@ -1094,6 +1167,14 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { $availableSites, $api->paymentTypesList()->paymentTypes ); + + $arResult['paymentTypesList'] = array_filter( + $arResult['paymentTypesList'], + function ($payment) { + return strripos($payment['code'], Constants::CRM_PART_SUBSTITUTED_PAYMENT_CODE) === false; + } + ); + $arResult['deliveryTypesList'] = RetailCrmService::getAvailableTypes( $availableSites, $api->deliveryTypesList()->deliveryTypes @@ -1149,6 +1230,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { $optionsOrderNumbers = COption::GetOptionString($mid, $CRM_ORDER_NUMBERS, 0); $optionsOrderVat = COption::GetOptionString($mid, $CRM_ORDER_VAT, 0); $optionsOrderTrackNumber = ConfigProvider::getTrackNumberStatus(); + $optionsSyncIntegrationPayment = ConfigProvider::getSyncIntegrationPayment(); $canselOrderArr = unserialize(COption::GetOptionString($mid, $CRM_CANSEL_ORDER, 0)); $sendPickupPointAddress = COption::GetOptionString($mid, Constants::CRM_SEND_PICKUP_POINT_ADDRESS, 'N'); @@ -1634,6 +1716,16 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { return true; }); + $('.r-sync-payment-button label').change(function() { + if ($(this).find('input').is(':checked') === true) { + $('tr.r-sync-payment').show('slow'); + } else if ($(this).find('input').is(':checked') === false) { + $('tr.r-sync-payment').hide('slow'); + } + + return true; + }); + $('.r-ac-button label').change(function() { if ($(this).find('input').is(':checked') === true) { $('tr.r-ac').show('slow'); @@ -1853,7 +1945,8 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { > + + + + + + > + +

+

+ + + @@ -3318,4 +3433,4 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { End(); ?> - \ No newline at end of file + diff --git a/tests/classes/general/events/RetailCrmEventTest.php b/tests/classes/general/events/RetailCrmEventTest.php index 3796f688..9254896e 100755 --- a/tests/classes/general/events/RetailCrmEventTest.php +++ b/tests/classes/general/events/RetailCrmEventTest.php @@ -1,5 +1,7 @@ createMock(\Bitrix\Sale\Payment::class); + $date = \Bitrix\Main\Type\DateTime::createFromPhp(new DateTime('2000-01-01'))->format('Y-m-d H:i:s'); + $order = $this->createMock(\Bitrix\Sale\Order::class); + + $order->expects($this->any()) + ->method('isNew') + ->willReturn(false); + + $paymentCollection = $this->createMock(\Bitrix\Sale\PaymentCollection::class); + $paymentCollection->expects($this->any()) + ->method('getOrder') + ->willReturn($order); + + $event->method('getCollection')->willReturn($paymentCollection); + $event->method('getId')->willReturn(11); + $event->method('getField')->willReturnCallback(function ($field) use ($date){ + switch ($field) { + case 'ORDER_ID': return 11; + case 'PAID': return 'paid'; + case 'PAY_SYSTEM_ID': return 1; + case 'SUM': return '500'; + case 'DATE_PAID': return $date; + default: return null; + } + }); + + $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); + $spy = \Mockery::spy('overload:' . RCrmActions::class); //Добавление слежки за классом + + $GLOBALS['RETAIL_CRM_HISTORY'] = false; + + $result = RetailCrmEvent::paymentSave($event); + + //Проверка вызова класса и передачи определенных параметров + $spy->shouldReceive('apiMethod')->with( + $api, + 'ordersPaymentCreate', + 'RetailCrmEvent::paymentSave', + [ + 'externalId' => null, + 'order' => ['externalId' => 11], + 'type' => 'testPayment' + ], + null + )->once(); + + $this->assertEquals(true, $result); + } + + /** * @dataProvider paymentSaveDataProvider */ - public function testPaymentSave($history, $new) + public function testSavePaymentWithHistoryAndCreateOrder($history, $new) { $event = $this->createMock(\Bitrix\Sale\Payment::class); @@ -81,6 +142,65 @@ class RetailCrmEventTest extends PHPUnit\Framework\TestCase $this->assertEquals(false, $result); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testPaymentSaveWithSyncIntegrationPayment() + { + RetailcrmConfigProvider::setSyncIntegrationPayment('Y'); + RetailcrmConfigProvider::setIntegrationPaymentTypes(['testPayment']); + + $event = $this->createMock(\Bitrix\Sale\Payment::class); + $date = \Bitrix\Main\Type\DateTime::createFromPhp(new DateTime('2000-01-01'))->format('Y-m-d H:i:s'); + $order = $this->createMock(\Bitrix\Sale\Order::class); + + $order->expects($this->any()) + ->method('isNew') + ->willReturn(false); + + $paymentCollection = $this->createMock(\Bitrix\Sale\PaymentCollection::class); + $paymentCollection->expects($this->any()) + ->method('getOrder') + ->willReturn($order); + + $event->method('getCollection')->willReturn($paymentCollection); + $event->method('getId')->willReturn(11); + $event->method('getField')->willReturnCallback(function ($field) use ($date){ + switch ($field) { + case 'ORDER_ID': return 11; + case 'PAID': return 'paid'; + case 'PAY_SYSTEM_ID': return 1; + case 'SUM': return '500'; + case 'DATE_PAID': return $date; + default: return null; + } + }); + + $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); + $spy = \Mockery::spy('overload:' . RCrmActions::class); + + $GLOBALS['RETAIL_CRM_HISTORY'] = false; + + $result = RetailCrmEvent::paymentSave($event); + + $spy->shouldReceive('apiMethod')->with( + $api, + 'ordersPaymentCreate', + 'RetailCrmEvent::paymentSave', + [ + 'externalId' => null, + 'order' => ['externalId' => 11], + 'type' => 'testPayment' . Constants::CRM_PART_SUBSTITUTED_PAYMENT_CODE, + 'status' => 'paid', + 'paidAt' => $date + ], + null + )->once(); + + $this->assertEquals(true, $result); + } + /** * @param $history * @@ -239,10 +359,6 @@ class RetailCrmEventTest extends PHPUnit\Framework\TestCase 'history' => true, 'new' => false ], - [ - 'history' => false, - 'new' => false - ], [ 'history' => false, 'new' => true diff --git a/tests/classes/general/order/RetailCrmOrder_v5Test.php b/tests/classes/general/order/RetailCrmOrder_v5Test.php index 0c96c580..87baabbe 100644 --- a/tests/classes/general/order/RetailCrmOrder_v5Test.php +++ b/tests/classes/general/order/RetailCrmOrder_v5Test.php @@ -29,7 +29,9 @@ class RetailCrmOrder_v5Test extends BitrixTestCase { */ public function testOrderSend($arFields, $arParams, $methodApi, $expected) { + RetailcrmConfigProvider::setIntegrationPaymentTypes([]); RetailcrmConfigProvider::setCustomFieldsStatus('Y'); + RetailcrmConfigProvider::setSyncIntegrationPayment('N'); self::assertEquals($expected, RetailCrmOrder::orderSend( $arFields, @@ -44,13 +46,14 @@ class RetailCrmOrder_v5Test extends BitrixTestCase { /** * @dataProvider orderSendProvider */ - public function testOrderSendWitIntegrationPayment( + public function testOrderSendWithIntegrationPayment( array $arFields, array $arParams, string $methodApi, array $expected ): void { RetailcrmConfigProvider::setIntegrationPaymentTypes(['testPayment']); + RetailcrmConfigProvider::setSyncIntegrationPayment('N'); $orderSend = RetailCrmOrder::orderSend( $arFields, @@ -65,6 +68,34 @@ class RetailCrmOrder_v5Test extends BitrixTestCase { static::assertEquals($expected['payments'][0], $orderSend['payments'][0]); } + /** + * @dataProvider orderSendProvider + */ + public function testOrderSendIntegrationPaymentWithEnableOption( + array $arFields, + array $arParams, + string $methodApi, + array $expected + ): void { + RetailcrmConfigProvider::setIntegrationPaymentTypes(['testPayment']); + RetailcrmConfigProvider::setSyncIntegrationPayment('Y'); + + $orderSend = RetailCrmOrder::orderSend( + $arFields, + new stdClass(), + $arParams, + false, + null, + $methodApi + ); + + self::assertEquals($expected['payments'][0]['paidAt'], $orderSend['payments'][0]['paidAt']); + self::assertEquals($expected['payments'][0]['status'], $orderSend['payments'][0]['status']); + self::assertEquals($expected['payments'][0]['type'] . '-not-integration', $orderSend['payments'][0]['type']); + + RetailcrmConfigProvider::setSyncIntegrationPayment('N'); + } + public function testFieldExists(): void { $order = \Bitrix\Sale\Order::create('s1', 1, 'RUB'); diff --git a/tests/classes/general/services/RetailCrmServiceTest.php b/tests/classes/general/services/RetailCrmServiceTest.php index 0394d32f..103446e4 100644 --- a/tests/classes/general/services/RetailCrmServiceTest.php +++ b/tests/classes/general/services/RetailCrmServiceTest.php @@ -59,9 +59,9 @@ class RetailCrmServiceTest extends PHPUnit\Framework\TestCase $result = RetailCrmService::getAvailableTypes($sites, $types); $this->assertCount(3, $result); - $this->assertEquals('test1', $result[0]['code']); - $this->assertEquals('test4', $result[1]['code']); - $this->assertEquals('test6', $result[2]['code']); + $this->assertEquals('test1', $result['test1']['code']); + $this->assertEquals('test4', $result['test4']['code']); + $this->assertEquals('test6', $result['test6']['code']); } public function selectIntegrationDeliveriesProvider()