From ee10d8f586dfd1f9b3c18129e17361344060931f Mon Sep 17 00:00:00 2001 From: fomichev Date: Tue, 12 Nov 2024 13:44:14 +0300 Subject: [PATCH] =?utf8?q?=D0=A4=D0=B8=D0=B4=20=D1=82=D0=B5=D1=81=D1=82?= =?utf8?q?=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- erp24/media/controllers/FlowwowController.php | 4 +- erp24/services/MarketplaceService.php | 137 +++++++++++++++++- 2 files changed, 132 insertions(+), 9 deletions(-) diff --git a/erp24/media/controllers/FlowwowController.php b/erp24/media/controllers/FlowwowController.php index 0b65b8c5..b8211a65 100644 --- a/erp24/media/controllers/FlowwowController.php +++ b/erp24/media/controllers/FlowwowController.php @@ -15,9 +15,11 @@ class FlowwowController extends Controller public function actionFeed($id) { + $balanceInfo = MarketplaceService::infoForMarketplace(1); + $productsInfo = MarketplaceService::getProductsInfoForFeed($id,$balanceInfo); - $productsInfo = MarketplaceService::getAllProductsInfo($id); + // $productsInfo = MarketplaceService::getAllProductsInfo($id); $xmlFeed = MarketplaceService::createXMLFeed($productsInfo); diff --git a/erp24/services/MarketplaceService.php b/erp24/services/MarketplaceService.php index 59db72fe..6aeefa2b 100644 --- a/erp24/services/MarketplaceService.php +++ b/erp24/services/MarketplaceService.php @@ -107,7 +107,7 @@ class MarketplaceService } } - // var_dump($prices); + //var_dump($prices); // 3. Получение состава букетов $bouquetComposition = []; @@ -130,10 +130,14 @@ class MarketplaceService // 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) { @@ -141,9 +145,9 @@ class MarketplaceService $balance2Dim[$balance['store_id']][$balance['product_id']] = $balance['quantity']; $balanceStoreIds[] = $balance['store_id']; } - + //var_dump( $balanceStoreIds ); $balanceStoreIds = array_unique($balanceStoreIds); - //var_dump($balanceStoreIds); + foreach ($bouquetComposition as $guid => $products) { $stockRecords = []; foreach ($products as $product_id => $count) { @@ -171,11 +175,11 @@ class MarketplaceService $stocks[$guid] = ['count' => $bouquetCount, 'store' => $store]; } } - + //var_dump(ArrayHelper::getColumn($productsGuids, 'id')); // 5. Получение приоритетов $priorities = MarketplacePriority::find() ->where(['guid' => ArrayHelper::getColumn($productsGuids, 'id')])->indexBy('guid')->asArray()->all(); - + //var_dump($priorities); // 6. Массив для хранения гуидов, которые можно отправить $availableGuids = []; @@ -209,7 +213,7 @@ class MarketplaceService } } - + // var_dump($availableGuids); $distribution = []; foreach ($availableGuids as $product) { @@ -226,7 +230,7 @@ class MarketplaceService $koefRemain = $priority['reminder_koef']; $totalBouquets = intval($stock['count'] / $koefRemain); // С учетом коэффициента -// echo "
"; var_dump($availableGuids); var_dump($totalBouquets); var_dump($stock); die;
+         //   echo "
"; var_dump($availableGuids); var_dump($totalBouquets); var_dump($stock); die;
             if ($totalBouquets >= 2) {
                 // Равномерное распределение
                 foreach ($marketplaceStores as $store) {
@@ -250,6 +254,7 @@ class MarketplaceService
                 }
             }
         }
+      //  var_dump($distribution);
 
         return Json::encode($distribution);
     }
@@ -354,6 +359,121 @@ class MarketplaceService
     }
 
 
+    public static function getProductsInfoForFeed(int $warehouseGuid, $storeData)
+    {
+
+
+        if (is_string($storeData)) {
+            $storeData = json_decode($storeData, true);
+
+
+            if (json_last_error() !== JSON_ERROR_NONE) {
+                Yii::error('Невалидный JSON в storeData: ' . json_last_error_msg(), __METHOD__);
+                return [];
+            }
+        }
+
+
+        if (!is_array($storeData)) {
+            Yii::error('Invalid data format for storeData; expected array.', __METHOD__);
+            return [];
+        }
+
+        $store = MarketplaceStore::findOne(['warehouse_guid' => $warehouseGuid]);
+        if (!$store) {
+            Yii::error("Не найден склад для GUID {$warehouseGuid}", __METHOD__);
+            return [];
+        }
+        $storeGuid = $store->guid;
+
+
+        if (!isset($storeData[$storeGuid])) {
+            Yii::warning("Не найдено данных store GUID {$storeGuid}", __METHOD__);
+            return [];
+        }
+
+
+        $productQuantities = $storeData[$storeGuid];
+
+
+        $products = Products1c::find()
+            ->where(['id' => array_keys($productQuantities)])
+            ->andWhere(['!=', 'components', ''])
+            ->all();
+
+        $result = [];
+
+        foreach ($products as $product) {
+            $properties = MarketplaceService::getProductPropertiesByGuid($product->id);
+            if (!$properties) {
+                $message = "Товар с GUID {$product->id} не имеет свойств в MatrixErpProperty и был исключен из фида.";
+                Yii::error($message, __METHOD__);
+
+                InfoLogService::setInfoLog(
+                    __FILE__,
+                    __LINE__,
+                    $message,
+                    'Missing properties error'
+                );
+                continue;
+            }
+
+            $price = MarketplaceService::getProductPrice($product->id);
+
+            /*  if ($price == 0) {
+                $message = "У товара {$product->id} отсутствует цена и он будет исключен из фида.";
+                Yii::error($message, __METHOD__);
+
+
+                InfoLogService::setInfoLog(
+                    __FILE__,
+                    __LINE__,
+                    $message,
+                    'Zero price error'
+                );
+                continue;
+            }*/
+
+            $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' => 'шт'
+                    ];
+                }
+            }
+
+
+            $availableQty = $productQuantities[$product->id] ?? 0;
+
+            $result[] = [
+                'id' => $product->id,
+                'name' => $properties['displayName'],
+                'pictures' => [$properties['imageUrl']],
+                'price' => $price,
+                'oldprice' => MarketplaceService::getProductOldPrice($product->id),
+                'description' => MarketplaceService::getProductDescription($product->id),
+                'qty' => $availableQty,
+                'amount' => $availableQty,
+                'weight' => MarketplaceService::getProductWeight($product->id),
+                'minorder' => MarketplaceService::getProductMinOrder($product->id),
+                'composition' => $composition,
+                'available' => MarketplaceService::getProductAvailability($product->id),
+                'category_id' => MarketplaceService::getProductCategory($product->id),
+                'category_name' => $properties['flowwowSubcategory'],
+                'params' => MarketplaceService::getProductParams($product->id),
+                'productLink' => MarketplaceService::getProductLinkByGuid($product->id),
+            ];
+        }
+
+        return $result;
+    }
+
     /**
      * Статический метод для создания XML-фида на основе информации о продуктах.
      *
@@ -422,7 +542,8 @@ class MarketplaceService
 
             // Добавление веса и количества
             $offer->addChild('weight', $product['weight']);
-            //  $offer->addChild('qty', $product['qty']);
+            $offer->addChild('qty', $product['qty']);
+
             // $offer->addChild('amount', $product['amount']);
             //   $offer->addChild('cost', $product['amount']);
 
-- 
2.39.5