]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
[ERP-148] доработка яндекс маркетплейса
authorAlexander Smirnov <fredeom@mail.ru>
Tue, 12 Nov 2024 12:14:00 +0000 (15:14 +0300)
committerAlexander Smirnov <fredeom@mail.ru>
Tue, 12 Nov 2024 12:14:00 +0000 (15:14 +0300)
erp24/api2/controllers/YandexMarketController.php
erp24/commands/MarketplaceController.php [new file with mode: 0644]
erp24/controllers/MatrixErpController.php
erp24/helpers/ImageHelper.php
erp24/media/controllers/MediaController.php
erp24/records/MatrixErp.php
erp24/views/matrix_erp/index.php

index 48f6c1bf46939a4890acf530072095c59b9b53b5..202d7a990f59337da9ab40bd02c6cfc27a9ef0a4 100644 (file)
@@ -2,21 +2,24 @@
 
 namespace app\controllers;
 
+use Matrix\Matrix;
 use Yii;
+use yii\helpers\ArrayHelper;
 use yii\rest\Controller;
 use OpenAPI\Client\Configuration;
 use OpenAPI\Client\Api;
 use OpenAPI\Client\Model;
 use GuzzleHttp;
+use yii_app\records\MarketplaceStore;
+use yii_app\records\MatrixErp;
 use yii_app\records\Products1c;
-use yii_app\services\MarketplaceService;
+use yii_app\records\ProductsClass;
 
 class YandexMarketController extends Controller
 {
     public function actionTest() {
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
 //http://localhost:5555/yandex-market/test
-        return MarketplaceService::infoForMarketplace(2);
 
         $config = Configuration::getDefaultConfiguration()->setApiKey('Api-Key', 'ACMA:r3sa2VyjkgcO0aOxGoyAWuGH15g5mWAqXRMuylVA:a0bccb7e');
 
@@ -80,44 +83,43 @@ class YandexMarketController extends Controller
 //        return $apiInstance->updateStocks(109969229, $update_stocks_request);
 
         $products = Products1c::find()->alias('p')->leftJoin('products_class pc', 'p.parent_id = pc.category_id')
-            ->where(['pc.tip' => 'marketplace'])->all();
+            ->where(['pc.tip' => [ProductsClass::MARKETPLACE, ProductsClass::MARKETPLACE_ADDITIONAL]])->all();
+        $matrixErp = MatrixErp::find()->where(['guid' => ArrayHelper::getColumn($products, 'id')])->all();
+        $matrixErpByGuid = [];
+        foreach ($matrixErp as $matrix) {
+            /* @var $matrix MatrixErp */
+            $matrixErpByGuid[$matrix->guid] = $matrix;
+        }
         $models = [];
         foreach ($products as $product) {
             /* @var $product Products1c */
+            if (($matrixErpByGuid[$product->id]->price->price ?? 0) == 0) {
+                continue;
+            }
             $models []= new Model\UpdateOfferMappingDTO([
                 'offer' => [
                     'offerId' => $product->id,
                     'category' => 'Цветы',
                     'marketCategoryId' => '91284',
-                    'name' => $product->name,
+                    'name' => $matrixErpByGuid[$product->id]->matrixProperty->display_name ?? $product->name,
                     'basicPrice' => [
                         'currencyId' => Model\CurrencyType::RUR,
-                        'value' => 2000 + rand(0, 1000),
+                        'value' => $matrixErpByGuid[$product->id]->price->price,
                     ],
                     'vendor' => 'База Цветов 24',
-                    'weightDimensions' => [
-                        'height' => 40,
-                        'length' => 23,
-                        'weight' => 0.15,
-                        'width' => 20,
-                    ],
-                    'description' => '
-Нежное сочетание хризантем и розовых гербер в этом оформлении создаёт гармонию и яркое настроение. Идеально для поздравлений и особых случаев, когда хочется подчеркнуть свою заботу и внимание. Этот ансамбль привнесёт радость и свежесть в любой момент.
-
-Советы по уходу за цветами:
-1) Меняйте воду в вазе каждые 2 дня.
-2) Обрезайте стебли под углом перед погружением в воду.
-3) Держите букет вдали от прямых солнечных лучей и сквозняков.
-',
-                    'pictures' => ['https://bazacvetov24.ru/products/8608/buket-glyantsevoe-roze-zakazat-s-dostavkoy_9773_lg.jpg'],
+//                    'weightDimensions' => [
+//                        'height' => 40,
+//                        'length' => 23,
+//                        'weight' => 0.15,
+//                        'width' => 20,
+//                    ],
+                    'description' => $matrixErpByGuid[$product->id]->matrixProperty->description ?? '-',
+                    'pictures' => ['https://media.dev1.erp-flowers.ru/media/view-image?id=' . ($matrixErpByGuid[$product->id]->matrixProperty->image_id ?? null)],
                 ],
             ]);
         }
 
-        $apiInstance = new Api\BusinessOfferMappingsApi(
-            new GuzzleHttp\Client(),
-            $config
-        );
+        $apiInstance = new Api\BusinessOfferMappingsApi(new GuzzleHttp\Client(), $config );
 
         $apiModel = new Model\UpdateOfferMappingsRequest;
         $apiModel->setOfferMappings($models);
@@ -180,6 +182,6 @@ class YandexMarketController extends Controller
 //            ]),
 //        ]);
 
-        return $apiInstance->updateoffermappings(5330887, $apiModel);
+        var_dump($apiInstance->updateoffermappings(5330887, $apiModel));
     }
 }
\ No newline at end of file
diff --git a/erp24/commands/MarketplaceController.php b/erp24/commands/MarketplaceController.php
new file mode 100644 (file)
index 0000000..ff2e87e
--- /dev/null
@@ -0,0 +1,58 @@
+<?php
+
+namespace yii_app\commands;
+
+use yii\console\Controller;
+use yii\helpers\ArrayHelper;
+use yii_app\records\MatrixErp;
+use yii_app\records\Products1c;
+use yii_app\records\ProductsClass;
+use yii_app\services\MarketplaceService;
+use OpenAPI\Client\Configuration;
+use OpenAPI\Client\Api;
+use OpenAPI\Client\Model;
+use GuzzleHttp;
+
+class MarketplaceController extends Controller
+{
+    public function actionYandex() {
+        $infoForMarketplace = MarketplaceService::infoForMarketplace(2);
+
+        $config = Configuration::getDefaultConfiguration()->setApiKey('Api-Key', 'ACMA:r3sa2VyjkgcO0aOxGoyAWuGH15g5mWAqXRMuylVA:a0bccb7e');
+
+        $products = Products1c::find()->alias('p')->leftJoin('products_class pc', 'p.parent_id = pc.category_id')
+            ->where(['pc.tip' => [ProductsClass::MARKETPLACE, ProductsClass::MARKETPLACE_ADDITIONAL]])->all();
+        $matrixErp = MatrixErp::find()->where(['guid' => ArrayHelper::getColumn($products, 'id')])->all();
+        $matrixErpByGuid = [];
+        $hiddenOfferings = [];
+        foreach ($matrixErp as $matrix) {
+            /* @var $matrix MatrixErp */
+            $matrixErpByGuid[$matrix->guid] = $matrix;
+            $hiddenOfferings [] = [
+                "offerId" => $matrix->guid,
+            ];
+        }
+
+        $apiInstance = new Api\HiddenOffersApi(new GuzzleHttp\Client(), $config);
+        $add_hidden_offers_request = new Model\AddHiddenOffersRequest([ "hiddenOffers" => $hiddenOfferings ]);
+        var_dump($apiInstance->addHiddenOffers(109969229 /* $campaignId */, $add_hidden_offers_request));
+
+        $apiInstance = new Api\StocksApi(new GuzzleHttp\Client(), $config);
+        foreach ($infoForMarketplace as $campaignId => $guidsWithCnt) {
+            $skus = [];
+            foreach ($guidsWithCnt as $guid => $cnt) {
+                $skus [] = [
+                    "sku" => $guid,
+                    "items" => [
+                        [
+                            "count" => $cnt,
+                            "updatedAt" => date("c"),
+                        ]
+                    ]
+                ];
+            }
+            $update_stocks_request = new Model\UpdateStocksRequest([ "skus" => $skus ]);
+            var_dump($apiInstance->updateStocks(109969229 /* $campaignId */, $update_stocks_request));
+        }
+    }
+}
\ No newline at end of file
index fa0402197635fa46a644ef85cb15316344081554..5c3f269cc8ce3b0dc7ebec86ea5b34f319178821 100644 (file)
@@ -4,6 +4,7 @@ namespace app\controllers;
 
 use Yii;
 use yii\base\DynamicModel;
+use yii\helpers\ArrayHelper;
 use yii\helpers\Json;
 use yii_app\records\MatrixErp;
 use yii_app\records\MatrixErpMedia;
@@ -12,6 +13,8 @@ use yii_app\records\MatrixErpSearch;
 use yii\web\Controller;
 use yii\web\NotFoundHttpException;
 use yii\filters\VerbFilter;
+use yii_app\records\Products1c;
+use yii_app\records\ProductsClass;
 
 /**
  * MatrixErpController implements the CRUD actions for MatrixErp model.
@@ -36,6 +39,45 @@ class MatrixErpController extends Controller
         );
     }
 
+    public static function fillInGuidsFromMarketplaceAndAdditional() {
+        $existings = MatrixErp::find()->all();
+        $existingMapGuidGroupNames = [];
+        foreach ($existings as $existing) {
+            /* @var $existing MatrixErp */
+            $existingMapGuidGroupNames[$existing->guid][] = $existing->group_name;
+        };
+
+        $productsClass = ArrayHelper::getColumn(ProductsClass::find()->where([
+            'tip' => [ProductsClass::MARKETPLACE, ProductsClass::MARKETPLACE_ADDITIONAL]
+        ])->all(), 'category_id');
+        $products = Products1c::find()->where(['parent_id' => $productsClass])->all();
+
+        $newCnt = 0;
+        foreach ($products as $product) {
+            /* @var $product Products1c */
+            if (!in_array($product->id, array_keys($existingMapGuidGroupNames))
+                || !(in_array('marketplace', $existingMapGuidGroupNames[$product->id]))) {
+                $matrixErp = new MatrixErp;
+                $matrixErp->guid = $product->id;
+                $matrixErp->name = $product->name;
+                $matrixErp->parent_id = $product->parent_id;
+                $matrixErp->code = $product->code;
+                $matrixErp->articule = $product->articule;
+                $matrixErp->group_name = 'marketplace';
+                $matrixErp->date_from = date('Y-m-d H:i:s');
+                $matrixErp->components = $product->components;
+                $matrixErp->save();
+                if ($matrixErp->getErrors()) {
+                    throw new \Exception(Json::encode($matrixErp->getErrors()));
+                }
+                $newCnt++;
+            }
+        }
+        if ($newCnt > 0) {
+            Yii::$app->session->setFlash('success', 'Новых записей в matrix-erp ' . $newCnt);
+        }
+    }
+
     /**
      * Lists all MatrixErp models.
      *
@@ -43,6 +85,7 @@ class MatrixErpController extends Controller
      */
     public function actionIndex()
     {
+        self::fillInGuidsFromMarketplaceAndAdditional();
 //        taskFilter 3000-3500
 
         $filterModel = DynamicModel::validateData([
index 7b744a132a6087c5253fb946dab0534dbaf91e82..afd3c7548595a31145442dc4ba240a125cf812f3 100644 (file)
@@ -36,8 +36,11 @@ class ImageHelper
         if ($modelImage && File::src($modelImage->filename, 'images') != null) {
             $fileName = File::src($modelImage->filename, 'images');
             $relaFileName = File::getRealName($imageId);
-            $imageThumbRow = File::getResizedImageByName($modelImage->filename, $width, $height);
-
+            try {
+                $imageThumbRow = File::getResizedImageByName($modelImage->filename, $width, $height);
+            } catch (\Exception $ex) {
+                $imageThumbRow = null;
+            }
             $imageSrcRow = '/' . $imageThumbRow;
             $srcImageThumbRow = '/' . $imageThumbRow;
             $image = Html::img($srcImageThumbRow, ['class' => 'file-preview-image tumb', 'alt' => $relaFileName]);
@@ -58,8 +61,11 @@ class ImageHelper
             if ($modelImage && File::src($modelImage->filename, 'images') != null) {
                 $fileName = File::src($modelImage->filename, 'images');
                 $relaFileName = File::getRealName($imageIdRow);
-                $imageThumbRow =  File::getResizedImageByName($modelImage->filename, $w , $h);
-
+                try {
+                    $imageThumbRow =  File::getResizedImageByName($modelImage->filename, $w , $h);
+                } catch (\Exception $ex) {
+                    $imageThumbRow = null;
+                }
                 $imageSrcRow = '/' . $imageThumbRow;
                 $srcImageThumbRow = '/' . $imageThumbRow;
                 $tagImageThumbRow = Html::img($srcImageThumbRow, ['class' => 'file-preview-image tumb', 'alt' => $relaFileName]);
index dec38f7ae0f44fea47fbe7f58a4e83a8edb2403f..b9285e345c30e6997da8646cb630adca3a8517d9 100644 (file)
@@ -29,6 +29,14 @@ class MediaController extends Controller
         return \Yii::$app->response->sendFile($filepath, $id, ['inline' => true]);
     }
 
+    public function actionViewImage($id) {
+        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
+        $image = Images::findOne($id);
+        $dir_name = substr($image->filename, 0, 2);
+        $filepath = \Yii::getalias('@yii_app/uploads/images') . '/' . $dir_name . '/' . $image->filename;
+        return \Yii::$app->response->sendFile($filepath, $id, ['inline' => true]);
+    }
+
     public function actionViewUrl($url) {
         Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
         $filepath = \Yii::getalias('@yii_app') . FileService::padWithSlash($url);
index 31f7e40afcf23dba2d3ada51c10193eee24f32c4..3adeb8ea91a87a8a1fa5efd8c37b51054b8afe31 100644 (file)
@@ -95,7 +95,7 @@ class MatrixErp extends \yii\db\ActiveRecord
 
     public function setComponentsArray() : void
     {
-        $componentsArray = DataHelper::getValuesFromJson($this->components);
+        $componentsArray = DataHelper::getValuesFromJson($this->components ?? "{}");
         if (!empty($componentsArray)) {
             $this->componentsArray = self::getProducts($componentsArray);
         }
index 2674dfeab69a5827704590bc884de752b249edd4..376e3547841c18a145a951d77dcd8ca3592b5ab4 100644 (file)
@@ -62,8 +62,14 @@ $this->params['breadcrumbs'][] = $this->title;
 
     <h1><?= Html::encode($this->title) ?></h1>
 
-    <p>
-    </p>
+    <?php if (Yii::$app->session->hasFlash('success')): ?>
+        <div class="alert alert-success alert-dismissable">
+            <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
+            <?= Yii::$app->session->getFlash('success') ?>
+            <?php Yii::$app->session->setFlash('success', null) ?>
+        </div>
+    <?php endif; ?>
+
     <div class="row">
         <div class="col-xl-12 col-lg-12 col-md-12">
             <div class="card">