From 3267e72b7c07acb738e9f3a0676fb0b9fab790cc Mon Sep 17 00:00:00 2001 From: Kocmonavtik <61938582+Kocmonavtik@users.noreply.github.com> Date: Mon, 16 Jan 2023 11:05:29 +0300 Subject: [PATCH] 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 --- CHANGELOG.md | 3 ++ .../general/history/RetailCrmHistory_v5.php | 13 +++++ intaro.retailcrm/description.ru | 2 +- intaro.retailcrm/install/version.php | 4 +- .../lib/component/handlers/eventshandlers.php | 46 +++++------------ .../lib/service/orderloyaltydataservice.php | 51 ++----------------- intaro.retailcrm/options.php | 17 ------- 7 files changed, 36 insertions(+), 100 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88b5fcc8..569e232d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2023-01-10 v.6.1.13 +- Изменение метода обновления полей программы лояльности в административной панели + ## 2022-12-28 v.6.1.12 - Исправление генерации пароля у корпоративного клиента - Добавлена проверка на существование пользователя в заказе diff --git a/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php b/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php index f6eedf27..5ff4aabe 100644 --- a/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php +++ b/intaro.retailcrm/classes/general/history/RetailCrmHistory_v5.php @@ -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)) { diff --git a/intaro.retailcrm/description.ru b/intaro.retailcrm/description.ru index 3288be52..b970d9a6 100644 --- a/intaro.retailcrm/description.ru +++ b/intaro.retailcrm/description.ru @@ -1 +1 @@ -- Исправление генерации пароля у корпоративного клиента, проверка существования пользователя в заказе \ No newline at end of file +- Изменение логики обновления полей программы лояльности в административной панели \ No newline at end of file diff --git a/intaro.retailcrm/install/version.php b/intaro.retailcrm/install/version.php index 42cf9aaf..099de893 100644 --- a/intaro.retailcrm/install/version.php +++ b/intaro.retailcrm/install/version.php @@ -1,6 +1,6 @@ '6.1.12', - 'VERSION_DATE' => '2022-12-28 17:30:00' + 'VERSION' => '6.1.13', + 'VERSION_DATE' => '2023-01-10 17:00:00' ]; diff --git a/intaro.retailcrm/lib/component/handlers/eventshandlers.php b/intaro.retailcrm/lib/component/handlers/eventshandlers.php index d99ec5b5..1d306671 100644 --- a/intaro.retailcrm/lib/component/handlers/eventshandlers.php +++ b/intaro.retailcrm/lib/component/handlers/eventshandlers.php @@ -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; } diff --git a/intaro.retailcrm/lib/service/orderloyaltydataservice.php b/intaro.retailcrm/lib/service/orderloyaltydataservice.php index 1d3bee45..898b9846 100644 --- a/intaro.retailcrm/lib/service/orderloyaltydataservice.php +++ b/intaro.retailcrm/lib/service/orderloyaltydataservice.php @@ -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 * diff --git a/intaro.retailcrm/options.php b/intaro.retailcrm/options.php index 555daad6..3c3364a0 100644 --- a/intaro.retailcrm/options.php +++ b/intaro.retailcrm/options.php @@ -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'); }