Advertisement
AlexeyGfi

Обновление цены при реакции на обновление цены

Aug 24th, 2022 (edited)
1,213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 3.73 KB | None | 0 0
  1. <?php
  2.  
  3. namespace AlexeyGfi;
  4.  
  5. use Bitrix\Catalog\Model\Event;
  6. use Bitrix\Catalog\Model\Price;
  7. use Bitrix\Catalog\PriceTable;
  8. use Bitrix\Main\EventManager;
  9. use Bitrix\Main\ORM\Query\Query;
  10.  
  11. class SquareMettersPrices
  12. {
  13.     protected static $eventDeployed = false;
  14.     protected static $eventOrder = [];
  15.  
  16.     public static function onPriceEvent(Event $event): void
  17.     {
  18.         // Проверяем и решаем — нужно ли внести изменения в цену
  19.         // ...
  20.  
  21.         // Решаем, что нужно.
  22.         // Накапливаем набор для действий
  23.         self::pushToEvent($productId, $squarePriceGroupId, $squarePrice);
  24.  
  25.     }
  26.  
  27.     protected static function pushToEvent($productId, $squarePriceGroupId, $squarePrice)
  28.     {
  29.         $pushEvent = false;
  30.  
  31.         /**
  32.          * Читаем у целевого товара цену целевого типа
  33.          * Если есть и отличается от того, что мы собираемся записать, - обновляем
  34.          * Если нет - добавляем
  35.          */
  36.         $priceEntity = PriceTable::getEntity();
  37.         $res = (new Query($priceEntity))
  38.             ->where('PRODUCT_ID', $productId)
  39.             ->where('CATALOG_GROUP_ID', $squarePriceGroupId)
  40.             ->setSelect(['ID', 'PRICE'])
  41.             ->setLimit(1)
  42.             ->exec();
  43.  
  44.         if ($elArr = $res->fetch()) {
  45.             // Если цена уже есть в таблице b_catalog_price
  46.             $priceValue = $elArr['PRICE'];
  47.             if ($priceValue != $squarePrice) {
  48.                 self::$eventOrder['UPDATE'] = self::$eventOrder['UPDATE'] ?? [];
  49.                 self::$eventOrder['UPDATE'][] = [
  50.                     'ID' => $elArr['ID'],
  51.                     'PRICE' => $squarePrice,
  52.                     'PRICE_SCALE' => $squarePrice,
  53.                 ];
  54.  
  55.                 $pushEvent = true;
  56.             }
  57.  
  58.         } else {
  59.             // Если нет
  60.             self::$eventOrder['ADD'] = self::$eventOrder['ADD'] ?? [];
  61.             self::$eventOrder['ADD'][$elArr['ID']] = [
  62.                 'PRODUCT_ID' => $productId,
  63.                 'CATALOG_GROUP_ID' => $squarePriceGroupId,
  64.                 'CURRENCY' => 'RUB',
  65.                 'PRICE' => $squarePrice,
  66.             ];
  67.  
  68.             $pushEvent = true;
  69.  
  70.         }
  71.  
  72.         if ($pushEvent && !self::$eventDeployed) {
  73.             self::$eventDeployed = true;
  74.  
  75.             // Прямо по ходу дела подписываемся на событие,
  76.             // когда БД будет разлочена от текущей операции с ценой
  77.             $eventManager = EventManager::getInstance();
  78.             $eventManager->addEventHandler(
  79.                 'main',
  80.                 'OnBeforeEndBufferContent',
  81.                 [__CLASS__, 'processPricesOrders']
  82.             );
  83.         }
  84.     }
  85.  
  86.     public static function processPricesOrders()
  87.     {
  88.         foreach (self::$eventOrder as $type => $orderList) {
  89.             foreach ($orderList as $orderFields) {
  90.                 if ($type === 'UPDATE') {
  91.                     $recordId = $orderFields['ID'];
  92.                     unset($orderFields['ID']);
  93.  
  94.                     $updateResult = Price::update($recordId, $orderFields);
  95.                     if (!$updateResult->isSuccess()) {
  96.                         // Процессинг ошибки
  97.                     }
  98.  
  99.                 } else {
  100.                     $addResult = Price::add($orderFields);
  101.                     if (!$addResult->isSuccess()) {
  102.                         // Процессинг ошибки
  103.                     }
  104.  
  105.                 }
  106.             }
  107.         }
  108.     }
  109.  
  110. }
Tags: bitrix
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement