]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
добавил контроллер для вывода фида
authorJoySystem_v <fvv2011@gmail.com>
Mon, 26 Aug 2024 08:17:29 +0000 (11:17 +0300)
committerJoySystem_v <fvv2011@gmail.com>
Mon, 26 Aug 2024 08:17:29 +0000 (11:17 +0300)
erp24/controllers/MarketplaceController.php [new file with mode: 0644]
erp24/services/MarketplaceService.php [new file with mode: 0644]
erp24/views/marketplace/feed.php [new file with mode: 0644]

diff --git a/erp24/controllers/MarketplaceController.php b/erp24/controllers/MarketplaceController.php
new file mode 100644 (file)
index 0000000..b217b95
--- /dev/null
@@ -0,0 +1,30 @@
+<?php
+
+namespace app\controllers;
+use Yii;
+use yii\web\Controller;
+use yii_app\services\MarketplaceService;
+use yii\web\Response;
+
+class MarketplaceController extends Controller
+{
+    /**
+     * Экшен для генерации и отображения XML-фида.
+     *
+     * @return string
+     */
+    public function actionFeed()
+    {
+        // Получаем информацию о продуктах
+        $productsInfo = MarketplaceService::getAllProductsInfo();
+
+        // Генерируем XML-фид
+        $xmlFeed = MarketplaceService::createXMLFeed($productsInfo);
+
+        // Устанавливаем заголовок, чтобы отдать XML
+        Yii::$app->response->format = Response::FORMAT_RAW;
+        Yii::$app->response->headers->add('Content-Type', 'application/xml; charset=utf-8');
+
+        return $xmlFeed;
+    }
+}
\ No newline at end of file
diff --git a/erp24/services/MarketplaceService.php b/erp24/services/MarketplaceService.php
new file mode 100644 (file)
index 0000000..f9adf09
--- /dev/null
@@ -0,0 +1,151 @@
+<?php
+
+namespace yii_app\services;
+
+use yii_app\records\Prices;
+use yii_app\records\Products1c;
+
+class MarketplaceService
+{
+    /**
+     * Статический метод для получения всей информации по продуктам, которая необходима для создания фида.
+     *
+     * @return array
+     */
+    public static function getAllProductsInfo()
+    {
+        $products = Products1c::find()
+            ->where(['tip' => 'products'])
+            ->andWhere(['not', ['components' => '']])
+            ->all();
+
+        $result = [];
+
+        foreach ($products as $product) {
+            $components = json_decode($product->components, true);
+            $composition = [];
+
+            foreach ($components as $componentId => $quantity) {
+                $component = Products1c::findOne(['id' => $componentId]);
+                if ($component && $quantity > 0) {
+                    $composition[] = [
+                        'name' => $component->name,
+                        'quantity' => $quantity,
+                        'unit' => 'шт'
+                    ];
+                }
+            }
+
+            $result[] = [
+                'id' => $product->id,
+                'name' => $product->name,
+                'picture' => self::getProductPictureUrl($product->id),
+                'price' => self::getProductPrice($product->id),
+                'oldprice' => self::getProductOldPrice($product->id),
+                'description' => self::getProductDescription($product->id),
+                'qty' => self::getProductQty($product->id),
+                'weight' => self::getProductWeight($product->id),
+                'minorder' => self::getProductMinOrder($product->id),
+                'composition' => $composition,
+                'available' => self::getProductAvailability($product->id)
+            ];
+        }
+
+        return $result;
+    }
+
+    /**
+     * Статический метод для создания XML-фида на основе информации о продуктах.
+     *
+     * @param array $productsInfo
+     * @return string
+     */
+    public static function createXMLFeed($productsInfo)
+    {
+        $xml = new \SimpleXMLElement('<yml_catalog/>');
+        $xml->addAttribute('date', date('Y-m-d\TH:i:sP'));
+
+        $shop = $xml->addChild('shop');
+        $shop->addChild('name', 'BestSeller');
+        $shop->addChild('company', 'The Best inc.');
+        $shop->addChild('url', 'http://best.seller.ru');
+
+        // Добавление валюты
+        $currencies = $shop->addChild('currencies');
+        $currency = $currencies->addChild('currency');
+        $currency->addAttribute('id', 'RUR');
+        $currency->addAttribute('rate', '1');
+
+        // Добавление категорий
+        $categories = $shop->addChild('categories');
+        $category = $categories->addChild('category', 'Букеты');
+        $category->addAttribute('id', '1');
+
+        // Добавление информации о доставке
+        $deliveryOptions = $shop->addChild('delivery-options');
+        $deliveryOption = $deliveryOptions->addChild('option');
+        $deliveryOption->addAttribute('cost', '200');
+        $deliveryOption->addAttribute('days', '1');
+
+        // Добавление офферов (продуктов)
+        $offers = $shop->addChild('offers');
+        foreach ($productsInfo as $product) {
+            $offer = $offers->addChild('offer');
+            $offer->addAttribute('id', $product['id']);
+            $offer->addChild('name', htmlspecialchars($product['name']));
+            $offer->addChild('url', 'http://best.seller.ru/product_page.asp?pid=' . $product['id']);
+            $offer->addChild('price', $product['price']);
+            $offer->addChild('currencyId', 'RUR');
+            $offer->addChild('categoryId', '1');
+            $offer->addChild('delivery', 'true');
+
+            // Информация о доставке для каждого оффера
+            $offerDeliveryOptions = $offer->addChild('delivery-options');
+            $offerDeliveryOption = $offerDeliveryOptions->addChild('option');
+            $offerDeliveryOption->addAttribute('cost', '300');
+            $offerDeliveryOption->addAttribute('days', '1');
+            $offerDeliveryOption->addAttribute('order-before', '18');
+
+            $offer->addChild('description', htmlspecialchars($product['description']));
+            $offer->addChild('weight', $product['weight']);
+            $offer->addChild('qty', $product['qty']);
+            $offer->addChild('minorder', $product['minorder']);
+            $offer->addChild('available', $product['available'] ? 'true' : 'false');
+
+            if ($product['oldprice']) {
+                $offer->addChild('oldprice', $product['oldprice']);
+            }
+
+            foreach ($product['composition'] as $component) {
+                $consist = $offer->addChild('param', $component['quantity']);
+                $consist->addAttribute('name', htmlspecialchars($component['name']));
+                $consist->addAttribute('unit', $component['unit']);
+            }
+        }
+
+        return $xml->asXML();
+    }
+
+    // Приватные статические вспомогательные методы
+    private static function getProductPictureUrl($productId) {
+        return 'https://files.erp24.ru/pic.jpg';
+    }
+    private static function getProductPrice($productId) {
+        $price = Prices::find()
+            ->where(['product_id' => $productId])
+            ->one();
+            return $price['price'] ?? 0;
+    }
+    private static function getProductOldPrice($productId) { return null; }
+    private static function getProductDescription($productId) { return 'Описание'; }
+    private static function getProductQty($productId) { return 100; }
+    private static function getProductWeight($productId) {
+        return null;
+    }
+    private static function getProductMinOrder($productId) {
+        return 1;
+    }
+    private static function getProductAvailability($productId) {
+        return true;
+    }
+}
diff --git a/erp24/views/marketplace/feed.php b/erp24/views/marketplace/feed.php
new file mode 100644 (file)
index 0000000..1c5f0de
--- /dev/null
@@ -0,0 +1,4 @@
+<?php
+
+/** @var $xmlFeed string */
+print_r($xmlFeed);
\ No newline at end of file