403Webshell
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/rospirotorg.ru/bitrix/modules/wbs24.exchange1c/lib/

Upload File :
current_dir [ Writeable] document_root [ Writeable]

 

Command :


[ Back ]     

Current File : /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/wbs24.exchange1c/lib/Yamarket.php
<?php
namespace Wbs24\Exchange1c;

/**
 * Класс для работы с Y.market по API
 */
class Yamarket
{
    public function __construct($objects = [])
    {
        $this->Db = $objects['Db'] ?? new Db($objects);
        $this->Curl = $objects['Curl'] ?? new Curl($objects);
    }

    public function fixOrders($orders)
    {
        foreach ($orders as $k => $order) {
            $xmlId = $order['xmlId'] ?? false;

            if ($this->isYmOrder($xmlId)) {
                $ymProfileId = $this->getYmProfileIdByXmlId($xmlId);
                $ymOrderId = $this->getYmOrderIdByXmlId($xmlId);
                $settings = $this->getYmSettings($ymProfileId);
                $campaignId = $settings['CAMPAIGN_ID'] ?? '';
                //$tokenId = $settings['OAUTH_TOKEN'] ?? '';
                $apiKey = $settings['API_KEY'] ?? '';
                //$bearerToken = $this->getBearerToken($tokenId);

                $ymOrderInfo = $this->getYmOrderInfo([
                    'ymOrderId' => $ymOrderId,
                    'campaignId' => $campaignId,
                    //'bearerToken' => $bearerToken,
                    'apiKey' => $apiKey,
                ]);

                if (isset($ymOrderInfo['order'])) {
                    $orders[$k] = $this->fixOrderProducts($order, $ymOrderInfo);
                } else {
                    unset($orders[$k]);
                }
            }
        }

        return $orders;
    }

    protected function isYmOrder($orderXmlId)
    {
        return strpos($orderXmlId, 'YAMARKET') === 0;
    }

    protected function getYmProfileIdByXmlId($orderXmlId)
    {
        $xmlIdParts = explode('_', $orderXmlId);
        $ymProfileId = $xmlIdParts[3] ?? false;

        return $ymProfileId;
    }

    protected function getYmOrderIdByXmlId($orderXmlId)
    {
        $xmlIdParts = explode('_', $orderXmlId);
        $ymOrderId = $xmlIdParts[2] ?? false;

        return $ymOrderId;
    }

    protected function getYmSettings($ymProfileId)
    {
        $settings = $this->Db->get(
            'yamarket_trading_settings',
            [
                'SETUP_ID' => $ymProfileId,
            ]
        );
        $settingsAssoc = [];
        foreach ($settings as $item) {
            $name = $item['NAME'] ?? false;
            $value = $item['VALUE'] ?? '';
            if (!$name) continue;

            $settingsAssoc[$name] = $value;
        }

        return $settingsAssoc;
    }

    // не используется
    /* protected function getBearerToken($tokenId)
    {
        if (!$tokenId) return '';

        $result = $this->Db->getSingle(
            'yamarket_api_oauth2_token',
            [
                'ID' => $tokenId,
                'TOKEN_TYPE' => 'bearer',
            ]
        );
        $token = $result['ACCESS_TOKEN'] ?? '';

        return $token;
    } */

    // ChatGPT 4o - min fix
    protected function getYmOrderInfo(array $params)
    {
        // Проверяем наличие необходимых параметров
        if (empty($params['campaignId']) || empty($params['ymOrderId']) || empty($params['apiKey'])) {
            return [];
        }

        // Формируем URL
        $url = sprintf(
            'https://api.partner.market.yandex.ru/campaigns/%s/orders/%s',
            $params['campaignId'],
            $params['ymOrderId']
        );

        // Устанавливаем заголовки
        $headers = [
            'Api-Key: ' . $params['apiKey']
        ];

        // Параметры запроса
        $curlParams = [
            'headers' => $headers,
            'post' => false, // GET-запрос
            'saveLog' => true,
        ];

        $json = $this->Curl->request($url, $curlParams);

        // Выполняем запрос
        return json_decode($json, true);
    }

    // ChatGPT 4o - as is
    // UPD - logic has changed 30.08.24
    protected function fixOrderProducts(array $order, array $ymOrderInfo)
    {
        // Проверка наличия продуктов в заказе и информации о продуктах из Yamarket
        if (isset($order['products']) && is_array($order['products']) && isset($ymOrderInfo['order']['items']) && is_array($ymOrderInfo['order']['items'])) {
            // Обновление товаров в заказе
            foreach ($order['products'] as &$product) {
                if (!isset($product['productId'])) {
                    continue; // Пропускаем товары без идентификатора продукта
                }

                foreach ($ymOrderInfo['order']['items'] as $ymItem) {
                    if (isset($ymItem['offerId']) && $product['productId'] == $ymItem['offerId']) {
                        if (isset($ymItem['priceBeforeDiscount']) && isset($ymItem['count'])) {
                            $realItemPriceWoDiscount = (int)$ymItem['buyerPrice'] + (int)$ymItem['subsidy'];
                            $product['salePrice'] = $realItemPriceWoDiscount;
                            $product['salePriceSum'] = $realItemPriceWoDiscount * (int)$ymItem['count'];
                        }

                        if (isset($ymItem['count'])) {
                            $product['stocks']['quantity'] = $ymItem['count'];
                        }
                    }
                }
            }
        }

        // добавить или заменить доставку
        $keyDeliveryProduct = $this->getDeliveryProductKeyFromProducts($order['products']);
        $deliveryPrice = $this->getDeliveryPriceFromYmOrder($ymOrderInfo);
        if ($keyDeliveryProduct) {
            $order['products'][$keyDeliveryProduct]['salePrice'] = $deliveryPrice;
            $order['products'][$keyDeliveryProduct]['salePriceSum'] = $deliveryPrice;
        } else {
            $order['products'][] = [
                'productId' => NULL,
                'sku' => 'DELIVERY',
                'salePrice' => $deliveryPrice,
                'stocks' => ['quantity' => 1],
                'salePriceSum' => $deliveryPrice,
            ];
        }

        // Обновление суммы заказа
        $subsidyPrice = $this->getSubsidyPriceFromYmOrder($ymOrderInfo);
        $order['orderSum'] = (int)$ymOrderInfo['order']['buyerItemsTotal'] + $deliveryPrice + $subsidyPrice;

        return $order;
    }

    protected function getDeliveryProductKeyFromProducts($products)
    {
        $key = 0;
        foreach ($products as $k => $product) {
            if ($product['sku'] == 'DELIVERY') {
                $key = $k;
                break;
            }
        }

        return $key;
    }

    // ChatGPT 4o - as is
    protected function getDeliveryPriceFromYmOrder($ymOrderInfo)
    {
        // Извлекаем значение deliveryTotal
        $deliveryTotal = (int)$ymOrderInfo['order']['deliveryTotal'];

        // Ищем в подмассиве subsidies элемент с type = DELIVERY и добавляем его amount
        foreach ($ymOrderInfo['order']['subsidies'] as $subsidy) {
            if ($subsidy['type'] === 'DELIVERY') {
                $deliveryTotal += (int)$subsidy['amount'];
            }
        }

        return $deliveryTotal;
    }

    protected function getSubsidyPriceFromYmOrder($ymOrderInfo)
    {
        $subsidyPrice = 0;
        // Ищем в подмассиве subsidies элемент с type = SUBSIDY и добавляем его amount
        foreach ($ymOrderInfo['order']['subsidies'] as $subsidy) {
            if ($subsidy['type'] === 'SUBSIDY') {
                $subsidyPrice += (int)$subsidy['amount'];
            }
        }

        return $subsidyPrice;
    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit