Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace AlexeyGfi;
- use Bitrix\Catalog\Model\Event;
- use Bitrix\Catalog\Model\Price;
- use Bitrix\Catalog\PriceTable;
- use Bitrix\Main\EventManager;
- use Bitrix\Main\ORM\Query\Query;
- class SquareMettersPrices
- {
- protected static $eventDeployed = false;
- protected static $eventOrder = [];
- public static function onPriceEvent(Event $event): void
- {
- // Проверяем и решаем — нужно ли внести изменения в цену
- // ...
- // Решаем, что нужно.
- // Накапливаем набор для действий
- self::pushToEvent($productId, $squarePriceGroupId, $squarePrice);
- }
- protected static function pushToEvent($productId, $squarePriceGroupId, $squarePrice)
- {
- $pushEvent = false;
- /**
- * Читаем у целевого товара цену целевого типа
- * Если есть и отличается от того, что мы собираемся записать, - обновляем
- * Если нет - добавляем
- */
- $priceEntity = PriceTable::getEntity();
- $res = (new Query($priceEntity))
- ->where('PRODUCT_ID', $productId)
- ->where('CATALOG_GROUP_ID', $squarePriceGroupId)
- ->setSelect(['ID', 'PRICE'])
- ->setLimit(1)
- ->exec();
- if ($elArr = $res->fetch()) {
- // Если цена уже есть в таблице b_catalog_price
- $priceValue = $elArr['PRICE'];
- if ($priceValue != $squarePrice) {
- self::$eventOrder['UPDATE'] = self::$eventOrder['UPDATE'] ?? [];
- self::$eventOrder['UPDATE'][] = [
- 'ID' => $elArr['ID'],
- 'PRICE' => $squarePrice,
- 'PRICE_SCALE' => $squarePrice,
- ];
- $pushEvent = true;
- }
- } else {
- // Если нет
- self::$eventOrder['ADD'] = self::$eventOrder['ADD'] ?? [];
- self::$eventOrder['ADD'][$elArr['ID']] = [
- 'PRODUCT_ID' => $productId,
- 'CATALOG_GROUP_ID' => $squarePriceGroupId,
- 'CURRENCY' => 'RUB',
- 'PRICE' => $squarePrice,
- ];
- $pushEvent = true;
- }
- if ($pushEvent && !self::$eventDeployed) {
- self::$eventDeployed = true;
- // Прямо по ходу дела подписываемся на событие,
- // когда БД будет разлочена от текущей операции с ценой
- $eventManager = EventManager::getInstance();
- $eventManager->addEventHandler(
- 'main',
- 'OnBeforeEndBufferContent',
- [__CLASS__, 'processPricesOrders']
- );
- }
- }
- public static function processPricesOrders()
- {
- foreach (self::$eventOrder as $type => $orderList) {
- foreach ($orderList as $orderFields) {
- if ($type === 'UPDATE') {
- $recordId = $orderFields['ID'];
- unset($orderFields['ID']);
- $updateResult = Price::update($recordId, $orderFields);
- if (!$updateResult->isSuccess()) {
- // Процессинг ошибки
- }
- } else {
- $addResult = Price::add($orderFields);
- if (!$addResult->isSuccess()) {
- // Процессинг ошибки
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement