1
0
mirror of synced 2024-11-21 21:06:09 +03:00

ref #92904 Передача данных интегрированных оплат (#335)

This commit is contained in:
Kocmonavtik 2024-01-24 15:01:13 +03:00 committed by GitHub
parent b8ac495a37
commit ad04daa904
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 397 additions and 43 deletions

View File

@ -1,3 +1,6 @@
## 2024-01-22 v.6.5.7
- Доработана передача данных интеграционных оплат в систему
## 2024-01-12 v.6.5.6 ## 2024-01-12 v.6.5.6
- Добавлена передача дополнительных свойств товаров через конфигурируемый файл - Добавлена передача дополнительных свойств товаров через конфигурируемый файл

View File

@ -1,6 +1,7 @@
<?php <?php
use Bitrix\Main\Context\Culture; use Bitrix\Main\Context\Culture;
use Intaro\RetailCrm\Component\Constants;
use Intaro\RetailCrm\Component\ServiceLocator; use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Repository\UserRepository; use Intaro\RetailCrm\Repository\UserRepository;
use Intaro\RetailCrm\Service\CustomerService; use Intaro\RetailCrm\Service\CustomerService;
@ -524,18 +525,13 @@ class RetailCrmEvent
} }
if (!empty($arPayment['PAY_SYSTEM_ID']) && isset($optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']])) { if (!empty($arPayment['PAY_SYSTEM_ID']) && isset($optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']])) {
$paymentToCrm = [ $paymentToCrm = [];
'type' => $optionsPaymentTypes[$arPayment['PAY_SYSTEM_ID']],
];
if (!empty($arPayment['ID'])) { if (!empty($arPayment['ID'])) {
$paymentToCrm['externalId'] = RCrmActions::generatePaymentExternalId($arPayment['ID']); $paymentToCrm['externalId'] = RCrmActions::generatePaymentExternalId($arPayment['ID']);
} }
$isIntegrationPayment if (!empty($arPayment['DATE_PAID'])) {
= RetailCrmService::isIntegrationPayment($arPayment['PAY_SYSTEM_ID'] ?? null);
if (!empty($arPayment['DATE_PAID']) && !$isIntegrationPayment) {
if (is_object($arPayment['DATE_PAID'])) { if (is_object($arPayment['DATE_PAID'])) {
$culture = new Culture(['FORMAT_DATETIME' => 'YYYY-MM-DD HH:MI:SS']); $culture = new Culture(['FORMAT_DATETIME' => 'YYYY-MM-DD HH:MI:SS']);
$paymentToCrm['paidAt'] = $arPayment['DATE_PAID']->toString($culture); $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']]; $paymentToCrm['status'] = $optionsPayStatuses[$arPayment['PAID']];
} }
@ -555,6 +551,8 @@ class RetailCrmEvent
if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { if (RetailcrmConfigProvider::shouldSendPaymentAmount()) {
$paymentToCrm['amount'] = $arPayment['SUM']; $paymentToCrm['amount'] = $arPayment['SUM'];
} }
$paymentToCrm = RetailCrmService::preparePayment($paymentToCrm, $arPayment, $optionsPaymentTypes);
} else { } else {
RCrmActions::eventLog('RetailCrmEvent::paymentSave', 'payments', 'OrderID = ' . $arPayment['ID'] . '. Payment not found.'); RCrmActions::eventLog('RetailCrmEvent::paymentSave', 'payments', 'OrderID = ' . $arPayment['ID'] . '. Payment not found.');
return false; return false;

View File

@ -52,6 +52,8 @@ class RetailCrmHistory
public static $CUSTOM_FIELDS_IS_ACTIVE = 'N'; public static $CUSTOM_FIELDS_IS_ACTIVE = 'N';
const PAGE_LIMIT = 25; const PAGE_LIMIT = 25;
private static $optionsPayment = [];
public static function customerHistory() public static function customerHistory()
{ {
if (!RetailcrmDependencyLoader::loadDependencies()) { if (!RetailcrmDependencyLoader::loadDependencies()) {
@ -280,6 +282,25 @@ class RetailCrmHistory
$contragentTypes = array_flip(RetailcrmConfigProvider::getContragentTypes()); $contragentTypes = array_flip(RetailcrmConfigProvider::getContragentTypes());
$shipmentDeducted = RetailcrmConfigProvider::getShipmentDeducted(); $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 = RetailcrmConfigProvider::getMatchedUserFields() ?? [];
$matchedCustomUserFields = is_array($matchedCustomUserFields) ? array_flip($matchedCustomUserFields) : []; $matchedCustomUserFields = is_array($matchedCustomUserFields) ? array_flip($matchedCustomUserFields) : [];
@ -1941,14 +1962,17 @@ class RetailCrmHistory
*/ */
public static function paymentsUpdate($order, $paymentsCrm, &$newHistoryPayments = []) public static function paymentsUpdate($order, $paymentsCrm, &$newHistoryPayments = [])
{ {
$optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0))); $optionsPayTypes = self::$optionsPayment['payTypes'];
$optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0))); $optionsPayment = self::$optionsPayment['paymentList'];
$allPaymentSystems = RCrmActions::PaymentList(); $allPaymentSystems = RCrmActions::PaymentList();
foreach ($allPaymentSystems as $allPaymentSystem) { foreach ($allPaymentSystems as $allPaymentSystem) {
$arPaySysmems[$allPaymentSystem['ID']] = $allPaymentSystem['NAME']; $arPaySysmems[$allPaymentSystem['ID']] = $allPaymentSystem['NAME'];
} }
$paymentsList = []; $paymentsList = [];
$paymentColl = $order->getPaymentCollection(); $paymentColl = $order->getPaymentCollection();
foreach ($paymentColl as $paymentData) { foreach ($paymentColl as $paymentData) {
$data = $paymentData->getFields()->getValues(); $data = $paymentData->getFields()->getValues();
$paymentsList[$data['ID']] = $paymentData; $paymentsList[$data['ID']] = $paymentData;
@ -1956,6 +1980,7 @@ class RetailCrmHistory
//data from crm //data from crm
$paySumm = 0; $paySumm = 0;
foreach ($paymentsCrm['payments'] as $paymentCrm) { foreach ($paymentsCrm['payments'] as $paymentCrm) {
if (isset($paymentCrm['externalId']) && !empty($paymentCrm['externalId'])) { if (isset($paymentCrm['externalId']) && !empty($paymentCrm['externalId'])) {
//find the payment //find the payment

View File

@ -9,6 +9,7 @@ use Bitrix\Sale\Internals\OrderTable;
use Bitrix\Sale\Location\LocationTable; use Bitrix\Sale\Location\LocationTable;
use Bitrix\Sale\Order; use Bitrix\Sale\Order;
use Intaro\RetailCrm\Component\ApiClient\ClientAdapter; use Intaro\RetailCrm\Component\ApiClient\ClientAdapter;
use Intaro\RetailCrm\Component\Constants;
use Intaro\RetailCrm\Component\Factory\ClientFactory; use Intaro\RetailCrm\Component\Factory\ClientFactory;
use Intaro\RetailCrm\Component\ServiceLocator; use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Service\LoyaltyService; use Intaro\RetailCrm\Service\LoyaltyService;
@ -365,30 +366,27 @@ class RetailCrmOrder
$payments = []; $payments = [];
foreach ($arOrder['PAYMENTS'] as $payment) { 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']])) { if (!empty($payment['PAY_SYSTEM_ID']) && isset($arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']])) {
$pm = [ $crmPayment = [];
'type' => $arParams['optionsPayTypes'][$payment['PAY_SYSTEM_ID']]
]; 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'])) { if (!empty($payment['ID'])) {
$pm['externalId'] = RCrmActions::generatePaymentExternalId($payment['ID']); $crmPayment['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']];
} }
if (RetailcrmConfigProvider::shouldSendPaymentAmount()) { if (RetailcrmConfigProvider::shouldSendPaymentAmount()) {
$pm['amount'] = $payment['SUM']; $crmPayment['amount'] = $payment['SUM'];
} }
$payments[] = $pm; $crmPayment = RetailCrmService::preparePayment($crmPayment, $payment, $arParams['optionsPayTypes']);
$payments[] = $crmPayment;
} else { } else {
RCrmActions::eventLog( RCrmActions::eventLog(
'RetailCrmOrder::orderSend', 'RetailCrmOrder::orderSend',

View File

@ -1,5 +1,7 @@
<?php <?php
use Intaro\RetailCrm\Component\Constants;
/** /**
* Class RetailCrmService * Class RetailCrmService
*/ */
@ -141,11 +143,11 @@ class RetailCrmService
} }
if (empty($type['sites'])) { if (empty($type['sites'])) {
$result[] = $type; $result[$type['code']] = $type;
} else { } else {
foreach ($type['sites'] as $site) { foreach ($type['sites'] as $site) {
if (!empty($availableSites[$site])) { if (!empty($availableSites[$site])) {
$result[] = $type; $result[$type['code']] = $type;
break; break;
} }
} }
@ -178,4 +180,29 @@ class RetailCrmService
); );
} }
} }
/**
* @param array $crmPayment
* @param array $bitrixPayment
* @param array $optionsPaymentTypes
* @return array mixed
*/
public static function preparePayment($crmPayment, $bitrixPayment, $optionsPaymentTypes)
{
$isIntegrationPayment = self::isIntegrationPayment($bitrixPayment['PAY_SYSTEM_ID'] ?? null);
if ($isIntegrationPayment && RetailcrmConfigProvider::getSyncIntegrationPayment() === 'Y') {
$crmPayment['type'] = $optionsPaymentTypes[$bitrixPayment['PAY_SYSTEM_ID']] .
Constants::CRM_PART_SUBSTITUTED_PAYMENT_CODE;
} else {
$crmPayment['type'] = $optionsPaymentTypes[$bitrixPayment['PAY_SYSTEM_ID']];
if ($isIntegrationPayment) {
unset($crmPayment['paidAt'], $crmPayment['status']);
}
}
return $crmPayment;
}
} }

View File

@ -1 +1 @@
- Добавлена передача дополнительных свойств товаров через конфигурируемый файл - Доработана передача данных интеграционных оплат в систему

View File

@ -1,6 +1,6 @@
<?php <?php
$arModuleVersion = [ $arModuleVersion = [
'VERSION' => '6.5.6', 'VERSION' => '6.5.7',
'VERSION_DATE' => '2024-01-12 17:00:00' 'VERSION_DATE' => '2024-01-22 11:00:00'
]; ];

View File

@ -137,3 +137,12 @@ $MESS ['DELETE_MATCHED'] = 'Delete';
$MESS ['LOCATION_LABEL'] = 'Location'; $MESS ['LOCATION_LABEL'] = 'Location';
$MESS ['TEXT_ADDRESS_LABEL'] = 'Address (line)'; $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';

View File

@ -196,3 +196,12 @@ $MESS ['DELETE_MATCHED'] = 'Удалить';
$MESS ['LOCATION_LABEL'] = 'Местоположение (LOCATION)'; $MESS ['LOCATION_LABEL'] = 'Местоположение (LOCATION)';
$MESS ['TEXT_ADDRESS_LABEL'] = 'Адрес (строкой)'; $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'] = 'Для корректной работы опции апи-ключу необходимы доступы на получение и редактирование справочников';

View File

@ -1171,6 +1171,26 @@ class ConfigProvider
return static::getOption(Constants::RECEIVE_TRACK_NUMBER_DELIVERY); 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 * @return string
*/ */

View File

@ -108,4 +108,7 @@ class Constants
public const MATCHED_CUSTOM_USER_FIELDS = 'matched_custom_field'; public const MATCHED_CUSTOM_USER_FIELDS = 'matched_custom_field';
public const USE_CRM_ORDER_METHODS = 'use_crm_order_methods'; public const USE_CRM_ORDER_METHODS = 'use_crm_order_methods';
public const CRM_ORDER_METHODS = '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';
} }

View File

@ -244,6 +244,7 @@ if (!empty($availableSites)) {
//update connection settings //update connection settings
if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
$error = null;
$api_host = htmlspecialchars(trim($_POST['api_host'])); $api_host = htmlspecialchars(trim($_POST['api_host']));
$api_key = htmlspecialchars(trim($_POST['api_key'])); $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'); 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( COption::SetOptionString(
$mid, $mid,
$CRM_COUPON_FIELD, $CRM_COUPON_FIELD,
@ -997,7 +1065,12 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
COption::SetOptionString($mid, $PROTOCOL, 'http://'); COption::SetOptionString($mid, $PROTOCOL, 'http://');
} }
if ($error !== null) {
$uri .= '&errc=' . $error;
} else {
$uri .= '&ok=Y'; $uri .= '&ok=Y';
}
LocalRedirect($uri); LocalRedirect($uri);
} else { } else {
$api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0); $api_host = COption::GetOptionString($mid, $CRM_API_HOST_OPTION, 0);
@ -1094,6 +1167,14 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
$availableSites, $availableSites,
$api->paymentTypesList()->paymentTypes $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( $arResult['deliveryTypesList'] = RetailCrmService::getAvailableTypes(
$availableSites, $availableSites,
$api->deliveryTypesList()->deliveryTypes $api->deliveryTypesList()->deliveryTypes
@ -1149,6 +1230,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
$optionsOrderNumbers = COption::GetOptionString($mid, $CRM_ORDER_NUMBERS, 0); $optionsOrderNumbers = COption::GetOptionString($mid, $CRM_ORDER_NUMBERS, 0);
$optionsOrderVat = COption::GetOptionString($mid, $CRM_ORDER_VAT, 0); $optionsOrderVat = COption::GetOptionString($mid, $CRM_ORDER_VAT, 0);
$optionsOrderTrackNumber = ConfigProvider::getTrackNumberStatus(); $optionsOrderTrackNumber = ConfigProvider::getTrackNumberStatus();
$optionsSyncIntegrationPayment = ConfigProvider::getSyncIntegrationPayment();
$canselOrderArr = unserialize(COption::GetOptionString($mid, $CRM_CANSEL_ORDER, 0)); $canselOrderArr = unserialize(COption::GetOptionString($mid, $CRM_CANSEL_ORDER, 0));
$sendPickupPointAddress = COption::GetOptionString($mid, Constants::CRM_SEND_PICKUP_POINT_ADDRESS, 'N'); $sendPickupPointAddress = COption::GetOptionString($mid, Constants::CRM_SEND_PICKUP_POINT_ADDRESS, 'N');
@ -1634,6 +1716,16 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
return true; 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() { $('.r-ac-button label').change(function() {
if ($(this).find('input').is(':checked') === true) { if ($(this).find('input').is(':checked') === true) {
$('tr.r-ac').show('slow'); $('tr.r-ac').show('slow');
@ -1853,7 +1945,8 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
<select name="payment-type-<?php echo $bitrixPaymentType['ID']; ?>" class="typeselect"> <select name="payment-type-<?php echo $bitrixPaymentType['ID']; ?>" class="typeselect">
<option value="" selected=""></option> <option value="" selected=""></option>
<?php foreach ($arResult['paymentTypesList'] as $paymentType): ?> <?php foreach ($arResult['paymentTypesList'] as $paymentType): ?>
<option value="<?php echo $paymentType['code']; ?>" <?php if ($optionsPayTypes[$bitrixPaymentType['ID']] === $paymentType['code']) { <option value="<?php echo $paymentType['code']; ?>"
<?php if ($optionsPayTypes[$bitrixPaymentType['ID']] === $paymentType['code']) {
echo 'selected'; echo 'selected';
} ?>> } ?>>
<?php echo $APPLICATION->ConvertCharset($paymentType['name'], 'utf-8', SITE_CHARSET); ?> <?php echo $APPLICATION->ConvertCharset($paymentType['name'], 'utf-8', SITE_CHARSET); ?>
@ -1864,6 +1957,28 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
</td> </td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<tr class="heading r-sync-payment-button">
<td colspan="2" class="option-other-heading">
<b>
<label>
<input class="addr" type="checkbox" name="sync-integration-payment" value="Y" <?php if ($optionsSyncIntegrationPayment === 'Y') {
echo "checked";
} ?>> <?php echo GetMessage('SYNC_INTEGRATION_PAYMENT'); ?>
</label>
</b>
</td>
</tr>
<tr class="r-sync-payment" <?php if ($optionsSyncIntegrationPayment !== 'Y') {
echo 'style="display: none;"';
} ?>>
<td class="option-head" colspan="2">
<p><b><?php echo GetMessage('INTEGRATION_PAYMENT_LABEL'); ?></b></p>
<p><b><?php echo GetMessage('NEED_PERMISSIONS_REFERENCE_LABEL'); ?></b></p>
</td>
</tr>
<tr class="heading"> <tr class="heading">
<td colspan="2"><b><?php echo GetMessage('PAYMENT_STATUS_LIST'); ?></b></td> <td colspan="2"><b><?php echo GetMessage('PAYMENT_STATUS_LIST'); ?></b></td>
</tr> </tr>

View File

@ -1,5 +1,7 @@
<?php <?php
use Intaro\RetailCrm\Component\Constants;
/** /**
* Class RetailCrmEventTest * Class RetailCrmEventTest
*/ */
@ -54,9 +56,68 @@ class RetailCrmEventTest extends PHPUnit\Framework\TestCase
* @throws \PHPUnit\Framework\MockObject\RuntimeException * @throws \PHPUnit\Framework\MockObject\RuntimeException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* *
* @runInSeparateProcess
* @preserveGlobalState disabled
*
*/
public function testIntegrationPaymentSave()
{
RetailcrmConfigProvider::setSyncIntegrationPayment('N');
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'
],
null
)->once();
$this->assertEquals(true, $result);
}
/**
* @dataProvider paymentSaveDataProvider * @dataProvider paymentSaveDataProvider
*/ */
public function testPaymentSave($history, $new) public function testSavePaymentWithHistoryAndCreateOrder($history, $new)
{ {
$event = $this->createMock(\Bitrix\Sale\Payment::class); $event = $this->createMock(\Bitrix\Sale\Payment::class);
@ -81,6 +142,65 @@ class RetailCrmEventTest extends PHPUnit\Framework\TestCase
$this->assertEquals(false, $result); $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 * @param $history
* *
@ -239,10 +359,6 @@ class RetailCrmEventTest extends PHPUnit\Framework\TestCase
'history' => true, 'history' => true,
'new' => false 'new' => false
], ],
[
'history' => false,
'new' => false
],
[ [
'history' => false, 'history' => false,
'new' => true 'new' => true

View File

@ -29,7 +29,9 @@ class RetailCrmOrder_v5Test extends BitrixTestCase {
*/ */
public function testOrderSend($arFields, $arParams, $methodApi, $expected) public function testOrderSend($arFields, $arParams, $methodApi, $expected)
{ {
RetailcrmConfigProvider::setIntegrationPaymentTypes([]);
RetailcrmConfigProvider::setCustomFieldsStatus('Y'); RetailcrmConfigProvider::setCustomFieldsStatus('Y');
RetailcrmConfigProvider::setSyncIntegrationPayment('N');
self::assertEquals($expected, RetailCrmOrder::orderSend( self::assertEquals($expected, RetailCrmOrder::orderSend(
$arFields, $arFields,
@ -44,13 +46,14 @@ class RetailCrmOrder_v5Test extends BitrixTestCase {
/** /**
* @dataProvider orderSendProvider * @dataProvider orderSendProvider
*/ */
public function testOrderSendWitIntegrationPayment( public function testOrderSendWithIntegrationPayment(
array $arFields, array $arFields,
array $arParams, array $arParams,
string $methodApi, string $methodApi,
array $expected array $expected
): void { ): void {
RetailcrmConfigProvider::setIntegrationPaymentTypes(['testPayment']); RetailcrmConfigProvider::setIntegrationPaymentTypes(['testPayment']);
RetailcrmConfigProvider::setSyncIntegrationPayment('N');
$orderSend = RetailCrmOrder::orderSend( $orderSend = RetailCrmOrder::orderSend(
$arFields, $arFields,
@ -65,6 +68,34 @@ class RetailCrmOrder_v5Test extends BitrixTestCase {
static::assertEquals($expected['payments'][0], $orderSend['payments'][0]); 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 public function testFieldExists(): void
{ {
$order = \Bitrix\Sale\Order::create('s1', 1, 'RUB'); $order = \Bitrix\Sale\Order::create('s1', 1, 'RUB');

View File

@ -59,9 +59,9 @@ class RetailCrmServiceTest extends PHPUnit\Framework\TestCase
$result = RetailCrmService::getAvailableTypes($sites, $types); $result = RetailCrmService::getAvailableTypes($sites, $types);
$this->assertCount(3, $result); $this->assertCount(3, $result);
$this->assertEquals('test1', $result[0]['code']); $this->assertEquals('test1', $result['test1']['code']);
$this->assertEquals('test4', $result[1]['code']); $this->assertEquals('test4', $result['test4']['code']);
$this->assertEquals('test6', $result[2]['code']); $this->assertEquals('test6', $result['test6']['code']);
} }
public function selectIntegrationDeliveriesProvider() public function selectIntegrationDeliveriesProvider()