1
0
Fork 0
mirror of synced 2025-04-18 16:41:02 +00:00

add register component (#148)

This commit is contained in:
Сергей Чазов 2020-11-03 17:37:15 +03:00 committed by Neur0toxine
parent a12a3a2dba
commit 6b56785118
8 changed files with 85 additions and 399 deletions

View file

@ -1,207 +0,0 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Component\Loyalty
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Component\Loyalty;
IncludeModuleLangFile(__FILE__);
use Bitrix\Main\ArgumentException;
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;
use Intaro\RetailCrm\Component\ConfigProvider;
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
use Intaro\RetailCrm\Service\LoyaltyService;
/**
* Class EventsHandlers
*
* @package Intaro\RetailCrm\Component\Loyalty
*/
class EventsHandlers
{
const BONUS_ERROR_MSG = 'Нельзя потратить такое количество бонусов';
/**
* @param \Bitrix\Main\Event $event
*/
public function OnBeforeSalePaymentSetFieldHandler(Event $event): void
{
AddMessage2Log('OnBeforeSalePaymentSetFieldHandler work! ' . $event->getDebugInfo());
}
/**
* @return mixed
*/
public function OnBeforeEndBufferContentHandler()
{
AddMessage2Log('OnBeforeEndBufferContentHandler work! ');
}
/**
* @param \Bitrix\Main\Event $event
*/
public function OnSaleOrderBeforeSavedHandler(Event $event): void
{
AddMessage2Log('OnSaleOrderBeforeSavedHandler work! ' . $event->getDebugInfo());
}
/**
* @param \Bitrix\Main\Event $event
*/
public function OnSaleOrderPaidHandler(Event $event): void
{
AddMessage2Log('OnSaleOrderPaidHandler work! ' . $event->getDebugInfo());
}
/**
* @param \Bitrix\Main\Event $event
*/
public function OnSaleStatusOrderChangeHandler(Event $event): void
{
AddMessage2Log('OnSaleStatusOrderChangeHandler work! ' . $event->getDebugInfo());
}
/**
* @param \Bitrix\Main\Event $event
*/
public function OnSaleOrderCanceledHandler(Event $event): void
{
AddMessage2Log('OnSaleOrderCanceledHandler work! ' . $event->getDebugInfo());
}
/**
* @param \Bitrix\Main\Event $event
*/
public function OnSaleOrderDeletedHandler(Event $event): void
{
AddMessage2Log('OnSaleOrderDeletedHandler work! ' . $event->getDebugInfo());
}
/**
* @param $arResult
* @param $arUserResult
* @param $arParams
*
* @return mixed
*/
public function OnSaleComponentOrderOneStepProcessHandler($arResult, $arUserResult, $arParams)
{
AddMessage2Log('OnSaleComponentOrderOneStepProcessHandler work! ' . $arUserResult . $arParams);
return $arResult;
}
/**
* Обработчик события, вызываемого при обновлении еще не сохраненного заказа
*
* @param \Bitrix\Sale\Order $order
* @param array $arUserResult
* @param \Bitrix\Main\HttpRequest $request
* @param array $arParams
* @param array $arResult
*/
public function OnSaleComponentOrderResultPreparedHandler(Order $order, array $arUserResult, HttpRequest $request, array $arParams, array &$arResult): void
{
if (ConfigProvider::getLoyaltyProgramStatus() === 'Y') {
$bonusInput = (int)$request->get('bonus-input');
$availableBonuses = (int)$request->get('available-bonuses');
if ($bonusInput > $availableBonuses) {
$arResult['LOYALTY']['ERROR'] = GetMessage('BONUS_ERROR_MSG');
return;
}
if ($bonusInput > 0
&& $availableBonuses > 0
&& $arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'] >= $bonusInput
) {
$arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'] -= $bonusInput;
$arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE_FORMATED'] = number_format($arResult['JS_DATA']['TOTAL']['ORDER_TOTAL_PRICE'], 0, ',', ' ');
$arResult['JS_DATA']['TOTAL']['BONUS_PAYMENT'] = $bonusInput;
}
}
}
/**
* Обработчик события, вызываемого ПОСЛЕ сохранения заказа
*
* @param \Bitrix\Main\Event $event
*/
public function OnSaleOrderSavedHandler(Event $event): void
{
/**@var \Bitrix\Sale\Order $order */
$order = $event->getParameter("ENTITY");
$isNew = $event->getParameter("IS_NEW");
if (isset($_POST['bonus-input'], $_POST['available-bonuses'])
&& $isNew
&& (int) $_POST['available-bonuses'] >= (int) $_POST['bonus-input']
) {
$orderId = $order->getId();
$bonusCount = $_POST['bonus-input'];
$service = new LoyaltyService();
$response = $service->sendBonusPayment($orderId, $bonusCount);
//TODO - заглушка до появления api на стороне CRM. После появления реального апи - убрать следующую строку
$response->success = true;
$response->verification->checkId = 'проверочный код.';
//конец заглушки
if ($response->success) {
try {
$bonusPaySystem = PaySystemActionRepository::getFirstByWhere(['ID'], [['ACTION_FILE', '=', 'retailcrmbonus']]);
$paymentCollection = $order->getPaymentCollection();
if ($bonusPaySystem !== null) {
if (count($paymentCollection) === 1) {
/** @var \Bitrix\Sale\Payment $payment */
foreach ($paymentCollection as $payment){
$oldSum = $payment->getField('SUM');
$payment->setField('SUM', $oldSum - $bonusCount);
break;
}
}
$service = Manager::getObjectById($bonusPaySystem->getId());
$newPayment = $paymentCollection->createItem($service);
$newPayment->setField('SUM', $bonusCount);
//если верификация необходима, но не пройдена
if (isset($response->verification, $response->verification->checkId)
&& !isset($response->verification->verifiedAt)
) {
$newPayment->setPaid('N');
$newPayment->setField('COMMENTS', $response->verification->checkId);
}
//если верификация не нужна
if (!isset($response->verification)) {
$newPayment->setPaid('Y');
}
$order->save();
}
} catch (ObjectPropertyException | ArgumentException | SystemException | Exception $e) {
AddMessage2Log('ERROR PaySystemActionRepository: ' . $e->getMessage());
}
}
}
}
}

View file

@ -1,2 +0,0 @@
<?php
$MESS["BONUS_ERROR_MSG"] = 'Нельзя потратить такое количество бонусов';

View file

@ -1,3 +1,3 @@
<?php
$MESS["CAN_NOT_SAVE_ORDER"] = 'Невозможно добавить заказ в RetailCRM ';
$MESS["CAN_NOT_SAVE_ORDER"] = 'Невозможно добавить заказ в retailCRM ';
$MESS["BONUS_ERROR_MSG"] = 'Нельзя потратить такое количество бонусов';

View file

@ -11,6 +11,8 @@
*/
namespace Intaro\RetailCrm\Model\Api;
use Intaro\RetailCrm\Component\Json\Mapping;
/**
* Class CalculateMaximum
*

View file

@ -13,7 +13,6 @@ namespace Intaro\RetailCrm\Model\Api\Request\Loyalty;
use Intaro\RetailCrm\Component\Json\Mapping;
use Intaro\RetailCrm\Model\Api\AbstractApiModel;
use Intaro\RetailCrm\Model\Api\SerializedOrder;
/**
* Class LoyaltyCalculateRequest

View file

@ -1,94 +0,0 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Service
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
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\SmsVerificationStatusRequest;
use Intaro\RetailCrm\Model\Api\SmsVerificationConfirm;
use Intaro\RetailCrm\Repository\UserRepository;
/**
* Class UserVerificationService
*/
class UserAccountService
{
/**
* @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter
*/
private $client;
/**
* UserAccountService constructor.
*/
public function __construct()
{
$this->client = ClientFactory::createClientAdapter();
}
/**
* Получает статус текущего состояния верификации
*
* @param string $checkId Идентификатор проверки кода
* @return \Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationStatusResponse|null
*/
public function getSmsStatus(string $checkId)
{
$request = new SmsVerificationStatusRequest();
$request->checkId = $checkId;
return $this->client->checkStatusPlVerification($request);
}
/**
* Подтверждает верификацию
*
* @param string $code Проверочный код
* @param string $checkId Идентификатор проверки кода
* @return \Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationConfirmResponse|null
*/
public function confirmVerification(string $code, string $checkId)
{
$request = new SmsVerificationConfirmRequest();
$request->verification = new SmsVerificationConfirm();
$request->verification->setCode($code);
$request->verification->setCheckId($checkId);
return $this->client->confirmLpVerificationBySMS($request);
}
/**
* Проверяем статус регистрации пользователя в ПЛ
*
* @param int $userId
* @return bool
*/
public function checkPlRegistrationStatus(int $userId)
{
//TODO когда метод будет реализован в АПИ, нужно будет написать реализацию
return true;
}
/**
* @throws \Exception
*/
private function checkAuth()
{
global $USER;
$user = $USER;
if (!$user->IsAuthorized()) {
throw new Exception(self::NOT_AUTHORIZE);
}
}
}

View file

@ -0,0 +1,82 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Service
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
namespace Intaro\RetailCrm\Service;
use Exception;
use Intaro\RetailCrm\Component\Factory\ClientFactory;
use Intaro\RetailCrm\Model\Api\Customer;
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersEditRequest;
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersGetRequest;
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersUploadRequest;
use Intaro\RetailCrm\Model\Api\Request\Loyalty\Account\LoyaltyAccountActivateRequest;
use Intaro\RetailCrm\Model\Api\Request\Loyalty\Account\LoyaltyAccountCreateRequest;
use Intaro\RetailCrm\Model\Api\Request\SmsVerification\SmsVerificationConfirmRequest;
use Intaro\RetailCrm\Model\Api\Response\CustomersUploadResponse;
use Intaro\RetailCrm\Model\Api\Response\Loyalty\Account\LoyaltyAccountActivateResponse;
use Intaro\RetailCrm\Model\Api\Response\Loyalty\Account\LoyaltyAccountCreateResponse;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationConfirmResponse;
use Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationStatusRequest;
use Intaro\RetailCrm\Model\Api\SerializedCreateLoyaltyAccount;
use Intaro\RetailCrm\Model\Api\SmsVerificationConfirm;
use Intaro\RetailCrm\Model\Api\User;
use RuntimeException;
/**
* Class UserService
*/
class UserService
{
/**
* @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter
*/
private $client;
/**
* LoyaltyService constructor.
*/
public function __construct()
{
IncludeModuleLangFile(__FILE__);
$this->client = ClientFactory::createClientAdapter();
}
/**
* @param \Intaro\RetailCrm\Model\Api\Customer $customer
* @return \Intaro\RetailCrm\Model\Api\Response\CustomersUploadResponse|null
*/
public function addNewUser(Customer $customer): ?CustomersUploadResponse
{
$customersGetRequest = new CustomersGetRequest();
$customersGetRequest->id = $customer->id;
$customersGetRequest->by = 'externalId';
$customersGetRequest->site = $customer->site;
$customerResponse = $this->client->customersGet($customersGetRequest);
if ($customerResponse !== null
&& $customerResponse->success
&& isset($customerResponse->customer->id)
) {
$customersEditRequest = new CustomersEditRequest();
$customersEditRequest->customer = $customer;
$customersEditRequest->site = $customer->site;
$this->client->customersEdit($customersEditRequest);
} else {
$customersUploadRequest = new CustomersUploadRequest();
$customersUploadRequest->site = $customer->site;
$customersUploadRequest->customers[0] = $customer;
return $this->client->customersUpload($customersUploadRequest);
}
}
}

View file

@ -1,94 +0,0 @@
<?php
/**
* PHP version 7.1
*
* @category Integration
* @package Intaro\RetailCrm\Service
* @author retailCRM <integration@retailcrm.ru>
* @license MIT
* @link http://retailcrm.ru
* @see http://retailcrm.ru/docs
*/
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;
/**
* Class UserVerificationService
*/
class UserVerificationService
{
const NOT_AUTHORIZE = 'Пользователь не авторизован';
const DEFAULT_CODE_LENGHT = 4;
/**
* @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter
*/
private $client;
public function __construct()
{
$this->client = ClientFactory::createClientAdapter();
}
/**
* Получает статус текущего состояния верификации
*
* @param string $checkId Идентификатор проверки кода
* @return \Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationStatusResponse|null
*/
public function getSmsStatus(string $checkId)
{
$request = new SmsVerificationStatusRequest();
$request->checkId = $checkId;
return $this->client->checkStatusPlVerification($request);
}
/**
* Подтверждает верификацию
*
* @param string $code Проверочный код
* @param string $checkId Идентификатор проверки кода
* @return \Intaro\RetailCrm\Model\Api\Response\SmsVerification\SmsVerificationConfirmResponse|null
*/
public function confirmVerification(string $code, string $checkId): ?SmsVerificationConfirmResponse
{
$request = new SmsVerificationConfirmRequest();
$request->verification = new SmsVerificationConfirm();
$request->verification->setCode($code);
$request->verification->setCheckId($checkId);
return $this->client->confirmLpVerificationBySMS($request);
}
/**
* Проверяем статус регистрации пользователя в ПЛ
*
* @param int $userId
* @return bool
*/
public function checkPlRegistrationStatus(int $userId)
{
//TODO когда метод будет реализован в АПИ, нужно будет написать реализацию
return $userId;
}
/**
* @throws \Exception
*/
private function checkAuth()
{
global $USER;
$user = $USER;
if (!$user->IsAuthorized()) {
throw new Exception(self::NOT_AUTHORIZE);
}
}
}