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

ref #74694 Changing loyalty program update in admin panel

* Removing unnecessary elements, fixing a broken method, adding code to OrderHistory
* Changing the verification to update the properties of the loyalty program order
This commit is contained in:
Kocmonavtik 2023-01-16 11:05:29 +03:00 committed by GitHub
parent be5d7ba33e
commit 3267e72b7c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 36 additions and 100 deletions

View File

@ -1,3 +1,6 @@
## 2023-01-10 v.6.1.13
- Изменение метода обновления полей программы лояльности в административной панели
## 2022-12-28 v.6.1.12
- Исправление генерации пароля у корпоративного клиента
- Добавлена проверка на существование пользователя в заказе

View File

@ -939,6 +939,7 @@ class RetailCrmHistory
$editBasketInfo = [];
$deleteBasketInfo = [];
$bonusesChargeTotal = null;
$loyaltyDiscount = null;
if (isset($order['items'])) {
$itemUpdate = true;
@ -1083,12 +1084,17 @@ class RetailCrmHistory
}
$manualProductDiscount = 0;
$bonusesChargeProduct = $product['bonusesCharge'] ?? null;
foreach ($product['discounts'] as $productDiscount) {
if ('manual_product' === $productDiscount['type']) {
$manualProductDiscount = $productDiscount['amount'];
}
if ('loyalty_level' === $productDiscount['type']) {
$loyaltyDiscount += $productDiscount['amount'];
}
}
$editBasketInfo[] = [
@ -1202,11 +1208,18 @@ class RetailCrmHistory
}
}
$orderLoyaltyDataService->saveBonusAndDiscToOrderProps(
$newOrder->getPropertyCollection(),
$loyaltyDiscount,
$bonusesChargeTotal
);
$hlInfoBuilder = new LoyaltyDataBuilder();
$hlInfoBuilder->setOrder($newOrder);
$hlInfoBuilder->setCalculateItemsInput($calculateItemsInput);
$hlInfoBuilder->setBonusCountTotal($bonusesChargeTotal);
$orderLoyaltyDataService->saveLoyaltyInfoToHl($hlInfoBuilder->build($basketItemIds)->getResult());
self::orderSave($newOrder);
}
if (!empty($deleteBasketInfo)) {

View File

@ -1 +1 @@
- Исправление генерации пароля у корпоративного клиента, проверка существования пользователя в заказе
- Изменение логики обновления полей программы лояльности в административной панели

View File

@ -1,6 +1,6 @@
<?php
$arModuleVersion = [
'VERSION' => '6.1.12',
'VERSION_DATE' => '2022-12-28 17:30:00'
'VERSION' => '6.1.13',
'VERSION_DATE' => '2023-01-10 17:00:00'
];

View File

@ -120,28 +120,6 @@ class EventsHandlers
}
}
/**
* Обновляет информацию о Программе лояльности в административной панели.
* При каждом открытии заказа делает запрос к CRM и получает актуальную информацию.
*
* @param $items
*/
public function OnAdminContextMenuShowHandler(&$items)
{
global $APPLICATION;
if (
$_SERVER['REQUEST_METHOD'] === 'GET'
&& $_REQUEST['ID'] > 0
&& $APPLICATION->GetCurPage() === '/bitrix/admin/sale_order_view.php'
) {
/* @var OrderLoyaltyDataService $service */
$service = ServiceLocator::get(OrderLoyaltyDataService::class);
$service->updateLoyaltyInfo($_REQUEST['ID']);
}
}
/**
* Обработчик события, вызываемого ПОСЛЕ сохранения заказа (OnSaleOrderSaved)
*
@ -149,11 +127,18 @@ class EventsHandlers
*/
public function OnSaleOrderSavedHandler(Event $event): void
{
if (self::$disableSaleHandler === true) {
return;
}
try {
$isBonusInput = (
!empty($_POST['bonus-input'])
&& !empty($_POST['available-bonuses'])
);
$isDataForLoyaltyDiscount = isset($_POST['calculate-items-input'], $_POST['loyalty-discount-input']);
if (self::$disableSaleHandler === true || !($isDataForLoyaltyDiscount || $isBonusInput) ) {
return;
}
/* @var LoyaltyService $loyaltyService */
$loyaltyService = ServiceLocator::get(LoyaltyService::class);
@ -164,20 +149,13 @@ class EventsHandlers
// TODO: Replace old call with a new one.
$saveResult = RetailCrmEvent::orderSave($order);
Utils::handleApiErrors($saveResult);
$isBonusInput = (
!empty($_POST['bonus-input'])
&& !empty($_POST['available-bonuses'])
);
$bonusFloat = (float) $_POST['bonus-input'];
/** @var bool $isNewOrder */
$isNewOrder = $event->getParameter('IS_NEW');
$isLoyaltyOn = ConfigProvider::getLoyaltyProgramStatus() === 'Y';
$isDataForLoyaltyDiscount = isset($_POST['calculate-items-input'], $_POST['loyalty-discount-input']);
$isBonusesIssetAndAvailable = $isBonusInput && (float) $_POST['available-bonuses'] >= $bonusFloat;
/** @var array $calculateItemsInput */
@ -220,8 +198,10 @@ class EventsHandlers
$discountInput,
$loyaltyBonusMsg
);
$hlInfoBuilder->setCalculateItemsInput($calculateItemsInput);
$orderLoyaltyDataService->saveLoyaltyInfoToHl($hlInfoBuilder->build()->getResult());
$order->save();
self::$disableSaleHandler = false;
}

View File

@ -151,61 +151,18 @@ class OrderLoyaltyDataService
foreach ($props as $prop) {
if ($prop->getField('CODE') === 'LP_DISCOUNT_INFO') {
$this->saveLpInfoToField($prop, $loyaltyDiscountInput);
break;
}
}
foreach ($props as $prop) {
if ($prop->getField('CODE') === 'LP_BONUS_INFO') {
$this->saveLpInfoToField($prop, $loyaltyBonus);
break;
}
}
}
/**
* Обновляет данные о начисленных бонусах и скидках в полях заказа
*
* @param int $orderId
*/
public function updateLoyaltyInfo(int $orderId): void
{
/** @var \Intaro\RetailCrm\Component\ApiClient\ClientAdapter $client */
$client = ClientFactory::createClientAdapter();
$response = $client->getOrder($orderId);
if ($response === null || !is_array($response->order->items)) {
return;
}
try {
$order = Order::load($orderId);
if ($order === null) {
return;
}
$loyaltyDiscount = 0;
/** @var OrderProduct $item */
foreach ($response->order->items as $item) {
foreach ($item->discounts as $discount) {
if (in_array($discount->type, ['personal', 'loyalty_level'])) {
$loyaltyDiscount += $discount->amount;
}
}
}
$this->saveBonusAndDiscToOrderProps(
$order->getPropertyCollection(),
$loyaltyDiscount ?? 0.0,
$response->order->bonusesChargeTotal
);
EventsHandlers::$disableSaleHandler = true;
$order->save();
EventsHandlers::$disableSaleHandler = false;
} catch (Exception $exception) {
$this->logger->write($exception->getMessage(), Constants::LOYALTY_ERROR);
}
}
/**
* @param int $orderId
*

View File

@ -597,23 +597,6 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) {
}
ConfigProvider::setLoyaltyProgramStatus('Y');
$eventManager = EventManager::getInstance();
$eventManager->unRegisterEventHandler('sale',
'OnSaleOrderSaved',
Constants::MODULE_ID,
'RetailCrmEvent',
'orderSave'
);
$eventManager->registerEventHandler(
'main',
'OnAdminContextMenuShow',
Constants::MODULE_ID,
EventsHandlers::class,
'OnAdminContextMenuShowHandler'
);
} else {
ConfigProvider::setLoyaltyProgramStatus('N');
}