Server IP : 80.87.202.40 / Your IP : 216.73.216.169 Web Server : Apache System : Linux rospirotorg.ru 5.14.0-539.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Dec 5 22:26:13 UTC 2024 x86_64 User : bitrix ( 600) PHP Version : 8.2.27 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /home/bitrix/ext_www/cvetdv.ru/bitrix/modules/wbs24.ozonapinew/lib/Prices/ |
Upload File : |
<?php namespace Wbs24\Ozonapinew\Prices; use Bitrix\Main\SystemException; use Bitrix\Main\Localization\Loc; use Wbs24\Ozonapinew\Main; use Wbs24\Ozonapinew\Wrappers; use Wbs24\Ozonapinew\Api; use Wbs24\Ozonapinew\Product; use Wbs24\Ozonapinew\Exception; use Wbs24\Ozonapinew\Products\Cache; use Wbs24\Ozonapinew\Error; use Wbs24\Ozonapinew\Settings; use Wbs24\Ozonapinew\StorageMessages; class Update { use Exception; // trait protected $entityType = 'prices'; protected $forbiddenEntityTypes = [ 'nothing', 'stocks' ]; public function __construct($objects = []) { try { $this->main = $objects['Main'] ?? new Main(); $this->moduleId = $this->main->getModuleId(); $this->wrappers = new Wrappers($objects); $this->accountIndex = $this->wrappers->Option->getAccountIndex(); $this->ApiController = $objects['ApiController'] ?? new Api\Controller(); $this->PricesHelper = $objects['PricesHelper'] ?? new Helper($objects); $this->Product = $objects['Product'] ?? new Product($objects); $this->CacheStack = $objects['CacheStack'] ?? new Cache\Stack(); $this->Error = $objects['Error'] ?? new Error(); $this->Settings = $objects['Settings'] ?? new Settings(); $this->StorageMessages = $objects['StorageMessages'] ?? new StorageMessages(); } catch (SystemException $exception) { $this->exceptionHandler($exception); } } public function updatePricesOnMarketplace($lastId) { // Получить информацию о ценах с ОЗОНа $response = $this->ApiController->action([ 'action' => 'get_prices', 'lastId' => $lastId, 'account_index' => $this->accountIndex, ]); $offerIdsToPrices = $response['offerIdsToPrices']; $newLastId = $response['newLastId']; if ($offerIdsToPrices) { // Получить информацию о ценах с Битрикса и сравнить с ценой маркетплейса $preparedOfferIdsToPrices = $this->prepareOfferIdsToPrices($offerIdsToPrices); if ($preparedOfferIdsToPrices) { // Обновить цены на ОЗОНе $updateProducts = $this->ApiController->action([ 'action' => 'update_prices', 'offerIdsToPrices' => $preparedOfferIdsToPrices, 'account_index' => $this->accountIndex, ]); if ($updateProducts) { // Проверить успешность обновлений цен и записать лог ошибок $this->checkPriceUpdatesSuccess($updateProducts); } } } return $newLastId; } protected function prepareOfferIdsToPrices($offerIdsToPrices) { $preparedOfferIdsToPrices = []; foreach ($offerIdsToPrices as $offerId => $prices) { $productInfo = $this->getProductInfo($offerId); $productId = $productInfo['product_id'] ?? false; $ratio = $productInfo['package_ratio'] ?? 1; if (!$productId || !$ratio) continue; $newPrices = $this->PricesHelper->getPricesByProductId($productId, $productInfo); $newOzonPrice = $newPrices['price']; $newOldOzonPrice = $newPrices['oldPrice']; $newMinOzonPrice = $newPrices['minPrice']; $newOzonPriceWithRatio = round($newOzonPrice) * $ratio; // цена с учетом коэффициента упаковки if ($newOzonPriceWithRatio <= 0) continue; // Не обновлять цены, если они вдруг равны нулю $newOzonOldPriceWithRatio = round($newOldOzonPrice) * $ratio; // цена с учетом коэффициента упаковки $newOzonMinPriceWithRatio = round($newMinOzonPrice) * $ratio; // цена с учетом коэффициента упаковки $ozonPrice = $prices['price']; $ozonOldPrice = $prices['old_price']; $ozonMinPrice = $prices['min_price']; if ( $newOzonPriceWithRatio == $ozonPrice && $newOzonOldPriceWithRatio == $ozonOldPrice && $newOzonMinPriceWithRatio == $ozonMinPrice ) continue; $preparedOfferIdsToPrices[$offerId]['price'] = $newOzonPriceWithRatio; $preparedOfferIdsToPrices[$offerId]['old_price'] = $newOzonOldPriceWithRatio; $preparedOfferIdsToPrices[$offerId]['min_price'] = $newOzonMinPriceWithRatio; } return $preparedOfferIdsToPrices; } protected function getProductInfo($offerId) { $productInfo = []; $iblocks = $this->CacheStack->getAllIblocks([ 'accountIndex' => $this->accountIndex, 'entityType' => $this->entityType ]); foreach ($iblocks as $iblockId) { $allowedEntityType = $this->wrappers->Option->get($this->moduleId, 'entity_type_iblock_'.$iblockId); if (in_array($allowedEntityType, $this->forbiddenEntityTypes)) continue; $productInfo = $this->CacheStack->searchProduct([ 'iblockId' => $iblockId, 'offerId' => $offerId, 'accountIndex' => $this->accountIndex, 'entityType' => $this->entityType ]); if ($productInfo) break; } return $productInfo; } protected function checkPriceUpdatesSuccess($updatedProducts) { $errorProductsUpdates = []; foreach ($updatedProducts as $updatedProduct) { if (!empty($updatedProduct['errors']) ) { $errorProductsUpdates[] = $updatedProduct; } } $suffix = strtoupper($this->moduleId); $siteId = $this->wrappers->Option->get($this->moduleId, 'siteId'); $siteInfo = $this->Settings->getSiteInfo($siteId); $offerIds = $this->getErrorOfferIds($errorProductsUpdates); $offerIdsToDetailPageUrl = $this->getOfferIdsToDetailPageUrl($offerIds, $siteInfo); foreach ($errorProductsUpdates as $errorProductUpdate) { $offerId = $errorProductUpdate['offer_id']; $errorMessage .= $this->getErrorMessage($errorProductUpdate['errors']); $this->createReport( 'prices_update_error_log.txt', $errorMessage ); $errorCodesToMessages = $this->getErrorCodesToMessages($errorProductUpdate['errors']); $prepareCodesToMessages = $this->StorageMessages->prepareCodesToMessages($errorCodesToMessages); foreach ($prepareCodesToMessages as $code => $message) { $this->Error->errorProcess([ 'siteName' => $siteInfo['siteNameHtml'], 'dateTime' => date("Y-m-d H:i:s", time()), 'errorLevel' => 'WARNING', 'errorType' => 'API', 'errorCode' => $code, 'errorMessage' => $errorMessage, 'errorDescription' => $message, 'accountId' => $this->accountIndex, 'apiUrl' => '/v1/product/import/prices', 'entityId' => '<a href="'.$offerIdsToDetailPageUrl[$offerId].'">'.$offerId.'</a>', 'entityType' => 'products', 'requestBody' => '', 'responseBody' => '', 'trace' => '', ]); } } } protected function getErrorOfferIds($errorProductsUpdates) { $offerIds = []; foreach ($errorProductsUpdates as $errorProductUpdate) { $offerIds[] = $errorProductUpdate['offer_id']; } return $offerIds; } protected function getOfferIdsToDetailPageUrl($offerIds, $siteInfo) { $offerIdsToDetailPageUrl = []; foreach ($offerIds as $offerId) { $product = $this->Product->getProductInfoByOfferId($offerId); switch ((int) $product['product_type']) { case 1: case 2: case 3: $type = 'catalog'; break; case 4: $type = 'offers'; break; } $offerIdsToDetailPageUrl[$offerId] = 'http://'.$siteInfo['serverName'].'/bitrix/admin/iblock_element_edit.php?IBLOCK_ID='.$product['iblock_id'].'&type='.$type.'&lang=ru&ID='.$product['id'].'&find_section_section=-1&WF=Y'; } return $offerIdsToDetailPageUrl; } protected function getErrorMessage($errors) { $suffix = strtoupper($this->moduleId); $errorsMessage = ''; foreach ($errors as $key => $error) { $errorsMessage .= Loc::getMessage($suffix.".PRICE_UPDATE_MESSAGE_CODE") .$error['code'] .Loc::getMessage($suffix.".PRICE_UPDATE_MESSAGE_STRING") .$error['message'] ; if (!empty($errors[$key+1])) { $errorsMessage .= ', '; } } return $errorsMessage; } protected function getErrorCodesToMessages($errors) { $errorCodes = []; foreach ($errors as $key => $error) { $errorCodes[$error['code']] = $error['message']; } return $errorCodes; } }