]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Добавление в фиды
authorVladimir Fomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 2 Oct 2025 08:51:54 +0000 (11:51 +0300)
committerVladimir Fomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 2 Oct 2025 08:51:54 +0000 (11:51 +0300)
17 files changed:
erp24/controllers/MarketplaceController.php
erp24/controllers/MarketplacePricesController.php
erp24/migrations/m251001_083230_add_marketplace_prices_table.php
erp24/records/MarketplacePrices.php
erp24/records/MarketplacePricesLog.php
erp24/records/MarketplacePricesLogSearch.php
erp24/records/MarketplacePricesSearch.php
erp24/records/MatrixBouquetActualitySearch.php
erp24/services/MarketplaceService.php
erp24/views/marketplace-prices-log/index.php
erp24/views/marketplace-prices-log/view.php
erp24/views/marketplace-prices/_form.php
erp24/views/marketplace-prices/create.php
erp24/views/marketplace-prices/index.php
erp24/views/marketplace-prices/update.php
erp24/views/marketplace-prices/view.php
erp24/web/js/marketplace-prices/_form.js [new file with mode: 0644]

index 53a2bd4cdd649aa7c1d3af895035e95dbcc2f2a8..ec28a5c57592f844936e02033349f72389d75089 100644 (file)
@@ -23,7 +23,7 @@ class MarketplaceController extends Controller
     public function actionFeed()
     {
         // Получаем информацию о продуктах
-        $productsInfo = MarketplaceService::getAllProductsInfo();
+        $productsInfo = MarketplaceService::getAllProductsInfo(10); // Получаем 10 товаров по умолчанию
 
         // Генерируем XML-фид
         $xmlFeed = MarketplaceService::createXMLFeed($productsInfo);
index 5d6d84b53db1b61aa935d6ae038dd3da04a0ccb4..d672e186ce4ffc554d16d87562b270259e33b334 100644 (file)
@@ -5,6 +5,7 @@ namespace app\controllers;
 use PhpOffice\PhpSpreadsheet\IOFactory;
 use Yii;
 use yii\base\DynamicModel;
+use yii\helpers\ArrayHelper;
 use yii\web\UploadedFile;
 use yii_app\records\MarketplacePrices;
 use yii_app\records\MarketplacePricesLog;
@@ -57,9 +58,10 @@ class MarketplacePricesController extends Controller
 
                 $spreadsheet = IOFactory::load($filePath);
                 $rows = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
-                $mpPrices = MarketplacePrices::find()
-                    ->indexBy('matrix_erp_id')
-                    ->all();
+                $all = MarketplacePrices::find()->all();
+                $mpPrices = ArrayHelper::index($all, function($m) {
+                    return $m->matrix_erp_id . '|' . $m->marketplace_id;
+                });
                 $mpMap = ['YM' => 1, 'FW' => 2];
 
                 foreach ($rows as $row) {
@@ -73,37 +75,55 @@ class MarketplacePricesController extends Controller
                         continue;
                     }
 
-                    $mpPrice = $mpPrices[$matrixProduct->id] ?? null;
-                    $action = 2;
-                    if ($mpPrice === null) {
-                        $mpPrice = new MarketplacePrices();
-                        $mpPrice->matrix_erp_id     = $matrixProduct->id;
-                        $mpPrice->marketplace_alias = $mpAlias;
-                        $mpPrice->marketplace_id    = $mpMap[$mpAlias] ?? null;
-                        $mpPrices[$matrixProduct->id] = $mpPrice;
-                        $action = 1;
+                    $marketplaceId = $mpMap[$mpAlias] ?? null;
+                    $key = $matrixProduct->id . '|' . $marketplaceId;
+
+                    $mpPrice = $mpPrices[$key] ?? MarketplacePrices::findOne([
+                        'matrix_erp_id'  => $matrixProduct->id,
+                        'marketplace_id' => $marketplaceId,
+                    ]);
+
+                    $action = $mpPrice ? 2 : 1;
+                    if (!$mpPrice) {
+                        $mpPrice = new MarketplacePrices([
+                            'matrix_erp_id'      => $matrixProduct->id,
+                            'marketplace_id'     => $marketplaceId,
+                            'marketplace_alias'  => $mpAlias,
+                        ]);
                     }
-                    $beforePrice = $mpPrice->price ?? null;
-                    $beforeOldPrice = $mpPrice->old_price ?? null;
+
+                    $beforePrice     = $mpPrice->price;
+                    $beforeOldPrice  = $mpPrice->old_price;
+
                     $mpPrice->price     = $price;
                     $mpPrice->old_price = $oldPrice;
 
+
+                    if ($action === 2 && $beforePrice === $price && $beforeOldPrice === $oldPrice) {
+                        continue;
+                    }
+
                     if (!$mpPrice->save()) {
-                        Yii::error("Ошибка создания цены: " . json_encode($mpPrice->getErrors()), __METHOD__);
-                    } else {
-                        $mpPriceLog = new MarketplacePricesLog();
-                        $mpPriceLog->marketplace_prices_id = $mpPrice->id;
-                        $mpPriceLog->price_after = $mpPrice->price;
-                        $mpPriceLog->price_before = $beforePrice;
-                        $mpPriceLog->old_price_after = $mpPrice->old_price;
-                        $mpPriceLog->old_price_before = $beforeOldPrice;
-                        $mpPriceLog->changed_at = date('Y-m-d H:i:s');
-                        $mpPriceLog->changed_by = Yii::$app->user->id;
-                        $mpPriceLog->action = $action;
-                        if (!$mpPriceLog->save()) {
-                            Yii::error("Ошибка создания лога цены: " . json_encode($mpPriceLog->getErrors()), __METHOD__);
-                        }
+                        Yii::error("Ошибка создания/обновления цены: " . json_encode($mpPrice->getErrors()), __METHOD__);
+                        continue;
                     }
+
+
+                    $mpPriceLog = new MarketplacePricesLog([
+                        'marketplace_prices_id' => $mpPrice->id,
+                        'price_before'          => $beforePrice,
+                        'price_after'           => $mpPrice->price,
+                        'old_price_before'      => $beforeOldPrice,
+                        'old_price_after'       => $mpPrice->old_price,
+                        'changed_at'            => date('Y-m-d H:i:s'),
+                        'changed_by'            => Yii::$app->user->id,
+                        'action'                => $action,
+                    ]);
+                    if (!$mpPriceLog->save()) {
+                        Yii::error("Ошибка создания лога цены: " . json_encode($mpPriceLog->getErrors()), __METHOD__);
+                    }
+                    $mpPrices[$key] = $mpPrice;
+
                 }
 
                 Yii::$app->session->setFlash('success', 'Импорт завершён: записи добавлены или обновлены.');
@@ -149,8 +169,24 @@ class MarketplacePricesController extends Controller
             $model->loadDefaultValues();
         }
 
+        // Данные для выпадающих списков
+        $matrixErpItems = \yii\helpers\ArrayHelper::map(
+            MatrixErp::find()->where(['active' => 1])->all(),
+            'id',
+            function($model) {
+                return $model->articule . ' - ' . $model->name;
+            }
+        );
+
+        $marketplaceItems = [
+            1 => 'Яндекс маркет',
+            2 => 'Флау вау',
+        ];
+
         return $this->render('create', [
             'model' => $model,
+            'matrixErpItems' => $matrixErpItems,
+            'marketplaceItems' => $marketplaceItems,
         ]);
     }
 
@@ -169,8 +205,24 @@ class MarketplacePricesController extends Controller
             return $this->redirect(['view', 'id' => $model->id]);
         }
 
+        // Данные для выпадающих списков
+        $matrixErpItems = \yii\helpers\ArrayHelper::map(
+            MatrixErp::find()->where(['active' => 1])->all(),
+            'id',
+            function($model) {
+                return $model->articule . ' - ' . $model->name;
+            }
+        );
+
+        $marketplaceItems = [
+            1 => 'Яндекс маркет',
+            2 => 'Флау вау',
+        ];
+
         return $this->render('update', [
             'model' => $model,
+            'matrixErpItems' => $matrixErpItems,
+            'marketplaceItems' => $marketplaceItems,
         ]);
     }
 
index 6e771065432fc39395467542454b69d8753275e7..8fc1cf3acbc2497e5dc384dc9e94702640ac6d59 100644 (file)
@@ -15,7 +15,7 @@ class m251001_083230_add_marketplace_prices_table extends Migration
         if (!isset($tableSchema)) {
             $this->createTable(self::TABLE_NAME, [
                 'id' => $this->primaryKey()->comment('ID'),
-                'matrix_erp_id' => $this->integer()->notNull()->unique()->comment('ID товара матрицы'),
+                'matrix_erp_id' => $this->integer()->notNull()->comment('ID товара матрицы'),
                 'marketplace_id' => $this->integer()->notNull()->comment('ID маркетплейса 1 - YM, 2 - FW'),
                 'marketplace_alias' => $this->string()->notNull()->comment('Алиас маркетплейса - YM, FW'),
                 'price' => $this->decimal(12,2)->notNull()->comment('Цена товара для МП'),
@@ -23,6 +23,12 @@ class m251001_083230_add_marketplace_prices_table extends Migration
                 'created_at' => $this->dateTime()->notNull()->defaultExpression('NOW()')->comment('Когда создано'),
                 'updated_at' => $this->dateTime()->null()->comment('Когда обновлено'),
             ]);
+            $this->createIndex(
+                'ux_marketplace_prices_matrix_marketplace',
+                self::TABLE_NAME,
+                ['matrix_erp_id', 'marketplace_id'],
+                true
+            );
         }
     }
 
index 113a68d490dce1c51c97bc303e2c80576bec17b4..8425183d287a9b69efaf07e556421ab61712172a 100644 (file)
@@ -40,6 +40,20 @@ class MarketplacePrices extends \yii\db\ActiveRecord
         ];
     }
 
+    public function beforeSave($insert)
+    {
+        if (parent::beforeSave($insert)) {
+            // Автоматически заполняем marketplace_alias на основе marketplace_id
+            if ($this->marketplace_id == 1) {
+                $this->marketplace_alias = 'YM';
+            } elseif ($this->marketplace_id == 2) {
+                $this->marketplace_alias = 'FW';
+            }
+            return true;
+        }
+        return false;
+    }
+
     /**
      * {@inheritdoc}
      */
@@ -53,7 +67,10 @@ class MarketplacePrices extends \yii\db\ActiveRecord
             [['price', 'old_price'], 'number'],
             [['created_at', 'updated_at'], 'safe'],
             [['marketplace_alias'], 'string', 'max' => 255],
-            [['matrix_erp_id'], 'unique'],
+            [['matrix_erp_id', 'marketplace_id'], 'unique',
+                'targetAttribute' => ['matrix_erp_id', 'marketplace_id'],
+                'message' => 'Цена для этого товара и маркетплейса уже существует.'
+            ],
         ];
     }
 
@@ -80,4 +97,9 @@ class MarketplacePrices extends \yii\db\ActiveRecord
             ->orderBy(['changed_at' => SORT_DESC, 'id' => SORT_DESC]);
     }
 
+    public function getMatrixErp()
+    {
+        return $this->hasOne(MatrixErp::class, ['id' => 'matrix_erp_id']);
+    }
+
 }
index ebcf32096b72e0f60e40bc1988d20c24be0df1b0..119198d2ea6e76f2b299b81565a15019b620862f 100644 (file)
@@ -79,4 +79,20 @@ class MarketplacePricesLog extends \yii\db\ActiveRecord
         ];
     }
 
+    public function getPrice()
+    {
+        return $this->hasOne(MarketplacePrices::class, ['id' => 'marketplace_prices_id']);
+    }
+
+    public function getMatrixErp()
+    {
+        return $this->hasOne(MatrixErp::class, ['id' => 'matrix_erp_id'])
+            ->via('price', function($q) { $q->alias('p'); });
+    }
+
+    public function getChangedByUser()
+    {
+        return $this->hasOne(Admin::class, ['id' => 'changed_by']);
+    }
+
 }
index c3f7575cbf38511dbb9bfb65b2379621993e0701..0ba180a063ff50a3066efbe7cd15ee01a13abe4c 100644 (file)
@@ -2,6 +2,7 @@
 
 namespace yii_app\records;
 
+use Yii;
 use yii\base\Model;
 use yii\data\ActiveDataProvider;
 use yii_app\records\MarketplacePricesLog;
@@ -11,6 +12,9 @@ use yii_app\records\MarketplacePricesLog;
  */
 class MarketplacePricesLogSearch extends MarketplacePricesLog
 {
+    public $articule;         // артикул из MatrixErp
+    public $changed_by_name;  // имя из Admin
+
     /**
      * {@inheritdoc}
      */
@@ -18,11 +22,19 @@ class MarketplacePricesLogSearch extends MarketplacePricesLog
     {
         return [
             [['id', 'marketplace_prices_id', 'action', 'changed_by'], 'integer'],
-            [['changed_at'], 'safe'],
+            [['changed_at', 'articule', 'changed_by_name'], 'safe'],
             [['price_before', 'price_after', 'old_price_before', 'old_price_after'], 'number'],
         ];
     }
 
+    public function attributeLabels()
+    {
+        return array_merge(parent::attributeLabels(), [
+            'articule'        => 'Артикул',
+            'changed_by_name' => 'Кем изменено',
+        ]);
+    }
+
     /**
      * {@inheritdoc}
      */
@@ -42,35 +54,57 @@ class MarketplacePricesLogSearch extends MarketplacePricesLog
      */
     public function search($params, $formName = null)
     {
-        $query = MarketplacePricesLog::find();
-
-        // add conditions that should always apply here
+        $query = MarketplacePricesLog::find()
+            ->alias('l')
+            ->innerJoinWith(['price p'])
+            ->innerJoinWith(['price.matrixErp me'])
+            ->leftJoin('admin u', 'u.id = l.changed_by')
+            ->with(['price', 'price.matrixErp', 'changedByUser']); // явная загрузка отношений
 
         $dataProvider = new ActiveDataProvider([
             'query' => $query,
+            'sort'  => [
+                'defaultOrder' => ['changed_at' => SORT_DESC, 'id' => SORT_DESC],
+            ],
         ]);
 
+
+        $dataProvider->sort->attributes['articule'] = [
+            'asc' => ['me.articule' => SORT_ASC],
+            'desc'=> ['me.articule' => SORT_DESC],
+        ];
+        $dataProvider->sort->attributes['changed_by_name'] = [
+            'asc' => ['u.name' => SORT_ASC],
+            'desc'=> ['u.name' => SORT_DESC],
+        ];
+
         $this->load($params, $formName);
 
         if (!$this->validate()) {
-            // uncomment the following line if you do not want to return any records when validation fails
-            // $query->where('0=1');
             return $dataProvider;
         }
 
-        // grid filtering conditions
+        // точные фильтры по собственным полям
         $query->andFilterWhere([
-            'id' => $this->id,
-            'marketplace_prices_id' => $this->marketplace_prices_id,
-            'action' => $this->action,
-            'changed_at' => $this->changed_at,
-            'changed_by' => $this->changed_by,
-            'price_before' => $this->price_before,
-            'price_after' => $this->price_after,
-            'old_price_before' => $this->old_price_before,
-            'old_price_after' => $this->old_price_after,
+            'l.id'                    => $this->id,
+            'l.marketplace_prices_id' => $this->marketplace_prices_id,
+            'l.action'                => $this->action,
+            'l.changed_by'            => $this->changed_by,
+            'l.price_before'          => $this->price_before,
+            'l.price_after'           => $this->price_after,
+            'l.old_price_before'      => $this->old_price_before,
+            'l.old_price_after'       => $this->old_price_after,
         ]);
 
+        // если нужно точное равенство по дате-времени, оставь так.
+        // Часто удобнее фильтр по дате (диапазон) — тогда добавь BETWEEN.
+        $query->andFilterWhere(['=', 'l.changed_at', $this->changed_at]);
+
+        // фильтры по связанным таблицам
+        $query->andFilterWhere(['ilike', 'me.articule', $this->articule]);
+        $query->andFilterWhere(['ilike', 'u.name', $this->changed_by_name]);
+
         return $dataProvider;
     }
+
 }
index 6aeeeb02552ede82437f9e2ef062f575fbb1533e..db9cd9b8ae90993a7592252abaa9e6990bc79c39 100644 (file)
@@ -11,6 +11,8 @@ use yii_app\records\MarketplacePrices;
  */
 class MarketplacePricesSearch extends MarketplacePrices
 {
+    public $articule;      // артикул из MatrixErp
+    public $product_name;  // наименование из MatrixErp
     /**
      * {@inheritdoc}
      */
@@ -20,9 +22,18 @@ class MarketplacePricesSearch extends MarketplacePrices
             [['id', 'matrix_erp_id', 'marketplace_id'], 'integer'],
             [['marketplace_alias', 'created_at', 'updated_at'], 'safe'],
             [['price', 'old_price'], 'number'],
+            [['articule', 'product_name'], 'safe'],
         ];
     }
 
+    public function attributeLabels()
+    {
+        return array_merge(parent::attributeLabels(), [
+            'articule'     => 'Артикул',
+            'product_name' => 'Наименование',
+        ]);
+    }
+
     /**
      * {@inheritdoc}
      */
@@ -42,14 +53,24 @@ class MarketplacePricesSearch extends MarketplacePrices
      */
     public function search($params, $formName = null)
     {
-        $query = MarketplacePrices::find();
-
-        // add conditions that should always apply here
+        $query = MarketplacePrices::find()
+            ->alias('mp')
+            ->innerJoinWith(['matrixErp me'])
+            ->with(['matrixErp']); // явная загрузка отношения
 
         $dataProvider = new ActiveDataProvider([
             'query' => $query,
         ]);
 
+        $dataProvider->sort->attributes['articule'] = [
+            'asc'  => ['me.articule' => SORT_ASC],
+            'desc' => ['me.articule' => SORT_DESC],
+        ];
+        $dataProvider->sort->attributes['product_name'] = [
+            'asc'  => ['me.name' => SORT_ASC],
+            'desc' => ['me.name' => SORT_DESC],
+        ];
+
         $this->load($params, $formName);
 
         if (!$this->validate()) {
@@ -60,16 +81,20 @@ class MarketplacePricesSearch extends MarketplacePrices
 
         // grid filtering conditions
         $query->andFilterWhere([
-            'id' => $this->id,
-            'matrix_erp_id' => $this->matrix_erp_id,
-            'marketplace_id' => $this->marketplace_id,
-            'price' => $this->price,
-            'old_price' => $this->old_price,
-            'created_at' => $this->created_at,
-            'updated_at' => $this->updated_at,
+            'mp.id' => $this->id,
+            'mp.matrix_erp_id' => $this->matrix_erp_id,
+            'mp.marketplace_id' => $this->marketplace_id,
+            'mp.price' => $this->price,
+            'mp.old_price' => $this->old_price,
+            'mp.created_at' => $this->created_at,
+            'mp.updated_at' => $this->updated_at,
         ]);
 
-        $query->andFilterWhere(['ilike', 'marketplace_alias', $this->marketplace_alias]);
+        $query->andFilterWhere(['ilike', 'mp.marketplace_alias', $this->marketplace_alias]);
+
+        // фильтры по связанным таблицам
+        $query->andFilterWhere(['ilike', 'me.articule', $this->articule]);
+        $query->andFilterWhere(['ilike', 'me.name', $this->product_name]);
 
         return $dataProvider;
     }
index e42b211cf6a4db3e63a012866900b92ae9006ed3..5a038433e5b6c85fa87de285bbf778df2fe799fd 100644 (file)
@@ -2,6 +2,7 @@
 
 namespace yii_app\records;
 
+use Yii;
 use yii\base\Model;
 use yii\data\ActiveDataProvider;
 use yii_app\records\MatrixBouquetActuality;
index fcade407a70cad9f14d1874af17ca8b7d2549df1..eaa078429f91900dec0b1e18ff3c2e6a84d2e2c5 100644 (file)
@@ -27,6 +27,7 @@ use yii_app\records\MarketplaceOrderItems;
 use yii_app\records\MarketplaceOrders;
 use yii_app\records\MarketplaceOrderStatusHistory;
 use yii_app\records\MarketplaceOrderStatusTypes;
+use yii_app\records\MarketplacePrices;
 use yii_app\records\MarketplacePriority;
 use yii_app\records\MarketplaceStore;
 use yii_app\records\MatrixErpMedia;
@@ -308,7 +309,7 @@ class MarketplaceService
      *
      * @return array
      */
-    public static function getAllProductsInfo($id)
+    public static function getAllProductsInfo($id, $marketplaceId = 2) // 2 = Flowwow по умолчанию
     {
         $parents = ProductsClass::find()
             ->select('category_id')
@@ -344,11 +345,11 @@ class MarketplaceService
                 continue;
             }
 
-            $price = MarketplaceService::getProductPrice($product->id);
-
+            // Получаем цену через геттеры
+            $price = MarketplaceService::getProductPrice($product->id, $marketplaceId);
 
             if ($price == 0) {
-                $message = "У товара {$product->id} отсутствует цена и он будет исключен из фида.";
+                $message = "У Ñ\82оваÑ\80а {$product->id} Ð¾Ñ\82Ñ\81Ñ\83Ñ\82Ñ\81Ñ\82вÑ\83еÑ\82 Ñ\86ена Ð´Ð»Ñ\8f Ð¼Ð°Ñ\80кеÑ\82плейÑ\81а {$marketplaceId} Ð¸ Ð¾Ð½ Ð±Ñ\83деÑ\82 Ð¸Ñ\81клÑ\8eÑ\87ен Ð¸Ð· Ñ\84ида.";
                 Yii::error($message, __METHOD__);
                 InfoLogService::setInfoLog(
                     __FILE__,
@@ -359,6 +360,8 @@ class MarketplaceService
                 continue;
             }
 
+            $oldPrice = MarketplaceService::getProductOldPrice($product->id, $marketplaceId);
+
             $components = json_decode($product->components, true);
             $composition = [];
 
@@ -380,7 +383,7 @@ class MarketplaceService
                 'name' => $properties['displayName'],
                 'pictures' => [$properties['imageUrl']],
                 'price' => $price,
-                'oldprice' => MarketplaceService::getProductOldPrice($product->id),
+                'oldprice' => $oldPrice,
                 'description' => MarketplaceService::getProductDescription($product->id),
                 'qty' => MarketplaceService::getProductQty($product->id),
                 'amount' => MarketplaceService::getProductQty($product->id),
@@ -418,6 +421,9 @@ class MarketplaceService
             return [];
         }
 
+        // Определяем marketplace_id на основе warehouse_id
+        $marketplaceId = ($store->warehouse_id == MarketplaceStore::YANDEX_WAREHOUSE_ID) ? 1 : 2; // 1-YM, 2-FW
+
         $productQuantities = $storeData[$storeGuid];
 
         $products = Products1c::find()
@@ -442,10 +448,10 @@ class MarketplaceService
                 continue;
             }
 
-            $price = MarketplaceService::getProductPrice($product->id);
+            $price = MarketplaceService::getProductPrice($product->id, $marketplaceId);
 
             if ($price == 0) {
-                $message = "У товара {$product->id} отсутствует цена и он будет исключен из фида.";
+                $message = "У Ñ\82оваÑ\80а {$product->id} Ð¾Ñ\82Ñ\81Ñ\83Ñ\82Ñ\81Ñ\82вÑ\83еÑ\82 Ñ\86ена Ð´Ð»Ñ\8f Ð¼Ð°Ñ\80кеÑ\82плейÑ\81а {$marketplaceId} Ð¸ Ð¾Ð½ Ð±Ñ\83деÑ\82 Ð¸Ñ\81клÑ\8eÑ\87ен Ð¸Ð· Ñ\84ида.";
                 Yii::error($message, __METHOD__);
 
 
@@ -479,7 +485,7 @@ class MarketplaceService
                 'name' => $properties['displayName'],
                 'pictures' => !empty($properties['imageUrls']) ? $properties['imageUrls'] : [$properties['imageUrl']],
                 'price' => $price,
-                'oldprice' => MarketplaceService::getProductOldPrice($product->id),
+                'oldprice' => MarketplaceService::getProductOldPrice($product->id, $marketplaceId),
                 'description' => MarketplaceService::getProductDescription($product->id),
                 'qty' => $availableQty,
                 'amount' => $availableQty,
@@ -568,7 +574,12 @@ class MarketplaceService
 
             // Добавление цены и валюты
             $offer->addChild('price', $product['price']);
-            //    $offer->addChild('oldPrice', $product['oldprice']);
+
+            // Добавление старой цены, если она есть
+            if (!empty($product['oldprice']) && $product['oldprice'] > 0) {
+                $offer->addChild('oldprice', $product['oldprice']);
+            }
+
             $offer->addChild('currencyId', 'RUB');
             $offer->addChild('categoryId', $product['category_id']);
 
@@ -680,17 +691,24 @@ class MarketplaceService
         return 'https://media.erp-flowers.ru/media/view-card?guid=' . urlencode($guid);
     }
 
-    private static function getProductPrice($productId)
+    private static function getProductPrice($productId, $marketplaceId = MarketplaceStore::FLOWWOW_WAREHOUSE_ID)
     {
-        $price = Prices::find()
-            ->where(['product_id' => $productId])
+        $marketplacePrice = MarketplacePrices::find()
+            ->joinWith('matrixErp me')
+            ->where(['me.guid' => $productId, 'marketplace_id' => $marketplaceId])
             ->one();
-        return $price['price'] ?? 0;
+
+        return $marketplacePrice ? $marketplacePrice->price : 0;
     }
 
-    private static function getProductOldPrice($productId)
+    private static function getProductOldPrice($productId, $marketplaceId = 2)
     {
-        return 300;
+        $marketplacePrice = MarketplacePrices::find()
+            ->joinWith('matrixErp me')
+            ->where(['me.guid' => $productId, 'marketplace_id' => $marketplaceId])
+            ->one();
+
+        return $marketplacePrice ? $marketplacePrice->old_price : null;
     }
 
     private static function getProductDescription($productId)
index 08d0ad83922c624e5edee3a52d12f5d48439e5b4..0148daa6b96b94254c13a3fd5091d9521b98c1b7 100644 (file)
@@ -22,55 +22,52 @@ $this->params['breadcrumbs'][] = $this->title;
 
     <?= GridView::widget([
         'dataProvider' => $dataProvider,
-        'filterModel' => $searchModel,
+        'filterModel'  => $searchModel,
         'columns' => [
             ['class' => 'yii\grid\SerialColumn'],
 
             'id',
 
             [
-                'attribute' => 'marketplace_prices_id',
-                'label' => 'Товар',
+                'attribute' => 'articule',
+                'label' => 'Товар (артикул)',
                 'format' => 'raw',
                 'value' => function ($model) {
-                    $mpPrice = \yii_app\records\MarketplacePrices::find()
-                        ->where(['id' => $model->marketplace_prices_id])->one();
-
-                    return \yii_app\records\MatrixErp::find()->select('articule')
-                        ->where(['id' => $mpPrice->matrix_erp_id])->scalar();
+                    if (!$model->matrixErp) return null;
+                    return Html::a(
+                        $model->matrixErp->articule,
+                        ['/matrix-erp/update', 'id' => $model->price->matrix_erp_id ?? null]
+                    );
                 },
             ],
+
             [
                 'attribute' => 'action',
                 'label' => 'Действие',
+                'filter' => [1 => 'Создание', 2 => 'Изменение'],
                 'value' => function ($model) {
                     return $model->action == 1 ? 'Создание' : 'Изменение';
                 },
             ],
-            [
-                'attribute' => 'price_before',
-                'label' => 'Цена до',
-            ],
-            [
-                'attribute' => 'price_after',
-                'label' => 'Цена после',
-            ],
-            [
-                'attribute' => 'old_price_before',
-                'label' => 'Старая Цена до',
-            ],
-            [
-                'attribute' => 'old_price_after',
-                'label' => 'Старая Цена после',
-            ],
+
+            ['attribute' => 'price_before',     'label' => 'Цена до'],
+            ['attribute' => 'price_after',      'label' => 'Цена после'],
+            ['attribute' => 'old_price_before', 'label' => 'Старая цена до'],
+            ['attribute' => 'old_price_after',  'label' => 'Старая цена после'],
+
             'changed_at',
+
             [
-                'attribute' => 'changed_by',
+                'attribute' => 'changed_by_name',
                 'label' => 'Кем изменено',
-                'format' => 'raw',
                 'value' => function ($model) {
-                    return Admin::find()->select('name')->where(['id' => $model->changed_by])->scalar();
+                    return $model->changedByUser->name ?? null;
                 },
+                'filter' => Html::textInput(
+                    Html::getInputName($searchModel, 'changed_by_name'),
+                    $searchModel->changed_by_name,
+                    ['class' => 'form-control']
+                ),
             ],
         ],
     ]); ?>
index bfa3932d95e5a8cf491b88ec713b204db6887060..49d96f0441960dbac5ae1531bddbde42f3cfaa45 100644 (file)
@@ -11,7 +11,7 @@ $this->params['breadcrumbs'][] = ['label' => 'Marketplace Prices Logs', 'url' =>
 $this->params['breadcrumbs'][] = $this->title;
 \yii\web\YiiAsset::register($this);
 ?>
-<div class="marketplace-prices-log-view">
+<div class="marketplace-prices-log-view p-4">
 
     <h1><?= Html::encode($this->title) ?></h1>
 
index 0f38f5bf2a7728aa9537f337db71bcb2864548e2..4390d7d2418e0d16db6da48fc63134c913fa440c 100644 (file)
@@ -1,22 +1,36 @@
 <?php
 
+use kartik\select2\Select2;
 use yii\helpers\Html;
 use yii\widgets\ActiveForm;
 
 /** @var yii\web\View $this */
 /** @var yii_app\records\MarketplacePrices $model */
 /** @var yii\widgets\ActiveForm $form */
+/** @var array $matrixErpItems */
+/** @var array $marketplaceItems */
+
+$this->registerJsFile('/js/marketplace-prices/_form.js', ['position' => \yii\web\View::POS_END]);
 ?>
 
 <div class="marketplace-prices-form">
 
     <?php $form = ActiveForm::begin(); ?>
 
-    <?= $form->field($model, 'matrix_erp_id')->textInput() ?>
+    <?= $form->field($model, 'matrix_erp_id')->widget(Select2::class, [
+        'data' => $matrixErpItems,
+        'options' => [
+            'placeholder' => 'Выберите товар...',
+            'value' => $model->matrix_erp_id,
+        ],
+        'pluginOptions' => [
+            'allowClear' => true,
+        ],
+    ]) ?>
 
-    <?= $form->field($model, 'marketplace_id')->textInput() ?>
+    <?= $form->field($model, 'marketplace_id')->dropDownList($marketplaceItems, ['prompt' => 'Выберите маркетплейс...', 'id' => 'marketplace-id']) ?>
 
-    <?= $form->field($model, 'marketplace_alias')->textInput(['maxlength' => true]) ?>
+    <?= $form->field($model, 'marketplace_alias')->textInput(['maxlength' => true, 'readonly' => true, 'id' => 'marketplace-alias']) ?>
 
     <?= $form->field($model, 'price')->textInput() ?>
 
@@ -29,3 +43,5 @@ use yii\widgets\ActiveForm;
     <?php ActiveForm::end(); ?>
 
 </div>
+
+
index ed8884135aeb48beb5d80809a93acc9701f51150..55337410a2103848a375fcc3b055166d301082bd 100644 (file)
@@ -4,6 +4,8 @@ use yii\helpers\Html;
 
 /** @var yii\web\View $this */
 /** @var yii_app\records\MarketplacePrices $model */
+/** @var array $matrixErpItems */
+/** @var array $marketplaceItems */
 
 $this->title = 'Создать цену';
 $this->params['breadcrumbs'][] = ['label' => 'Marketplace Prices', 'url' => ['index']];
@@ -15,6 +17,8 @@ $this->params['breadcrumbs'][] = $this->title;
 
     <?= $this->render('_form', [
         'model' => $model,
+        'matrixErpItems' => $matrixErpItems,
+        'marketplaceItems' => $marketplaceItems,
     ]) ?>
 
 </div>
index ee9eb871eedb260536d49c72d2ce0866001cb861..3766a073092874c6a0c050f872e0405a2242e5ef 100644 (file)
@@ -14,19 +14,34 @@ use yii\grid\GridView;
 $this->title = 'Цены для маркетплейсов';
 $this->params['breadcrumbs'][] = $this->title;
 ?>
-<div class="marketplace-prices-index px-4">
+<div class="marketplace-prices-index p-4">
 
     <h1><?= Html::encode($this->title) ?></h1>
 
-    <p>
-        <?= Html::a('Добавить цены', ['create'], ['class' => 'btn btn-success']) ?>
+    <div class="d-flex justify-content-between">
+        <div>
+            <?= Html::a('Добавить цены', ['create'], ['class' => 'btn btn-success ']) ?>
+            <?= Html::a('История цен', ['/marketplace-prices-log/index'], ['class' => 'btn btn-success']) ?>
+            <?= Html::a('Товары маркетплейсов', ['/matrix-erp/index'], ['class' => 'btn btn-success']) ?>
+        </div>
+
         <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
-        <?= $form->field($model, 'excelFile')->fileInput() ?>
-    <div class="form-group">
-        <?= Html::submitButton('Загрузить', ['class' => 'btn btn-success']) ?>
+            <div class="mb-3">
+                <label for="excelFile" class="form-label">Выберите файл Excel</label>
+                <?= $form->field($model, 'excelFile', [
+                    'template' => '{input}{error}',
+                    'inputOptions' => [
+                        'class' => 'form-control',
+                        'id' => 'excelFile',
+                        'accept' => '.xlsx,.xls'
+                    ]
+                ])->fileInput()->label(false) ?>
+            </div>
+            <div class="form-group">
+                <?= Html::submitButton('Загрузить', ['class' => 'btn btn-success']) ?>
+            </div>
+        <?php ActiveForm::end(); ?>
     </div>
-    <?php ActiveForm::end(); ?>
-    </p>
 
     <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
 
@@ -38,30 +53,27 @@ $this->params['breadcrumbs'][] = $this->title;
 
             'id',
             [
-                'attribute' => 'matrix_erp_id',
+                'attribute' => 'articule',
                 'label' => 'Артикул товара',
                 'format' => 'raw',
                 'value' => function ($model) {
-                    $matrixProduct = \yii_app\records\MatrixErp::find()
-                        ->where(['id' => $model->matrix_erp_id])->one();
+                    $matrixProduct = $model->matrixErp;
                     return Html::a($matrixProduct->articule, '/matrix-erp/update?id=' . $model->matrix_erp_id);
-
                 },
             ],
             [
-                'attribute' => 'matrix_erp_id',
+                'attribute' => 'product_name',
                 'label' => 'Наименование товара',
                 'format' => 'raw',
                 'value' => function ($model) {
-                    $matrixProduct = \yii_app\records\MatrixErp::find()
-                        ->where(['id' => $model->matrix_erp_id])->one();
+                    $matrixProduct = $model->matrixErp;
                     return Html::a($matrixProduct->name, '/matrix-erp/update?id=' . $model->matrix_erp_id);
-
                 },
             ],
             [
                 'attribute' => 'marketplace_id',
                 'label' => 'Маркетплейс',
+                'filter' => [1 => 'ЯндексМаркет', 2 => 'Flowwow'],
                 'value' => function ($model) {
                     return $model->marketplace_id == 1 ? 'ЯндексМаркет' : 'Flowwow';
                 },
index 51ddea3cf473e391fe743ce76b5a0db4da15a8d7..438826d3db9e5efac8e4241709176fd82d137a26 100644 (file)
@@ -4,11 +4,13 @@ use yii\helpers\Html;
 
 /** @var yii\web\View $this */
 /** @var yii_app\records\MarketplacePrices $model */
+/** @var array $matrixErpItems */
+/** @var array $marketplaceItems */
 
-$this->title = 'Изменить цену: ' . $model->id;
+$this->title = 'Изменить цену: ' . ($model->matrixErp->name ?? 'товар');
 $this->params['breadcrumbs'][] = ['label' => 'Marketplace Prices', 'url' => ['index']];
-$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
-$this->params['breadcrumbs'][] = 'Update';
+$this->params['breadcrumbs'][] = ['label' => $model->matrixErp->name ?? $model->id, 'url' => ['view', 'id' => $model->id]];
+$this->params['breadcrumbs'][] = 'Изменить';
 ?>
 <div class="marketplace-prices-update px-4">
     <?= Html::a('Назад', ['index'], ['class' => 'btn btn-primary my-4']) ?>
@@ -16,6 +18,8 @@ $this->params['breadcrumbs'][] = 'Update';
 
     <?= $this->render('_form', [
         'model' => $model,
+        'matrixErpItems' => $matrixErpItems,
+        'marketplaceItems' => $marketplaceItems,
     ]) ?>
 
 </div>
index 865b3f378ee5a0b6c66a158c67d8cc0f71e6fe61..ed08a95558ad4a892110a782f57c130a7ce6a96c 100644 (file)
@@ -6,12 +6,12 @@ use yii\widgets\DetailView;
 /** @var yii\web\View $this */
 /** @var yii_app\records\MarketplacePrices $model */
 
-$this->title = $model->id;
+$this->title = $model->matrixErp->name ?? 'Цена товара';
 $this->params['breadcrumbs'][] = ['label' => 'Marketplace Prices', 'url' => ['index']];
 $this->params['breadcrumbs'][] = $this->title;
 \yii\web\YiiAsset::register($this);
 ?>
-<div class="marketplace-prices-view">
+<div class="marketplace-prices-view p-4">
     <?= Html::a('Назад', ['index'], ['class' => 'btn btn-primary my-4']) ?>
     <h1><?= Html::encode($this->title) ?></h1>
 
diff --git a/erp24/web/js/marketplace-prices/_form.js b/erp24/web/js/marketplace-prices/_form.js
new file mode 100644 (file)
index 0000000..e14479c
--- /dev/null
@@ -0,0 +1,18 @@
+$(document).ready(function() {
+    $('#marketplace-id').change(function() {
+        var marketplaceId = $(this).val();
+        var alias = '';
+        if (marketplaceId == 1) {
+            alias = 'YM';
+        } else if (marketplaceId == 2) {
+            alias = 'FW';
+        }
+        $('#marketplace-alias').val(alias);
+    });
+
+    // Инициализация при загрузке страницы (для редактирования)
+    var initialMarketplaceId = $('#marketplace-id').val();
+    if (initialMarketplaceId) {
+        $('#marketplace-id').trigger('change');
+    }
+});