]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ERP-153 Реализовать метод для сбора информации об остатках и стоимости товара
authormarina <m.zozirova@gmail.com>
Fri, 8 Nov 2024 13:13:39 +0000 (16:13 +0300)
committermarina <m.zozirova@gmail.com>
Fri, 8 Nov 2024 13:13:39 +0000 (16:13 +0300)
erp24/actions/marketplace/InfoAboutStocksAndPrice.php [deleted file]
erp24/controllers/AdminController.php
erp24/controllers/MarketplaceController.php
erp24/services/MarketplaceService.php [new file with mode: 0644]

diff --git a/erp24/actions/marketplace/InfoAboutStocksAndPrice.php b/erp24/actions/marketplace/InfoAboutStocksAndPrice.php
deleted file mode 100644 (file)
index f6ca73c..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-<?php
-
-namespace yii_app\actions\marketplace;
-
-use yii\base\Action;
-use yii\helpers\ArrayHelper;
-use yii\helpers\Json;
-use yii_app\records\Balances;
-use yii_app\records\MarketplacePriority;
-use yii_app\records\MarketplaceStore;
-use yii_app\records\Prices;
-use yii_app\records\Products1c;
-use yii_app\records\ProductsClass;
-
-
-class InfoAboutStocksAndPrice extends Action
-{
-    public function run()
-    {
-        $post = \Yii::$app->request->post();
-        $marketId = $post['marketId'];
-        $is_yandex = $post['is_yandex'];
-
-        if (!array_key_exists($marketId, MarketplaceStore::getWarehouseId()))
-            return;
-
-        $marketplacesCount = count(MarketplaceStore::getWarehouseId());
-
-        // 1. Получение гуидов букетов
-        $productsGroup = ProductsClass::find()
-            ->orWhere(['ilike', 'tip', ProductsClass::MARKETPLACE])
-            ->orWhere(['ilike', 'tip', ProductsClass::MARKETPLACE_ADDITIONAL])
-            ->select('category_id')
-            ->asArray();
-
-        $productsGuids = Products1c::find()
-            ->andWhere(['in', 'parent_id', $productsGroup])
-            ->andWhere(['<>', 'components', ''])
-            ->select('id')
-            ->column();
-
-        // 2. Получение цен на букеты
-        $prices = ArrayHelper::map(Prices::findAll(['product_id' => $productsGuids]), 'product_id', 'price');
-
-        // 3. Получение состава букетов
-        $bouquetComposition = [];
-        foreach ($productsGuids as $guid) {
-            $components = Products1c::find()
-                ->andWhere(['id' => $guid])
-                ->select('components')
-                ->column();
-
-            // Проверяем, что массив не пустой и строка валидна
-            if (!empty($components) && !in_array('', $components, true)) {
-                $bouquetComposition[$guid] = json_decode($components[0]); // Сохраняем компоненты
-            }
-        }
-
-        // 4. Проверка остатков
-
-        $marketplaceStores = array_column(MarketplaceStore::findAll(['warehouse_id' => $marketId]), null, 'guid');
-
-        $stocks = [];
-
-        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 ($stockRecords as $productGuid => $values) {
-                $temp = intval($values['count'] / $products->$productGuid);
-                $bouquetCount = !empty($bouquetCount) ? min($bouquetCount, $temp) : $temp;
-                $store = $values['marketplace_guid'];
-            }
-
-            if ($bouquetCount > 0) {
-                $stocks[$guid] = ['count' => $bouquetCount, 'store' => $store];
-            }
-        }
-
-        // 5. Получение приоритетов
-        $priorities = MarketplacePriority::findAll(['guid' => $productsGuids]);
-
-        // 6. Массив для хранения гуидов, которые можно отправить
-        $availableGuids = [];
-
-        foreach ($productsGuids as $guid) {
-            if (!array_key_exists($guid, $stocks)) {
-                continue;
-            }
-
-            $stock = $stocks[$guid];
-
-            $priority = MarketplacePriority::findOne(['guid' => $guid]);
-
-            if (empty($priority)) {
-                continue;
-            }
-            $minQuanity = $priority->minimal_quantity;
-            $koefRemain = $priority->reminder_koef;
-
-            // Учитываем количество букетов с коэффициентом
-            $effectiveStock = floor($stock['count'] / $koefRemain);
-
-
-            if (array_key_exists($guid, $prices)) {
-                $price = $prices[$guid];
-            } else {
-                continue;
-            }
-
-            if (($effectiveStock >= $minQuanity)) {
-                $availableGuids[] = array('guid' => $guid, 'count' => $stock['count'], 'price' => $price, 'store' => $stock['store']);// Добав// Добавляем GUID
-            }
-
-        }
-
-        $distribution = [];
-
-        foreach ($availableGuids as $product) {
-            $stock = $stocks[$product['guid']];
-
-            $priority = MarketplacePriority::findOne(['guid' => $guid]);
-
-            if (empty($priority)) {
-                continue;
-            }
-
-            $minQuanity = $priority->minimal_quantity;
-            $koefRemain = $priority->reminder_koef;
-
-            $totalBouquets = intval($stock['count'] / $koefRemain); // С учетом коэффициента
-
-            if ($totalBouquets >= 2) {
-                // Равномерное распределение
-                foreach ($marketplaceStores as $store) {
-                    $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + floor($totalBouquets / count($marketplaceStores));
-                }
-            } elseif ($totalBouquets == 1 && $minQuanity == 1) {
-                // Если минимальный остаток 1, отправляем только на Яндекс
-                foreach ($marketplaceStores as $store) {
-                    if ($is_yandex) {
-                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + 1;
-                    }
-                }
-            } elseif ($totalBouquets > 1) {
-                // Нечётное количество, большую часть на Яндекс
-                foreach ($marketplaceStores as $store) {
-                    if ($is_yandex) {
-                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + ceil($totalBouquets / 2);
-                    } else {
-                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + floor($totalBouquets / 2);
-                    }
-                }
-            }
-        }
-
-        return Json::decode($availableGuids);
-    }
-}
index 584d7fa966767998ba8d7c04c342393e8e86779f..8ce25d94ccc40525100ded136878950c632ec28f 100755 (executable)
@@ -18,8 +18,6 @@ class AdminController extends \yii\web\Controller
         return [
             'index' => \yii_app\actions\admin\IndexAction::class,
             'add' => \yii_app\actions\admin\AddAction::class,
-
-
         ];
     }
 
index 82eca99d4789eb0a3d2f0ec8949ce40c4722b71a..765fad6d0d72b664b6b90cde63285a2c82c5869d 100644 (file)
@@ -9,7 +9,6 @@ class MarketplaceController extends Controller
     public function actions() {
         return [
             'priority' => \yii_app\actions\marketplace\PriorityAction::class,
-            'infoAboutStocksAndPrice' => \yii_app\actions\marketplace\InfoAboutStocksAndPrice::class,
         ];
     }
 }
\ 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..67ba804
--- /dev/null
@@ -0,0 +1,167 @@
+<?php
+
+namespace yii_app\services;
+
+use yii\helpers\ArrayHelper;
+use yii\helpers\Json;
+use yii_app\records\Balances;
+use yii_app\records\MarketplacePriority;
+use yii_app\records\MarketplaceStore;
+use yii_app\records\Prices;
+use yii_app\records\Products1c;
+use yii_app\records\ProductsClass;
+
+class MarketplaceService
+{
+
+    public static function infoForMarketplace(int $marketId, bool $is_yandex) {
+        if (!array_key_exists($marketId, MarketplaceStore::getWarehouseId()))
+            return;
+
+        $marketplacesCount = count(MarketplaceStore::getWarehouseId());
+
+        // 1. Получение гуидов букетов
+        $productsGroup = ProductsClass::find()
+            ->orWhere(['ilike', 'tip', ProductsClass::MARKETPLACE])
+            ->orWhere(['ilike', 'tip', ProductsClass::MARKETPLACE_ADDITIONAL])
+            ->select('category_id')
+            ->asArray();
+
+        $productsGuids = Products1c::find()
+            ->andWhere(['in', 'parent_id', $productsGroup])
+            ->andWhere(['<>', 'components', ''])
+            ->select('id')
+            ->column();
+
+        // 2. Получение цен на букеты
+        $prices = ArrayHelper::map(Prices::findAll(['product_id' => $productsGuids]), 'product_id', 'price');
+
+        // 3. Получение состава букетов
+        $bouquetComposition = [];
+        foreach ($productsGuids as $guid) {
+            $components = Products1c::find()
+                ->andWhere(['id' => $guid])
+                ->select('components')
+                ->column();
+
+            // Проверяем, что массив не пустой и строка валидна
+            if (!empty($components) && !in_array('', $components, true)) {
+                $bouquetComposition[$guid] = json_decode($components[0]); // Сохраняем компоненты
+            }
+        }
+
+        // 4. Проверка остатков
+
+        $marketplaceStores = array_column(MarketplaceStore::findAll(['warehouse_id' => $marketId]), null, 'guid');
+
+        $stocks = [];
+
+        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 ($stockRecords as $productGuid => $values) {
+                $temp = intval($values['count'] / $products->$productGuid);
+                $bouquetCount = !empty($bouquetCount) ? min($bouquetCount, $temp) : $temp;
+                $store = $values['marketplace_guid'];
+            }
+
+            if ($bouquetCount > 0) {
+                $stocks[$guid] = ['count' => $bouquetCount, 'store' => $store];
+            }
+        }
+
+        // 5. Получение приоритетов
+        $priorities = MarketplacePriority::findAll(['guid' => $productsGuids]);
+
+        // 6. Массив для хранения гуидов, которые можно отправить
+        $availableGuids = [];
+
+        foreach ($productsGuids as $guid) {
+            if (!array_key_exists($guid, $stocks)) {
+                continue;
+            }
+
+            $stock = $stocks[$guid];
+
+            $priority = MarketplacePriority::findOne(['guid' => $guid]);
+
+            if (empty($priority)) {
+                continue;
+            }
+            $minQuanity = $priority->minimal_quantity;
+            $koefRemain = $priority->reminder_koef;
+
+            // Учитываем количество букетов с коэффициентом
+            $effectiveStock = floor($stock['count'] / $koefRemain);
+
+
+            if (array_key_exists($guid, $prices)) {
+                $price = $prices[$guid];
+            } else {
+                continue;
+            }
+
+            if (($effectiveStock >= $minQuanity)) {
+                $availableGuids[] = array('guid' => $guid, 'count' => $stock['count'], 'price' => $price, 'store' => $stock['store']);// Добав// Добавляем GUID
+            }
+
+        }
+
+        $distribution = [];
+
+        foreach ($availableGuids as $product) {
+            $stock = $stocks[$product['guid']];
+
+            $priority = MarketplacePriority::findOne(['guid' => $guid]);
+
+            if (empty($priority)) {
+                continue;
+            }
+
+            $minQuanity = $priority->minimal_quantity;
+            $koefRemain = $priority->reminder_koef;
+
+            $totalBouquets = intval($stock['count'] / $koefRemain); // С учетом коэффициента
+
+            if ($totalBouquets >= 2) {
+                // Равномерное распределение
+                foreach ($marketplaceStores as $store) {
+                    $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + floor($totalBouquets / count($marketplaceStores));
+                }
+            } elseif ($totalBouquets == 1 && $minQuanity == 1) {
+                // Если минимальный остаток 1, отправляем только на Яндекс
+                foreach ($marketplaceStores as $store) {
+                    if ($is_yandex) {
+                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + 1;
+                    }
+                }
+            } elseif ($totalBouquets > 1) {
+                // Нечётное количество, большую часть на Яндекс
+                foreach ($marketplaceStores as $store) {
+                    if ($is_yandex) {
+                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + ceil($totalBouquets / 2);
+                    } else {
+                        $distribution[$store->guid] = ($distribution[$store->guid] ?? 0) + floor($totalBouquets / 2);
+                    }
+                }
+            }
+        }
+
+        return Json::encode($availableGuids);
+    }
+}
\ No newline at end of file