1
0
Fork 0
mirror of synced 2025-04-20 01:21:01 +00:00

add sms confirmation after order saved

This commit is contained in:
Sergey Chazov 2020-10-21 15:44:10 +03:00
parent fa8163a4ce
commit a83ab55564
11 changed files with 224 additions and 46 deletions

View file

@ -1,6 +1,12 @@
<? if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();
<?php if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
die();
}
use Bitrix\Main\ArgumentException;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\SystemException;
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
/**
* @var array $arParams
@ -14,17 +20,18 @@ if ($arParams["SET_TITLE"] == "Y")
}
?>
<? if (!empty($arResult["ORDER"])): ?>
<?php if (!empty($arResult["ORDER"])): ?>
<?php
$order = Bitrix\Sale\Order::load($arResult["ORDER"]['ID']);
$paymentCollection = $order->getPaymentCollection();
/** @var \Bitrix\Sale\Payment $payment */
foreach ($paymentCollection as $payment) {
$isPaid = $payment->isPaid();
$isPaid = $payment->isPaid();
$checkId = $payment->getField('COMMENTS');
try {
$paySystemAction = \Intaro\RetailCrm\Repository\PaySystemActionRepository::getFirstByWhere(
$paySystemAction = PaySystemActionRepository::getFirstByWhere(
['*'],
[
[
@ -34,23 +41,29 @@ if ($arParams["SET_TITLE"] == "Y")
],
]
);
} catch (\Bitrix\Main\ObjectPropertyException | \Bitrix\Main\ArgumentException | \Bitrix\Main\SystemException $e) {
} catch (ObjectPropertyException | ArgumentException | SystemException $e) {
AddMessage2Log($e->getMessage());
}
//если есть бонусная оплата и она не оплачена, то отрисовываем форму введения кода верификации
$isPaid=false;//TODO заглушка - убрать после теста
if ($paySystemAction->get('CODE') === 'INTARO_BONUS' && !$isPaid) {
if (isset($paySystemAction)
&& !$isPaid
&& !empty($checkId)
&& $paySystemAction->get('CODE') === 'INTARO_BONUS'
) {
?>
<div id="orderConfirm">
<b><?= GetMessage('CONFIRM_MESSAGE')?></b><br>
<div id="orderVerificationCodeBlock" style="display: none;">
<div id="orderVerificationCodeBlock">
<b><?= GetMessage('SEND_VERIFICATION_CODE')?></b><br>
<label for="orderVerificationCode"></label>
<input type="text" id="orderVerificationCode" placeholder="<?= GetMessage('VERIFICATION_CODE')?>">
<input type="button" onclick="sendVerificationCode()" value="<?= GetMessage('SEND')?>"/>
<input type="button" onclick="sendVerificationCode(<?= $arResult["ORDER"]['ID'] ?>, '<?= $checkId ?>')" value="<?= GetMessage('SEND')?>"/>
</div>
<div id="msg"></div>
</div>
<br><br>
<?php
}
}
@ -63,11 +76,6 @@ if ($arParams["SET_TITLE"] == "Y")
"#ORDER_DATE#" => $arResult["ORDER"]["DATE_INSERT"]->toUserTime()->format('d.m.Y H:i'),
"#ORDER_ID#" => $arResult["ORDER"]["ACCOUNT_NUMBER"]
))?>
<? if (!empty($arResult['ORDER']["PAYMENT_ID"])): ?>
<?=Loc::getMessage("SOA_PAYMENT_SUC", array(
"#PAYMENT_ID#" => $arResult['PAYMENT'][$arResult['ORDER']["PAYMENT_ID"]]['ACCOUNT_NUMBER']
))?>
<? endif ?>
<? if ($arParams['NO_PERSONAL'] !== 'Y'): ?>
<br /><br />
<?=Loc::getMessage('SOA_ORDER_SUC1', ['#LINK#' => $arParams['PATH_TO_PERSONAL']])?>

View file

@ -143,4 +143,5 @@ $MESS["BONUS_TOTAL"] = 'Всего бонусов:';
$MESS["YOU_CAN_SPEND"] = 'Можно потратить:';
$MESS["CALCULATION_ERROR"] = 'Не удалось рассчитать количество доступных бонусов.';
$MESS["CONFIRM_MESSAGE"] = 'Для завершения процедуры списания бонусов, введите код верификации';
$MESS["SEND"] = 'Отправить';

View file

@ -134,6 +134,7 @@ BX.namespace('BX.Sale.OrderAjaxComponent');
this.propsHiddenBlockNode = BX(parameters.propsBlockId + '-hidden');
this.loyaltyStatus = parameters.loyaltyStatus;
this.personalLoyaltyStatus = parameters.personalLoyaltyStatus;
if (this.result.SHOW_AUTH) {
this.authBlockNode.style.display = '';
@ -8307,21 +8308,23 @@ BX.namespace('BX.Sale.OrderAjaxComponent');
this.totalInfoBlockNode.appendChild(this.createTotalUnit(discText + ':', total.DISCOUNT_PRICE_FORMATED, {highlighted: true}));
}
//добавление строки с бонусами
if (this.result.TOTAL.BONUS_PAYMENT !== undefined && this.result.TOTAL.BONUS_PAYMENT > 0) {
let bonusPayment = this.result.TOTAL.BONUS_PAYMENT.toString();
bonusPayment = this.bonusCurrency
.replace('&#8381;', '₽')
.replace('&euro;', '€')
.replace('&#8372;', '¥')
.replace('#', bonusPayment);
this.totalInfoBlockNode.appendChild(this.createTotalUnit('Бонусная скидка:', bonusPayment));
//проверяем включена ли ПЛ и участвует ли в ней данный пользователь
if (this.personalLoyaltyStatus === '1' && this.loyaltyStatus === 'Y') {
//добавление строки с бонусами
if (this.result.TOTAL.BONUS_PAYMENT !== undefined && this.result.TOTAL.BONUS_PAYMENT > 0) {
let bonusPayment = this.result.TOTAL.BONUS_PAYMENT.toString();
bonusPayment = this.bonusCurrency
.replace('&#8381;', '₽')
.replace('&euro;', '€')
.replace('&#8372;', '¥')
.replace('#', bonusPayment);
this.totalInfoBlockNode.appendChild(this.createTotalUnit('Бонусная скидка:', bonusPayment));
}
const willBeCredited = this.willBeCredited;
this.totalInfoBlockNode.appendChild(this.createTotalUnit('Будет начислено бонусов:', willBeCredited, {highlighted: true}));
}
const willBeCredited = this.willBeCredited;
this.totalInfoBlockNode.appendChild(this.createTotalUnit('Будет начислено бонусов:', willBeCredited, {highlighted: true}));
if (this.options.showPayedFromInnerBudget)
{
this.totalInfoBlockNode.appendChild(this.createTotalUnit(BX.message('SOA_SUM_IT'), total.ORDER_TOTAL_PRICE_FORMATED));

View file

@ -18,6 +18,7 @@ if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
Loader::includeModule('intaro.retailcrm');
$arResult['LOYALTY_STATUS'] = ConfigProvider::getLoyaltyProgramStatus();
$arResult['PERSONAL_LOYALTY_STATUS'] = LoyaltyService::getLoyaltyPersonalStatus();
//TODO Закомментированно до появления реального апи
//TODO добавить проверку на участие покупателя в программе лояльности (таска 68813)

View file

@ -21,24 +21,27 @@ $(document).ready(function() {
$('#bonus-input').on('keydown', _.debounce(makeAjaxRequest, 1000));
});
function sendVerificationCode() {
function sendVerificationCode(orderId, checkId) {
const verificationCode = $('#orderVerificationCode').val();
BX.ajax.runAction('intaro:retailcrm.api.loyalty.register.sendVerificationCode',
BX.ajax.runAction('intaro:retailcrm.api.loyalty.order.sendVerificationCode',
{
data: {
sessid: BX.bitrix_sessid(),
code: verificationCode
verificationCode: verificationCode,
orderId: orderId,
checkId: checkId
}
}
).then(
function(response) {
if (response.data.status === 'error' && response.data.msg !== undefined) {
const msg = response.data.msg;
$('#msg').text(msg);
const msg = $('#msg');
msg.text(response.data.msg);
msg.css('color', response.data.msgColor);
}
if (response.data.status === 'activate') {
if (response.data.status === 'success') {
const msgBlock = $('#orderConfirm');
msgBlock.text(response.data.msg);
msgBlock.css('color', response.data.msgColor);

View file

@ -425,7 +425,7 @@ if (strlen($request->get('ORDER_ID')) > 0) {
<? endif ?>
<!-- INTARO BONUS BLOCK -->
<? if ($arResult['LOYALTY_STATUS'] === 'Y' ): ?>
<? if ($arResult['LOYALTY_STATUS'] === 'Y' && $arResult['PERSONAL_LOYALTY_STATUS'] === true): ?>
<div id="bx-soa-intaro" data-visited="true" class="bx-soa-section bx-selected">
<div class="bx-soa-section-title-container">
<h2 class="bx-soa-section-title col-sm-9">
@ -594,16 +594,17 @@ if (strlen($request->get('ORDER_ID')) > 0) {
zoom: 7
}
},
orderBlockId: 'bx-soa-order',
authBlockId: 'bx-soa-auth',
basketBlockId: 'bx-soa-basket',
regionBlockId: 'bx-soa-region',
paySystemBlockId: 'bx-soa-paysystem',
deliveryBlockId: 'bx-soa-delivery',
pickUpBlockId: 'bx-soa-pickup',
propsBlockId: 'bx-soa-properties',
totalBlockId: 'bx-soa-total',
loyaltyStatus: '<?=$arResult['LOYALTY_STATUS']?>'
orderBlockId: 'bx-soa-order',
authBlockId: 'bx-soa-auth',
basketBlockId: 'bx-soa-basket',
regionBlockId: 'bx-soa-region',
paySystemBlockId: 'bx-soa-paysystem',
deliveryBlockId: 'bx-soa-delivery',
pickUpBlockId: 'bx-soa-pickup',
propsBlockId: 'bx-soa-properties',
totalBlockId: 'bx-soa-total',
loyaltyStatus: '<?=$arResult['LOYALTY_STATUS']?>',
personalLoyaltyStatus: '<?=$arResult['PERSONAL_LOYALTY_STATUS']?>'
});
</script>
<script>

View file

@ -19,6 +19,7 @@ use Bitrix\Main\Event;
use Bitrix\Main\HttpRequest;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\SystemException;
use Bitrix\Sale\Internals\PaymentTable;
use Bitrix\Sale\Order;
use Bitrix\Sale\PaySystem\Manager;
use Exception;
@ -155,6 +156,8 @@ class EventsHandlers
//TODO - заглушка до появления api на стороне CRM. После появления реального апи - убрать следующую строку
$response->success = true;
$response->verification->checkId = 'проверочный код.';
//конец заглушки
if ($response->success) {
try {
@ -178,8 +181,10 @@ class EventsHandlers
$newPayment->setField('SUM', $bonusCount);
//если верификация необходима, но не пройдена
if (isset($response->verification) && !isset($response->verification->verifiedAt)) {
if (isset($response->verification, $response->verification->checkId) && !isset($response->verification->verifiedAt)
) {
$newPayment->setPaid('N');
$newPayment->setField('COMMENTS', $response->verification->checkId);
}
//если верификация не нужна

View file

@ -0,0 +1,136 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Controller\Loyalty
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Controller\Loyalty;
use Bitrix\Main\ArgumentException;
use Bitrix\Main\ArgumentNullException;
use Bitrix\Main\Engine\ActionFilter\Authentication;
use Bitrix\Main\Engine\ActionFilter\HttpMethod;
use Bitrix\Main\Engine\Controller;
use Bitrix\Main\Loader;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\Request;
use Bitrix\Main\SystemException;
use Exception;
use Intaro\RetailCrm\Component\ServiceLocator;
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
use Intaro\RetailCrm\Service\UserVerificationService;
/**
* Class AdminPanel
* @package Intaro\RetailCrm\Controller\Loyalty
*/
class Order extends Controller
{
/** @var UserVerificationService */
private $service;
/**
* AdminPanel constructor.
*
* @param \Bitrix\Main\Request|null $request
*/
public function __construct(Request $request = null)
{
$this->service = ServiceLocator::get(UserVerificationService::class);
parent::__construct($request);
}
/**
* @param string $verificationCode
* @param int $orderId
* @param string $checkId
* @return array
*/
public function sendVerificationCodeAction(string $verificationCode, int $orderId, string $checkId): array
{
$response = $this->service->confirmVerification($verificationCode, $checkId);
$response->success = true;
$response->verification->verifiedAt = '123';
if ($response !== null
&& $response->success
&& isset($response->verification->verifiedAt)
&& !empty($response->verification->verifiedAt)
) {
try {
Loader::includeModule('sale');
$order = \Bitrix\Sale\Order::load($orderId);
if (!$order) {
AddMessage2Log('ОШибка списания бонусов (не удалось получить заказ) по заказу №'.$orderId);
return [
'status' => 'error',
'msg' => 'Ошибка',
'msgColor' => 'brown',
];
}
$paymentCollection = $order->getPaymentCollection();
/** @var \Bitrix\Sale\Payment $payment */
foreach ($paymentCollection as $payment) {
$isPaid = $payment->isPaid();
try {
$paySystemAction = PaySystemActionRepository::getFirstByWhere(
['*'],
[
['ID', '=', $payment->getField('PAY_SYSTEM_ID')],
]
);
} catch (ObjectPropertyException | ArgumentException | SystemException $e) {
AddMessage2Log($e->getMessage());
}
if (isset($paySystemAction)
&& !$isPaid
&& $paySystemAction->get('CODE') === 'INTARO_BONUS'
) {
$payment->setPaid('Y');
$order->save();
}
}
} catch (Exception | ArgumentNullException $exception) {
AddMessage2Log($exception->getMessage());
}
return [
'status' => 'success',
'msg' => 'Бонусы успешно списаны',
'msgColor' => 'green',
];
}
return [
'status' => 'error',
'msg' => 'Ошибка',
'msgColor' => 'brown',
];
}
/**
* @return \array[][]
*/
public function sendVerificationCode(): array
{
return [
'sendSms' => [
'-prefilters' => [
new Authentication,
new HttpMethod(['GET']),
],
],
];
}
}

View file

@ -32,6 +32,7 @@ class AdminPanel extends Controller
/**
* AdminPanel constructor.
*
* @param \Bitrix\Main\Request|null $request
*/
public function __construct(Request $request = null)

View file

@ -14,12 +14,19 @@ namespace Intaro\RetailCrm\Service;
use Bitrix\Catalog\GroupTable;
use Bitrix\Main\ArgumentException;
use Bitrix\Main\ArgumentNullException;
use Bitrix\Main\Loader;
use Bitrix\Main\LoaderException;
use Bitrix\Main\ObjectPropertyException;
use Bitrix\Main\SystemException;
use Bitrix\Sale\Order;
use CUser;
use Exception;
use Intaro\RetailCrm\Component\Factory\ClientFactory;
use Intaro\RetailCrm\Model\Api\Request\Loyalty\LoyaltyCalculateRequest;
use Intaro\RetailCrm\Model\Api\Request\Order\Loyalty\OrderLoyaltyApplyRequest;
use Intaro\RetailCrm\Model\Api\SerializedOrderProduct;
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
/**
* Class LoyaltyService
@ -41,6 +48,17 @@ class LoyaltyService
$this->client = ClientFactory::createClientAdapter();
}
/*
* Возвращает статус пользователя в системе лояльности
*/
public static function getLoyaltyPersonalStatus(): bool
{
global $USER;
$userFields = CUser::GetByID($USER->GetID())->Fetch();
return isset($userFields['UF_EXT_REG_PL_INTARO']) && $userFields['UF_EXT_REG_PL_INTARO'] === '1';
}
/**
* @param int $orderId
* @param int $bonusCount

View file

@ -14,6 +14,7 @@ namespace Intaro\RetailCrm\Service;
use Exception;
use Intaro\RetailCrm\Component\Factory\ClientFactory;
use Intaro\RetailCrm\Model\Api\Request\SmsVerification\SmsVerificationConfirmRequest;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationConfirmResponse;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationStatusRequest;
use Intaro\RetailCrm\Model\Api\SmsVerificationConfirm;
@ -56,7 +57,7 @@ class UserVerificationService
* @param string $checkId Идентификатор проверки кода
* @return \Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationConfirmResponse|null
*/
public function confirmVerification(string $code, string $checkId)
public function confirmVerification(string $code, string $checkId): ?SmsVerificationConfirmResponse
{
$request = new SmsVerificationConfirmRequest();
$request->verification = new SmsVerificationConfirm();