add save order in CRM handler in lib folder
This commit is contained in:
parent
5e4dfda6e7
commit
be7238b746
13 changed files with 674 additions and 114 deletions
|
@ -617,24 +617,19 @@ class ApiClient
|
|||
$this->fillSite($site, $parameters)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create corporate customer address
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $address (default: array())
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \RetailCrm\Exception\CurlException
|
||||
* @throws \RetailCrm\Exception\InvalidJsonException
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $address (default: array())
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param null $site (default: null)
|
||||
*
|
||||
* @return \RetailCrm\Response\ApiResponse
|
||||
*/
|
||||
public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null)
|
||||
public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null): ApiResponse
|
||||
{
|
||||
/* @noinspection PhpUndefinedMethodInspection */
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/addresses/create",
|
||||
Client::METHOD_POST,
|
||||
|
@ -2985,7 +2980,11 @@ class ApiClient
|
|||
return $this->client->makeRequest(
|
||||
"/orders/loyalty/apply",
|
||||
Client::METHOD_POST,
|
||||
$request
|
||||
[
|
||||
'site' => $request['site'],
|
||||
'order' => json_encode($request['order']),
|
||||
'bonuses' => $request['bonuses'],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -10,24 +10,21 @@ global $MESS;
|
|||
use Bitrix\Highloadblock\HighloadBlockTable;
|
||||
use Bitrix\Main\Application;
|
||||
use Bitrix\Main\ArgumentException;
|
||||
use Bitrix\Main\ArgumentOutOfRangeException;
|
||||
use Bitrix\Main\Context;
|
||||
use Bitrix\Main\EventManager;
|
||||
use Bitrix\Main\Loader;
|
||||
use Bitrix\Main\ObjectPropertyException;
|
||||
use Bitrix\Main\SystemException;
|
||||
use Bitrix\Main\UserConsent\Internals\AgreementTable;
|
||||
use Bitrix\Sale\Internals\OrderPropsGroupTable;
|
||||
use Bitrix\Sale\Internals\PaySystemActionTable;
|
||||
use Bitrix\Sale\Delivery\Services\Manager;
|
||||
use Bitrix\sale\EventActions;
|
||||
use Bitrix\Sale\Internals\OrderTable;
|
||||
use Intaro\RetailCrm\Component\ConfigProvider;
|
||||
use Intaro\RetailCrm\Component\Handlers\EventsHandlers;
|
||||
use Intaro\RetailCrm\Model\Bitrix\Agreement;
|
||||
use Intaro\RetailCrm\Repository\AgreementRepository;
|
||||
use \RetailCrm\ApiClient;
|
||||
use RetailCrm\Exception\CurlException;
|
||||
use Intaro\RetailCrm\Component\Loyalty\EventsHandlers;
|
||||
use Intaro\RetailCrm\Repository\ToModuleRepository;
|
||||
|
||||
IncludeModuleLangFile(__FILE__);
|
||||
|
@ -1003,7 +1000,6 @@ class intaro_retailcrm extends CModule
|
|||
RegisterModule($this->MODULE_ID);
|
||||
RegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder");
|
||||
RegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
|
||||
RegisterModuleDependences("sale", EventActions::EVENT_ON_ORDER_SAVED, $this->MODULE_ID, "RetailCrmEvent", "orderSave");
|
||||
RegisterModuleDependences("sale", "OnSaleOrderDeleted", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
|
||||
RegisterModuleDependences("sale", "OnSalePaymentEntitySaved", $this->MODULE_ID, "RetailCrmEvent", "paymentSave");
|
||||
RegisterModuleDependences("sale", "OnSalePaymentEntityDeleted", $this->MODULE_ID, "RetailCrmEvent", "paymentDelete");
|
||||
|
@ -1257,16 +1253,6 @@ class intaro_retailcrm extends CModule
|
|||
COption::RemoveOption($this->MODULE_ID, $this->CLIENT_ID);
|
||||
COption::RemoveOption($this->MODULE_ID, $this->PROTOCOL);
|
||||
|
||||
if (CModule::IncludeModule('sale')) {
|
||||
UnRegisterModuleDependences(
|
||||
"sale",
|
||||
EventActions::EVENT_ON_ORDER_SAVED,
|
||||
$this->MODULE_ID,
|
||||
"RetailCrmEvent",
|
||||
"orderSave"
|
||||
);
|
||||
}
|
||||
|
||||
UnRegisterModuleDependences("sale", "OnOrderUpdate", $this->MODULE_ID, "RetailCrmEvent", "onUpdateOrder");
|
||||
UnRegisterModuleDependences("main", "OnAfterUserUpdate", $this->MODULE_ID, "RetailCrmEvent", "OnAfterUserUpdate");
|
||||
UnRegisterModuleDependences("sale", "OnSaleOrderDeleted", $this->MODULE_ID, "RetailCrmEvent", "orderDelete");
|
||||
|
@ -1522,10 +1508,6 @@ class intaro_retailcrm extends CModule
|
|||
{
|
||||
$this->addCustomUserFields(
|
||||
[
|
||||
[
|
||||
'name' => "UF_CARD_NUM_INTARO",
|
||||
'title' => GetMessage('UF_CARD_NUMBER_INTARO_TITLE'),
|
||||
],
|
||||
[
|
||||
'name' => "UF_LP_ID_INTARO",
|
||||
'title' => GetMessage('UF_LP_ID_INTARO_TITLE'),
|
||||
|
@ -1533,6 +1515,17 @@ class intaro_retailcrm extends CModule
|
|||
],
|
||||
'string'
|
||||
);
|
||||
|
||||
$this->addCustomUserFields(
|
||||
[
|
||||
[
|
||||
'name' => "UF_LP_ID_INTARO",
|
||||
'title' => GetMessage('UF_LP_ID_INTARO_TITLE'),
|
||||
],
|
||||
],
|
||||
'string',
|
||||
['EDIT_IN_LIST' => 'N']
|
||||
);
|
||||
|
||||
$this->addCustomUserFields(
|
||||
[
|
||||
|
@ -1559,8 +1552,9 @@ class intaro_retailcrm extends CModule
|
|||
/**
|
||||
* @param $fields
|
||||
* @param string $filedType
|
||||
* @param array $customProps
|
||||
*/
|
||||
public function addCustomUserFields($fields, $filedType = 'boolean'): void
|
||||
public function addCustomUserFields($fields, $filedType = 'boolean', $customProps = []): void
|
||||
{
|
||||
foreach ($fields as $filed) {
|
||||
$arProps = [
|
||||
|
@ -1572,11 +1566,12 @@ class intaro_retailcrm extends CModule
|
|||
"EDIT_FORM_LABEL" => ["ru" => $filed['title']],
|
||||
|
||||
];
|
||||
$props = array_merge($arProps, $customProps);
|
||||
$obUserField = new CUserTypeEntity;
|
||||
$dbRes = CUserTypeEntity::GetList([], ["FIELD_NAME" => $filed['name']])->fetch();
|
||||
|
||||
if (!$dbRes['ID']) {
|
||||
$obUserField->Add($arProps);
|
||||
$obUserField->Add($props);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,8 +17,8 @@ $MESS ['SALE_VERSION_ERR'] = 'Версия модуля \'Интернет-ма
|
|||
$MESS ['AGREEMENT_LOYALTY_PROGRAM_TEXT'] = 'Вставить текст Правил программы лояльности';
|
||||
$MESS ['AGREEMENT_PERSONAL_DATA_TEXT'] = 'Вставить текст соглашения на обработку персональных данных';
|
||||
|
||||
$MESS ['AGREEMENT_LOYALTY_PROGRAM_TITLE'] = 'Условия программы лояльности retailCRM';
|
||||
$MESS ['AGREEMENT_PERSONAL_DATA_TITLE'] = 'Согласие на обработку персональных данных retailCRM';
|
||||
$MESS ['AGREEMENT_LOYALTY_PROGRAM_TITLE'] = 'Согласие с условиями программы лояльности';
|
||||
$MESS ['AGREEMENT_PERSONAL_DATA_TITLE'] = 'Соглашение на обработку персональных данных';
|
||||
|
||||
$MESS ['UF_REG_IN_PL_INTARO_TITLE'] = 'Зарегистрироваться в программе лояльности';
|
||||
$MESS ['UF_AGREE_PL_INTARO_TITLE'] = 'Я согласен с условиями программы лояльности';
|
||||
|
|
|
@ -109,8 +109,8 @@ $MESS['PHONE_REQUIRED'] = "В настройках главного модуля
|
|||
|
||||
$MESS ['LOYALTY_PROGRAM_TITLE'] = 'Программа лояльности';
|
||||
$MESS ['LOYALTY_PROGRAM_TOGGLE_MSG'] = 'Активность программы лояльности';
|
||||
$MESS ['LP_CUSTOM_TEMP_CREATE_MSG'] = 'Создать шаблон intaro.retailCRM для компонента оформления заказа sale.order.ajax c функциями Программы лояльности. <br> <b>Внимение:</b> если шаблон уже существует, то он будет перезаписан';
|
||||
$MESS ['LP_CUSTOM_REG_TEMP_CREATE_MSG'] = 'Создать шаблон intaro.retailCRM для компонента регистрации main.register c функциями Программы лояльности. <br> <b>Внимение:</b> если шаблон уже существует, то он будет перезаписан';
|
||||
$MESS ['LP_CUSTOM_TEMP_CREATE_MSG'] = 'Создать шаблон intaro.retailCRM для компонента оформления заказа sale.order.ajax c функциями Программы лояльности. <br> <b>Внимание:</b> если шаблон уже существует, то он будет перезаписан';
|
||||
$MESS ['LP_CUSTOM_REG_TEMP_CREATE_MSG'] = 'Создать шаблон intaro.retailCRM для компонента регистрации main.register c функциями Программы лояльности. <br> <b>Внимание:</b> если шаблон уже существует, то он будет перезаписан';
|
||||
$MESS ['LP_DEF_TEMP_CREATE_MSG'] = 'Заменить шаблон .default компонента sale.order.ajax шаблоном с функциями Программы лояльности. <br> Если в папке шаблонов компонента уже будет .default, то он будет скопирован в папку .default_backup';
|
||||
$MESS ['LP_CREATE_TEMPLATE'] = 'Создать шаблон';
|
||||
$MESS ['LP_REPLACE_TEMPLATE'] = 'Заменить шаблон';
|
||||
|
|
|
@ -10,22 +10,17 @@
|
|||
* @link http://retailcrm.ru
|
||||
* @see http://retailcrm.ru/docs
|
||||
*/
|
||||
namespace Intaro\RetailCrm\Component\Loyalty;
|
||||
namespace Intaro\RetailCrm\Component\Handlers;
|
||||
|
||||
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\Order;
|
||||
use Bitrix\Sale\PaySystem\Manager;
|
||||
use Exception;
|
||||
use Intaro\RetailCrm\Component\ConfigProvider;
|
||||
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
|
||||
use Intaro\RetailCrm\Repository\UserRepository;
|
||||
use Intaro\RetailCrm\Service\LoyaltyService;
|
||||
use Intaro\RetailCrm\Service\OrderService;
|
||||
use Intaro\RetailCrm\Service\UserAccountService;
|
||||
use RetailCrm\ApiClient;
|
||||
use RetailcrmConfigProvider;
|
||||
|
@ -139,71 +134,17 @@ class EventsHandlers
|
|||
}
|
||||
|
||||
/**
|
||||
* Обработчик события, вызываемого ПОСЛЕ сохранения заказа
|
||||
* Обработчик события, вызываемого ПОСЛЕ сохранения заказа (OnSaleOrderSaved)
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
$orderService = new OrderService();
|
||||
$loyaltyService = new LoyaltyService();
|
||||
|
||||
//если верификация не нужна
|
||||
if (!isset($response->verification)) {
|
||||
$newPayment->setPaid('Y');
|
||||
}
|
||||
|
||||
$order->save();
|
||||
}
|
||||
} catch (ObjectPropertyException | ArgumentException | SystemException | Exception $e) {
|
||||
AddMessage2Log('ERROR PaySystemActionRepository: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
$orderService->saveOrderInCRM($event);
|
||||
$loyaltyService->applyBonusesInOrder($event);
|
||||
}
|
||||
|
||||
/**
|
|
@ -8,7 +8,6 @@ use Intaro\RetailCrm\Model\Api\Request\SmsVerification\SmsVerificationConfirmReq
|
|||
use Intaro\RetailCrm\Model\Api\SmsVerificationConfirm;
|
||||
use Intaro\RetailCrm\Model\Bitrix\User;
|
||||
use Intaro\RetailCrm\Service\UserAccountService;
|
||||
use RetailCrm\ApiClient;
|
||||
|
||||
class Register extends Controller
|
||||
{
|
||||
|
|
|
@ -32,7 +32,7 @@ class CustomersCorporateCompaniesCreateRequest extends AbstractApiModel
|
|||
public $externalId;
|
||||
|
||||
/**
|
||||
* @var \Intaro\RetailCrm\Model\Api\Company
|
||||
* @var \Intaro\RetailCrm\Model\Api\Company $company
|
||||
*
|
||||
* @Mapping\Type("Intaro\RetailCrm\Model\Api\Company")
|
||||
* @Mapping\SerializedName("company")
|
||||
|
|
|
@ -21,6 +21,16 @@ use Intaro\RetailCrm\Model\Api\AbstractApiModel;
|
|||
*/
|
||||
class OrderLoyaltyApplyRequest extends AbstractApiModel
|
||||
{
|
||||
/**
|
||||
* Символьный код магазина
|
||||
*
|
||||
* @var string $site
|
||||
*
|
||||
* @Mapping\Type("string")
|
||||
* @Mapping\SerializedName("site")
|
||||
*/
|
||||
public $site;
|
||||
|
||||
/**
|
||||
* @var \Intaro\RetailCrm\Model\Api\SerializedOrderReference
|
||||
*
|
||||
|
@ -28,4 +38,14 @@ class OrderLoyaltyApplyRequest extends AbstractApiModel
|
|||
* @Mapping\SerializedName("order")
|
||||
*/
|
||||
public $order;
|
||||
|
||||
/**
|
||||
* Количество бонусов для списания
|
||||
*
|
||||
* @var float $bonuses
|
||||
*
|
||||
* @Mapping\Type("float")
|
||||
* @Mapping\SerializedName("bonuses")
|
||||
*/
|
||||
public $bonuses;
|
||||
}
|
||||
|
|
|
@ -21,6 +21,8 @@ use Intaro\RetailCrm\Component\Json\Mapping;
|
|||
class SerializedOrderReference
|
||||
{
|
||||
/**
|
||||
* Внутренний ID заказа
|
||||
*
|
||||
* @var integer $id
|
||||
*
|
||||
* @Mapping\Type("integer")
|
||||
|
@ -29,10 +31,22 @@ class SerializedOrderReference
|
|||
public $id;
|
||||
|
||||
/**
|
||||
* @var float $bonuses
|
||||
* Внешний ID заказа
|
||||
*
|
||||
* @Mapping\Type("float")
|
||||
* @Mapping\SerializedName("bonuses")
|
||||
* @var string $externalId
|
||||
*
|
||||
* @Mapping\Type("string")
|
||||
* @Mapping\SerializedName("externalId")
|
||||
*/
|
||||
public $bonuses;
|
||||
public $externalId;
|
||||
|
||||
/**
|
||||
* Номер заказа
|
||||
*
|
||||
* @var string $number
|
||||
*
|
||||
* @Mapping\Type("string")
|
||||
* @Mapping\SerializedName("number")
|
||||
*/
|
||||
public $number;
|
||||
}
|
||||
|
|
139
intaro.retailcrm/lib/service/logger.php
Normal file
139
intaro.retailcrm/lib/service/logger.php
Normal file
|
@ -0,0 +1,139 @@
|
|||
<?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 CSite;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Class Logger
|
||||
*
|
||||
* @author retailCRM
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://help.retailcrm.pro/docs/Developers
|
||||
*/
|
||||
class Logger
|
||||
{
|
||||
/** @var self $instance */
|
||||
private static $instance;
|
||||
|
||||
/** @var string $logPath */
|
||||
private $logPath;
|
||||
|
||||
/** @var int $files */
|
||||
private $files;
|
||||
|
||||
/**
|
||||
* Get logger instance or re-initialize it with new parameters
|
||||
*
|
||||
* @param string $logPath
|
||||
* @param int $files
|
||||
*
|
||||
* @return \Intaro\RetailCrm\Service\Logger
|
||||
*/
|
||||
public static function getInstance($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3): Logger
|
||||
{
|
||||
if (empty(self::$instance)
|
||||
|| (self::$instance instanceof self
|
||||
&& (self::$instance->logPath !== $logPath || self::$instance->files !== $files))
|
||||
) {
|
||||
self::$instance = new Logger($logPath, $files);
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logger constructor.
|
||||
*
|
||||
* @param string $logPath
|
||||
* @param int $files
|
||||
*/
|
||||
public function __construct($logPath = '/bitrix/modules/intaro.retailcrm/log', $files = 3)
|
||||
{
|
||||
$this->logPath = $logPath;
|
||||
$this->files = $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $dump
|
||||
* @param string $file
|
||||
*/
|
||||
public function write($dump, $file = 'info'): void
|
||||
{
|
||||
$rsSites = CSite::GetList($by, $sort, array('DEF' => 'Y'));
|
||||
$ar = $rsSites->Fetch();
|
||||
if (!is_dir($ar['ABS_DOC_ROOT'] . $this->logPath . '/')
|
||||
&& !mkdir($concurrentDirectory = $ar['ABS_DOC_ROOT'] . $this->logPath . '/')
|
||||
&& !is_dir($concurrentDirectory)) {
|
||||
throw new RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
|
||||
}
|
||||
$file = $ar['ABS_DOC_ROOT'] . $this->logPath . '/' . $file . '.log';
|
||||
|
||||
$data['TIME'] = date('Y-m-d H:i:s');
|
||||
$data['DATA'] = $dump;
|
||||
|
||||
$f = fopen($file, 'ab+');
|
||||
fwrite($f, print_r($data, true));
|
||||
fclose($f);
|
||||
|
||||
// if filesize more than 5 Mb rotate it
|
||||
if (filesize($file) > 5242880) {
|
||||
$this->rotate($file);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $file
|
||||
*/
|
||||
private function rotate($file): void
|
||||
{
|
||||
$path = pathinfo($file);
|
||||
$rotate = implode('', array(
|
||||
$path['dirname'],
|
||||
'/',
|
||||
$path['filename'],
|
||||
'_',
|
||||
date('Y-m-d_H:i:s'),
|
||||
'.',
|
||||
$path['extension']
|
||||
));
|
||||
|
||||
copy($file, $rotate);
|
||||
$this->clean($file);
|
||||
|
||||
$files = glob($path['dirname'] . '/' . $path['filename'] . "*" . ".log");
|
||||
|
||||
if (0 === $this->files) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (count($files) > $this->files) {
|
||||
natsort($files);
|
||||
$files = array_reverse($files);
|
||||
foreach (array_slice($files, $this->files) as $log) {
|
||||
if (is_writable($log)) {
|
||||
unlink($log);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $file
|
||||
*/
|
||||
private function clean($file): void
|
||||
{
|
||||
file_put_contents($file, '');
|
||||
}
|
||||
}
|
|
@ -16,11 +16,13 @@ namespace Intaro\RetailCrm\Service;
|
|||
use Bitrix\Catalog\GroupTable;
|
||||
use Bitrix\Main\ArgumentException;
|
||||
use Bitrix\Main\ArgumentNullException;
|
||||
use Bitrix\Main\Event;
|
||||
use Bitrix\Main\Loader;
|
||||
use Bitrix\Main\LoaderException;
|
||||
use Bitrix\Main\ObjectPropertyException;
|
||||
use Bitrix\Main\SystemException;
|
||||
use Bitrix\Sale\Order;
|
||||
use Bitrix\Sale\PaySystem\Manager;
|
||||
use CUser;
|
||||
use Exception;
|
||||
use Intaro\RetailCrm\Component\Factory\ClientFactory;
|
||||
|
@ -32,6 +34,7 @@ use Intaro\RetailCrm\Model\Api\Request\Order\Loyalty\OrderLoyaltyApplyRequest;
|
|||
use Intaro\RetailCrm\Model\Api\SerializedOrder;
|
||||
use Intaro\RetailCrm\Model\Api\SerializedOrderProduct;
|
||||
use Intaro\RetailCrm\Model\Api\SerializedOrderProductOffer;
|
||||
use Intaro\RetailCrm\Model\Api\SerializedOrderReference;
|
||||
use Intaro\RetailCrm\Model\Api\SerializedRelationCustomer;
|
||||
use Intaro\RetailCrm\Repository\PaySystemActionRepository;
|
||||
|
||||
|
@ -81,9 +84,14 @@ class LoyaltyService
|
|||
*/
|
||||
public function sendBonusPayment(int $orderId, int $bonusCount)
|
||||
{
|
||||
$request = new OrderLoyaltyApplyRequest();
|
||||
$request->order->id = $orderId;
|
||||
$request->order->bonuses = $bonusCount;
|
||||
$request = new OrderLoyaltyApplyRequest();
|
||||
$request->order = new SerializedOrderReference();
|
||||
$request->order->externalId = $orderId;
|
||||
$request->bonuses = $bonusCount;
|
||||
/** @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter $client */
|
||||
$client = ClientFactory::createClientAdapter();
|
||||
$credentials = $client->getCredentials();
|
||||
$request->site = $credentials->sitesAvailable[0];
|
||||
|
||||
$result = $this->client->loyaltyOrderApply($request);
|
||||
|
||||
|
@ -279,6 +287,66 @@ class LoyaltyService
|
|||
return $regInLp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Bitrix\Main\Event $event
|
||||
*/
|
||||
public function applyBonusesInOrder(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 = (int) $_POST['bonus-input'];
|
||||
$response = $this->sendBonusPayment($orderId, $bonusCount);
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $userFields
|
||||
* @return array
|
||||
|
|
385
intaro.retailcrm/lib/service/orderservice.php
Normal file
385
intaro.retailcrm/lib/service/orderservice.php
Normal file
|
@ -0,0 +1,385 @@
|
|||
<?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 Bitrix\Main\ArgumentException;
|
||||
use Bitrix\Main\ObjectPropertyException;
|
||||
use Bitrix\Main\SystemException;
|
||||
use Bitrix\Main\UserTable;
|
||||
use CModule;
|
||||
use Intaro\RetailCrm\Component\Factory\ClientFactory;
|
||||
use Intaro\RetailCrm\Model\Api\Address;
|
||||
use Intaro\RetailCrm\Model\Api\Company;
|
||||
use Intaro\RetailCrm\Model\Api\Contragent;
|
||||
use Intaro\RetailCrm\Model\Api\Customer;
|
||||
use Intaro\RetailCrm\Model\Api\CustomerContact;
|
||||
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersCorporateAddressesCreateRequest;
|
||||
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersCorporateCompaniesCreateRequest;
|
||||
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersCorporateCompaniesRequest;
|
||||
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersCorporateContactsCreateRequest;
|
||||
use Intaro\RetailCrm\Model\Api\Request\Customers\CustomersCorporateListRequest;
|
||||
use RCrmActions;
|
||||
use RetailcrmConfigProvider;
|
||||
use RetailCrmCorporateClient;
|
||||
use RetailCrmOrder;
|
||||
use RetailCrmUser;
|
||||
|
||||
/**
|
||||
* Class LoyaltyService
|
||||
*
|
||||
* @package Intaro\RetailCrm\Service
|
||||
*/
|
||||
class OrderService
|
||||
{
|
||||
public function saveOrderInCRM($event)
|
||||
{
|
||||
if (true === $GLOBALS['ORDER_DELETE_USER_ADMIN']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($GLOBALS['RETAILCRM_ORDER_OLD_EVENT'] === false
|
||||
&& $GLOBALS['RETAILCRM_ORDER_DELETE'] === true
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($GLOBALS['RETAIL_CRM_HISTORY'] === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CModule::IncludeModule('iblock')) {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'iblock', 'module not found');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CModule::IncludeModule("sale")) {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'sale', 'module not found');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!CModule::IncludeModule("catalog")) {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'catalog', 'module not found');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//exists getParameter("ENTITY")
|
||||
if (method_exists($event, 'getId')) {
|
||||
$obOrder = $event;
|
||||
} elseif (method_exists($event, 'getParameter')) {
|
||||
$obOrder = $event->getParameter("ENTITY");
|
||||
} else {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'events', 'event error');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$arOrder = RetailCrmOrder::orderObjToArr($obOrder);
|
||||
} catch (SystemException $exception) {
|
||||
AddMessage2Log($exception->getMessage());
|
||||
}
|
||||
|
||||
/** @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter $client */
|
||||
$api = ClientFactory::createClientAdapter();
|
||||
|
||||
if ($api === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
//params
|
||||
$optionsOrderTypes = RetailcrmConfigProvider::getOrderTypes();
|
||||
$optionsDeliveryTypes = RetailcrmConfigProvider::getDeliveryTypes();
|
||||
$optionsPayTypes = RetailcrmConfigProvider::getPaymentTypes();
|
||||
$optionsPayStatuses = RetailcrmConfigProvider::getPaymentStatuses(); // --statuses
|
||||
$optionsPayment = RetailcrmConfigProvider::getPayment();
|
||||
$optionsSitesList = RetailcrmConfigProvider::getSitesList();
|
||||
$optionsOrderProps = RetailcrmConfigProvider::getOrderProps();
|
||||
$optionsLegalDetails = RetailcrmConfigProvider::getLegalDetails();
|
||||
$optionsContragentType = RetailcrmConfigProvider::getContragentTypes();
|
||||
$optionsCustomFields = RetailcrmConfigProvider::getCustomFields();
|
||||
|
||||
//corp cliente swich
|
||||
$optionCorpClient = RetailcrmConfigProvider::getCorporateClientStatus();
|
||||
|
||||
$arParams = RCrmActions::clearArr([
|
||||
'optionsOrderTypes' => $optionsOrderTypes,
|
||||
'optionsDelivTypes' => $optionsDeliveryTypes,
|
||||
'optionsPayTypes' => $optionsPayTypes,
|
||||
'optionsPayStatuses' => $optionsPayStatuses,
|
||||
'optionsPayment' => $optionsPayment,
|
||||
'optionsOrderProps' => $optionsOrderProps,
|
||||
'optionsLegalDetails' => $optionsLegalDetails,
|
||||
'optionsContragentType' => $optionsContragentType,
|
||||
'optionsSitesList' => $optionsSitesList,
|
||||
'optionsCustomFields' => $optionsCustomFields,
|
||||
]);
|
||||
|
||||
//many sites?
|
||||
if ($optionsSitesList) {
|
||||
if (isset($arOrder)
|
||||
&& array_key_exists($arOrder['LID'], $optionsSitesList)
|
||||
&& $optionsSitesList[$arOrder['LID']] !== null) {
|
||||
$site = $optionsSitesList[$arOrder['LID']];
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} elseif (!$optionsSitesList) {
|
||||
$site = null;
|
||||
}
|
||||
|
||||
//new order?
|
||||
$orderCrm = RCrmActions::apiMethod($api, 'ordersGet', __METHOD__, $arOrder['ID'], $site);
|
||||
if (isset($orderCrm['order'])) {
|
||||
$methodApi = 'ordersEdit';
|
||||
$arParams['crmOrder'] = $orderCrm['order'];
|
||||
} else {
|
||||
$methodApi = 'ordersCreate';
|
||||
}
|
||||
|
||||
$orderCompany = null;
|
||||
|
||||
if ("Y" === $optionCorpClient && $optionsContragentType[$arOrder['PERSON_TYPE_ID']] === 'legal-entity') {
|
||||
//corparate cliente
|
||||
$nickName = '';
|
||||
$address = '';
|
||||
$contractor = new Contragent();
|
||||
$userCorp = [];
|
||||
$corpName = RetailcrmConfigProvider::getCorporateClientName();
|
||||
$corpAddress = RetailcrmConfigProvider::getCorporateClientAddress();
|
||||
|
||||
foreach ($arOrder['PROPS']['properties'] as $prop) {
|
||||
if ($prop['CODE'] === $corpName) {
|
||||
$nickName = $prop['VALUE'][0];
|
||||
}
|
||||
|
||||
if ($prop['CODE'] === $corpAddress) {
|
||||
$address = $prop['VALUE'][0];
|
||||
}
|
||||
|
||||
if (!empty($optionsLegalDetails)
|
||||
&& $search = array_search($prop['CODE'], $optionsLegalDetails[$arOrder['PERSON_TYPE_ID']], true)
|
||||
) {
|
||||
$contractor->{$search} = $prop['VALUE'][0];//legal order data
|
||||
}
|
||||
}
|
||||
|
||||
$customersCorporateRequest = new CustomersCorporateListRequest();
|
||||
$customersCorporateRequest->filter->companyName = $nickName;
|
||||
$response = $api->customersCorporateList($customersCorporateRequest);
|
||||
|
||||
if ($response && $response->success === true) {
|
||||
$customersCorporate = $response['customersCorporate'];
|
||||
$singleCorp = reset($customersCorporate);
|
||||
|
||||
if (!empty($singleCorp)) {
|
||||
$userCorp['customerCorporate'] = $singleCorp;
|
||||
|
||||
$customersCorporateCompaniesRequest = new CustomersCorporateCompaniesRequest();
|
||||
$customersCorporateCompaniesRequest->site = $site;
|
||||
$customersCorporateCompaniesRequest->by = 'id';
|
||||
$customersCorporateCompaniesRequest->idOrExternalId = $singleCorp['id'];
|
||||
$customersCorporateCompaniesRequest->filter =[];
|
||||
$customersCorporateCompaniesRequest->page =null;
|
||||
$customersCorporateCompaniesRequest->limit =null;
|
||||
|
||||
$companiesResponse = $api->customersCorporateCompanies($customersCorporateCompaniesRequest);
|
||||
|
||||
if ($companiesResponse && $companiesResponse->success === true) {
|
||||
$orderCompany = array_reduce(
|
||||
$companiesResponse['companies'],
|
||||
static function ($carry, $item) use ($nickName) {
|
||||
if (is_array($item) && $item['name'] === $nickName) {
|
||||
$carry = $item;
|
||||
}
|
||||
|
||||
return $carry;
|
||||
},
|
||||
null
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
RCrmActions::eventLog(
|
||||
'RetailCrmEvent::orderSave',
|
||||
'ApiClient::customersCorporateList',
|
||||
'error during fetching corporate customers'
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//user
|
||||
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site);
|
||||
|
||||
if (!isset($userCrm['customer'])) {
|
||||
try {
|
||||
$arUser = UserTable::getById($arOrder['USER_ID'])->fetch();
|
||||
} catch (ObjectPropertyException | ArgumentException | SystemException $exception) {
|
||||
AddMessage2Log($exception);
|
||||
}
|
||||
|
||||
if (!empty($address)) {
|
||||
$arUser['PERSONAL_STREET'] = $address;
|
||||
}
|
||||
|
||||
$resultUser = RetailCrmUser::customerSend($arUser, $api, "individual", true, $site);
|
||||
|
||||
if (!$resultUser) {
|
||||
RCrmActions::eventLog(
|
||||
__CLASS__ . '::' . __METHOD__,
|
||||
'RetailCrmUser::customerSend',
|
||||
'error during creating customer'
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$userCrm = ['customer' => ['externalId' => $arOrder['USER_ID']]];
|
||||
}
|
||||
|
||||
if (!isset($userCorp['customerCorporate'])) {
|
||||
$resultUserCorp = RetailCrmCorporateClient::clientSend(
|
||||
$arOrder,
|
||||
$api,
|
||||
$optionsContragentType[$arOrder['PERSON_TYPE_ID']],
|
||||
true,
|
||||
false,
|
||||
$site
|
||||
);
|
||||
|
||||
Logger::getInstance()->write($resultUserCorp, 'resultUserCorp');
|
||||
|
||||
if (!$resultUserCorp) {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmCorporateClient::clientSend', 'error during creating client');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$arParams['customerCorporate'] = $resultUserCorp;
|
||||
$arParams['orderCompany'] = $resultUserCorp['mainCompany'] ?? null;
|
||||
|
||||
$addressResult = null;
|
||||
$companyResult = null;
|
||||
$customerCorporateCompany = [];
|
||||
|
||||
if (!empty($address)) {
|
||||
$customersCorporateAddressesCreateRequest = new CustomersCorporateAddressesCreateRequest();
|
||||
$customersCorporateAddressesCreateRequest->externalId = $resultUserCorp['id'];
|
||||
$customersCorporateAddressesCreateRequest->address = new Address;
|
||||
$customersCorporateAddressesCreateRequest->address->name = $nickName;
|
||||
$customersCorporateAddressesCreateRequest->address->isMain = true;
|
||||
$customersCorporateAddressesCreateRequest->address->text = $address;
|
||||
$customersCorporateAddressesCreateRequest->by = 'id';
|
||||
$customersCorporateAddressesCreateRequest->site = $site;
|
||||
|
||||
$addressResult = $api->customersCorporateAddressesCreate($customersCorporateAddressesCreateRequest);
|
||||
}
|
||||
|
||||
if ($addressResult->success === true) {
|
||||
$customerCorporateCompany['address'] = [
|
||||
'id' => $addressResult['id'],
|
||||
];
|
||||
}
|
||||
|
||||
$customersCorporateCompaniesCreateRequest = new CustomersCorporateCompaniesCreateRequest();
|
||||
$customersCorporateCompaniesCreateRequest->externalId = $resultUserCorp['id'];
|
||||
$customersCorporateCompaniesCreateRequest->company = new Company();
|
||||
$customersCorporateCompaniesCreateRequest->company->name = $nickName;
|
||||
$customersCorporateCompaniesCreateRequest->company->isMain = true;
|
||||
$customersCorporateCompaniesCreateRequest->company->contragent = $contractor;
|
||||
$customersCorporateCompaniesCreateRequest->by = 'id';
|
||||
$customersCorporateCompaniesCreateRequest->site = $site;
|
||||
|
||||
$companyResult = $api->customersCorporateCompaniesCreate($customersCorporateCompaniesCreateRequest);
|
||||
|
||||
$customersCorporateContactsCreateRequest= new CustomersCorporateContactsCreateRequest();
|
||||
$customersCorporateContactsCreateRequest->contact = new CustomerContact;
|
||||
$customersCorporateContactsCreateRequest->contact->isMain = true;
|
||||
$customersCorporateContactsCreateRequest->contact->customer = new Customer;
|
||||
$customersCorporateContactsCreateRequest->contact->customer->externalId = $arOrder['USER_ID'];
|
||||
$customersCorporateContactsCreateRequest->contact->customer->site = $site;
|
||||
$customersCorporateContactsCreateRequest->site = $site;
|
||||
$customersCorporateContactsCreateRequest->idOrExternalId = $resultUserCorp['id'];
|
||||
|
||||
if ($companyResult->success === true) {
|
||||
$company = new Company();
|
||||
$company->id = $companyResult->id;
|
||||
$customersCorporateContactsCreateRequest->contact->companies[0] = $company;
|
||||
}
|
||||
|
||||
$api->customersCorporateContactsCreate($customersCorporateContactsCreateRequest);
|
||||
|
||||
$arParams['orderCompany'] = array_merge(
|
||||
$customerCorporateCompany,
|
||||
['id' => $companyResult['id']]
|
||||
);
|
||||
} else {
|
||||
RetailCrmCorporateClient::addCustomersCorporateAddresses(
|
||||
$userCorp['customerCorporate']['id'],
|
||||
$nickName,
|
||||
$address,
|
||||
$api,
|
||||
$site = null
|
||||
);
|
||||
|
||||
$arParams['customerCorporate'] = $userCorp['customerCorporate'];
|
||||
|
||||
if (!empty($orderCompany)) {
|
||||
$arParams['orderCompany'] = $orderCompany;
|
||||
}
|
||||
}
|
||||
|
||||
$arParams['contactExId'] = $userCrm['customer']['externalId'];
|
||||
} else {
|
||||
//user
|
||||
$userCrm = RCrmActions::apiMethod($api, 'customersGet', __METHOD__, $arOrder['USER_ID'], $site);
|
||||
if (!isset($userCrm['customer'])) {
|
||||
try {
|
||||
$arUser = UserTable::getById($arOrder['USER_ID'])->fetch();
|
||||
} catch (ObjectPropertyException | ArgumentException | SystemException $exception) {
|
||||
AddMessage2Log($exception->getMessage());
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$resultUser = RetailCrmUser::customerSend($arUser, $api, $optionsContragentType[$arOrder['PERSON_TYPE_ID']], true, $site);
|
||||
|
||||
if (!$resultUser) {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmUser::customerSend', 'error during creating customer');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//order
|
||||
try {
|
||||
$resultOrder = RetailCrmOrder::orderSend($arOrder, $api, $arParams, true, $site, $methodApi);
|
||||
|
||||
if (!$resultOrder) {
|
||||
RCrmActions::eventLog('RetailCrmEvent::orderSave', 'RetailCrmOrder::orderSend', 'error during creating order');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (ObjectPropertyException | ArgumentException | SystemException $exception) {
|
||||
AddMessage2Log($exception->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1474,9 +1474,9 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
|
|||
?>
|
||||
<h4>Редактирование соглашений</h4>
|
||||
<?php if (isset($isAgreementLoyaltyProgram['ID']) && isset($isAgreementLoyaltyProgram['ID'])) { ?>
|
||||
<a href="<?= SITE_SERVER_NAME . '/bitrix/admin/agreement_edit.php?ID=' . $isAgreementLoyaltyProgram['ID']?>">Редактирование "Соглашения на обработку персональных данных"</a>
|
||||
<a href="<?= SITE_SERVER_NAME . '/bitrix/admin/agreement_edit.php?ID=' . $isAgreementLoyaltyProgram['ID']?>">Соглашение на обработку персональных данных</a>
|
||||
<br>
|
||||
<a href="<?= SITE_SERVER_NAME . '/bitrix/admin/agreement_edit.php?ID=' . $isAgreementLoyaltyProgram['ID']?>">Ссылка на Согласие с условиями программы лояльности</a>
|
||||
<a href="<?= SITE_SERVER_NAME . '/bitrix/admin/agreement_edit.php?ID=' . $isAgreementLoyaltyProgram['ID']?>">Согласие с условиями программы лояльности</a>
|
||||
<?php } ?>
|
||||
</td>
|
||||
</tr>
|
||||
|
|
Loading…
Add table
Reference in a new issue