]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
[ERP-148] починил Маринин метод
authorAlexander Smirnov <fredeom@mail.ru>
Tue, 12 Nov 2024 07:19:47 +0000 (10:19 +0300)
committerAlexander Smirnov <fredeom@mail.ru>
Tue, 12 Nov 2024 07:19:47 +0000 (10:19 +0300)
erp24/actions/marketplace/PriorityAction.php
erp24/api2/controllers/YandexMarketController.php
erp24/services/MarketplaceService.php

index a715013c6d0708da1ae8fe1ea91931a6433db063..391abb7951ae9a29225d42699561e8bae2f8f058 100644 (file)
@@ -37,7 +37,9 @@ class PriorityAction extends Action
             return 'ok ' . $guid . ' ' . $paramName . ' ' . $value;
         }
 
-        $productsClass = ArrayHelper::getColumn(ProductsClass::find()->where(['tip' => 'matrix'])->all(), 'category_id');
+        $productsClass = ArrayHelper::getColumn(ProductsClass::find()->where([
+            'tip' => [ProductsClass::MARKETPLACE, ProductsClass::MARKETPLACE_ADDITIONAL]
+        ])->all(), 'category_id');
         $products = ArrayHelper::map(Products1c::find()->where(['parent_id' => $productsClass])->all(), 'id', 'name');
 
         $marketplacePriorityMap = [];
index 741eacfb63da077d1a7f7aa91662bd50fe99d9ee..ea029597090754db8b265de341dbd9236b391328 100644 (file)
@@ -9,12 +9,14 @@ use OpenAPI\Client\Api;
 use OpenAPI\Client\Model;
 use GuzzleHttp;
 use yii_app\records\Products1c;
+use yii_app\services\MarketplaceService;
 
 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, true);
 
         $config = Configuration::getDefaultConfiguration()->setApiKey('Api-Key', 'ACMA:r3sa2VyjkgcO0aOxGoyAWuGH15g5mWAqXRMuylVA:a0bccb7e');
 
index bf3e0304f6c5e31ae3acd4c19349140499585636..0085659c4e95b798ffa7c67fa23b2760890e5faa 100644 (file)
@@ -18,8 +18,6 @@ class MarketplaceService
         if (!array_key_exists($marketId, MarketplaceStore::getWarehouseId()))
             return;
 
-        $marketplacesCount = count(MarketplaceStore::getWarehouseId());
-
         // 1. Получение гуидов букетов
         $productsGroup = ProductsClass::find()
             ->where(['tip' => [ProductsClass::MARKETPLACE, ProductsClass::MARKETPLACE_ADDITIONAL]])
@@ -28,51 +26,68 @@ class MarketplaceService
             ->column();
 
         $productsGuids = Products1c::find()
-            ->where(['in', 'parent_id', $productsGroup])
-            ->andWhere(['<>', 'components', ''])
-            ->select('id')
-            ->column();
+            ->where(['parent_id' => $productsGroup])
+            ->andWhere(['!=', 'components', ''])
+            ->select(['id', 'components'])
+            ->asArray()
+            ->all();
 
         // 2. Получение цен на букеты
-        $prices = ArrayHelper::map(Prices::findAll(['product_id' => $productsGuids]), 'product_id', 'price');
+        $prices = ArrayHelper::map(Prices::findAll(['product_id' => ArrayHelper::getColumn($productsGuids, 'id')]), 'product_id', 'price');
 
         // 3. Получение состава букетов
         $bouquetComposition = [];
-        foreach ($productsGuids as $guid) {
-            $components = Products1c::find()
-                ->andWhere(['id' => $guid])
-                ->select('components')
-                ->column();
+//        $componentsArr = [];
+        $componentsGuids = [];
+        foreach ($productsGuids as $ind => $dataComponents) {
+            $guid = $dataComponents['id'];
+            $components = $dataComponents['components'];
 
             // Проверяем, что массив не пустой и строка валидна
-            if (!empty($components) && !in_array('', $components, true)) {
-                $bouquetComposition[$guid] = json_decode($components[0]); // Сохраняем компоненты
+            if (!empty($components)) {
+                $componentsJson = json_decode($components);
+                $bouquetComposition[$guid] = $componentsJson;
+                foreach ($componentsJson as $compJsonGuid => $compJsonCnt) {
+//                    $componentsArr[] = ['guid' => $compJsonGuid, 'cnt' => $compJsonCnt];
+                    $componentsGuids[] = $compJsonGuid;
+                }
             }
         }
-
+        $componentsGuids = array_unique($componentsGuids);
+//echo "<pre>"; var_dump($componentsArr); die;
         // 4. Проверка остатков
 
         $marketplaceStores = array_column(MarketplaceStore::findAll(['warehouse_id' => $marketId]), null, 'guid');
-
+        $marketplaceStoresCnt = MarketplaceStore::find()->select(['guid', 'COUNT(warehouse_id) as cnt'])->groupBy(['guid'])->indexBy('guid')->asArray()->all();
         $stocks = [];
 
+        $balancesAll = Balances::find()->where(['product_id' => $componentsGuids, 'store_id' => array_keys($marketplaceStores)])->asArray()->all();
+        $balance2Dim = [];
+        $balanceStoreIds = [];
+        foreach ($balancesAll as $balance) {
+            /* @var $balance Balances */
+            $balance2Dim[$balance['store_id']][$balance['product_id']] = $balance['quantity'];
+            $balanceStoreIds[] = $balance['store_id'];
+        }
+//        echo "<pre>"; var_dump($balance2Dim); die;
+        $balanceStoreIds = array_unique($balanceStoreIds);
+
         foreach ($bouquetComposition as $guid => $products) {
             $stockRecords = [];
-
-
             foreach ($products as $product_id => $count) {
-                // Получаем записи остатков для текущего product_id
-                $balances = Balances::findAll(['product_id' => $product_id]);
-
                 // Если записи остатков найдены, суммируем их
-                foreach ($balances as $balance) {
-                    if (array_key_exists($balance->store_id, $marketplaceStores)) {
-                        $marketplace = $marketplaceStores[$balance->store_id];
-                        $stockRecords[$product_id] = ['store_guid' => $marketplace, 'count' => $balance->quantity, 'marketplace_guid' => $marketplace->warehouse_guid];
+                foreach ($balanceStoreIds as $storeId) {
+                    if (array_key_exists($storeId, $marketplaceStores)) {
+                        $marketplace = $marketplaceStores[$storeId];
+                        $stockRecords[$product_id] = [
+                            'store_guid' => $storeId,
+                            'count' => $balance2Dim[$storeId][$product_id] ?? 0,
+                            'marketplace_guid' => $marketplace->warehouse_guid
+                        ];
                     }
                 }
             }
-
+//            echo "<pre>"; var_dump($stockRecords); die;
 
             $bouquetCount = PHP_INT_MAX;
             foreach ($stockRecords as $productGuid => $values) {
@@ -87,30 +102,31 @@ class MarketplaceService
         }
 
         // 5. Получение приоритетов
-        $priorities = MarketplacePriority::findAll(['guid' => $productsGuids]);
-
+        $priorities = MarketplacePriority::find()
+            ->where(['guid' => ArrayHelper::getColumn($productsGuids, 'id')])->indexBy('guid')->asArray()->all();
+//        echo "<pre>"; var_dump($priorities); die;
         // 6. Массив для хранения гуидов, которые можно отправить
         $availableGuids = [];
 
-        foreach ($productsGuids as $guid) {
+        foreach ($productsGuids as $ind => $idAndComponents) {
+            $guid = $idAndComponents['id'];
             if (!array_key_exists($guid, $stocks)) {
                 continue;
             }
 
             $stock = $stocks[$guid];
 
-            $priority = MarketplacePriority::findOne(['guid' => $guid]);
+            $priority = $priorities[$guid] ?? null;
 
             if (empty($priority)) {
                 continue;
             }
-            $minQuanity = $priority->minimal_quantity;
-            $koefRemain = $priority->reminder_koef;
+            $minQuanity = $priority['minimal_quantity'];
+            $koefRemain = $priority['reminder_koef'];
 
             // Учитываем количество букетов с коэффициентом
             $effectiveStock = floor($stock['count'] / $koefRemain);
 
-
             if (array_key_exists($guid, $prices)) {
                 $price = $prices[$guid];
             } else {
@@ -118,7 +134,7 @@ class MarketplaceService
             }
 
             if (($effectiveStock >= $minQuanity)) {
-                $availableGuids[] = array('guid' => $guid, 'count' => $stock['count'], 'price' => $price, 'store' => $stock['store']);// Добав// Добавляем GUID
+                $availableGuids[] = array('guid' => $guid, 'count' => $stock['count'], 'price' => $price, 'store' => $stock['store']);
             }
 
         }
@@ -126,43 +142,44 @@ class MarketplaceService
         $distribution = [];
 
         foreach ($availableGuids as $product) {
-            $stock = $stocks[$product['guid']];
+            $guid = $product['guid'];
+            $stock = $stocks[$guid];
 
-            $priority = MarketplacePriority::findOne(['guid' => $guid]);
+            $priority = $priorities[$guid] ?? null;
 
             if (empty($priority)) {
                 continue;
             }
 
-            $minQuanity = $priority->minimal_quantity;
-            $koefRemain = $priority->reminder_koef;
+            $minQuanity = $priority['minimal_quantity'];
+            $koefRemain = $priority['reminder_koef'];
 
             $totalBouquets = intval($stock['count'] / $koefRemain); // С учетом коэффициента
-
+//            echo "<pre>"; var_dump($availableGuids); var_dump($totalBouquets); var_dump($stock); die;
             if ($totalBouquets >= 2) {
                 // Равномерное распределение
                 foreach ($marketplaceStores as $store) {
-                    $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + floor($totalBouquets / count($marketplaceStores));
+                    $distribution[$store->guid][$guid] = ($distribution[$store->guid][$guid] ?? 0) + floor($totalBouquets / $marketplaceStoresCnt[$store->guid]['cnt']);
                 }
             } elseif ($totalBouquets == 1 && $minQuanity == 1) {
                 // Если минимальный остаток 1, отправляем только на Яндекс
                 foreach ($marketplaceStores as $store) {
                     if ($is_yandex) {
-                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + 1;
+                        $distribution[$store->guid][$guid] = ($distribution[$store->guid][$guid] ?? 0) + 1;
                     }
                 }
             } elseif ($totalBouquets > 1) {
                 // Нечётное количество, большую часть на Яндекс
                 foreach ($marketplaceStores as $store) {
                     if ($is_yandex) {
-                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + ceil($totalBouquets / 2);
+                        $distribution[$store->guid][$guid] = ($distribution[$store->guid][$guid] ?? 0) + ceil($totalBouquets / 2);
                     } else {
-                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + floor($totalBouquets / 2);
+                        $distribution[$store->guid][$guid] = ($distribution[$store->guid][$guid] ?? 0) + floor($totalBouquets / 2);
                     }
                 }
             }
         }
 
-        return Json::encode($availableGuids);
+        return Json::encode($distribution);
     }
 }
\ No newline at end of file