]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Коректировки по товарам без истории и букетам
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Wed, 21 May 2025 13:05:49 +0000 (16:05 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Wed, 21 May 2025 13:05:49 +0000 (16:05 +0300)
erp24/controllers/BouquetController.php
erp24/controllers/CategoryPlanController.php
erp24/services/AutoPlannogrammaService.php
erp24/services/StorePlanService.php
erp24/views/bouquet/month-goal-forecast.php

index f6bb6404f80146267426112adc928fdd9f9a6aa4..5bf10532d80906a2642e854e3b63664ade2fb0b3 100644 (file)
@@ -331,7 +331,7 @@ class BouquetController extends Controller
         $model->storeId = $storeId;
         $model->matrix  = $matrix;
 
-               $result = StorePlanService::getBouquetSpiecesMonthGoalFromForecast($month, $year, $storeId, $matrix);
+        $result = StorePlanService::getBouquetSpiecesMonthGoalFromForecast($month, $year, $storeId, $matrix);
 
         $stores = CityStore::find()
             ->select(['id', 'name'])
index b2b52b9dd74b709d8974934721bcba2fbac2303b..d5989dc777df280d2078499a79d80f0804fd3c0b 100644 (file)
@@ -364,7 +364,7 @@ class CategoryPlanController extends Controller {
                 }
             }
         }
-
+       // var_dump($weightedResults); die();
         return $this->render('show-history-data', [
             'result'          => $result,
             'weighted'          => $weightedResults,
index 38bc39d2213dfc82612f67a384d50161e375f2a3..4cdaf1a0b02447770d688327a2c65e2be6e78e58 100644 (file)
@@ -604,11 +604,11 @@ class AutoPlannogrammaService
 
             // ——————— WEIGHTED SALES ————————
             $t2 = hrtime(true);
-            $weightedResults = StorePlanService::calculateWeightedSalesForProductsWithoutHistory(
+            $weightedResults = StorePlanService::calculateMedianSalesForProductsWithoutHistory(
                 $storeId, $month, $year, $productsWithoutHistory
             );
             $dur = (hrtime(true) - $t2) / 1e6;
-            Yii::warning("calculateWeightedSalesForProductsWithoutHistory for store {$storeId}: {$dur} ms\n");
+            Yii::warning("calculateMedianSalesForProductsWithoutHistory for store {$storeId}: {$dur} ms\n");
 
             if (empty($weightedResults)) {
                 continue;
index 6b7208a11a7112497dc6ae68e25c9289db9be2d3..0911a597a224a47f2e2bb3828b2d8b8f06b4a1e2 100755 (executable)
@@ -497,12 +497,12 @@ class StorePlanService
             }
             $dur = (hrtime(true) - $t2) / 1e6;
             Yii::warning("calculateMedianSalesForPeriod  for product {$guid} {$storeId}: {$dur} ms\n");
-            $weights = [3, 2, 1];
+
             $t3 = hrtime(true);
-            $weightedValue = self::computeWeightedValue($medianSales, $weights);
+            $median3 = self::calculateMedianSalesOverPeriods($storeId, $similarProductIds, $periods);
 
             $weightedResults[$guid] = [
-                'weightedValue' => $weightedValue,
+                'weightedValue' => $median3,
                 'medianSales'   => $medianSales,
                 'salesValues'   => $salesValuesForEachMonth,
             ];
@@ -612,7 +612,7 @@ class StorePlanService
         $accumulator = [];
 
         foreach ($weightedProductsWithoutHistory as $guid => $info) {
-            $quantity = (float)$info['weightedValue'];
+            $quantity = (float)$info;
             if ($quantity <= 0) {
                 continue;
             }
@@ -696,6 +696,59 @@ class StorePlanService
         return $query->column();
     }
 
+
+    public static function calculateMedianSalesForProductsWithoutHistory(
+        int $storeId,
+        int $selectedMonth,
+        int $selectedYear,
+        array $productsWithoutHistory
+    ): array {
+        $targetDate = strtotime("{$selectedYear}-{$selectedMonth}-01");
+        $periods    = self::getPeriods($targetDate, 3);
+
+        $results = [];
+        foreach ($productsWithoutHistory as $prod) {
+            $guid = $prod['guid'];
+            $similar = self::getSimilarProductIDs($guid);
+            if (empty($similar)) {
+                $results[$guid] = 0;
+                continue;
+            }
+
+            $median3 = self::calculateMedianSalesOverPeriods($storeId, $similar, $periods);
+            $results[$guid] = $median3;
+        }
+
+        return $results;
+    }
+
+    private static function calculateMedianSalesOverPeriods(int $storeId, array $similarProductIds, array $periods): float
+    {
+        $allValues = [];
+        foreach ($periods as $monthInfo) {
+            list(, $salesValues) = self::calculateMedianSalesForPeriod(
+                $storeId,
+                $similarProductIds,
+                $monthInfo
+            );
+            $allValues = array_merge($allValues, $salesValues);
+        }
+        $filtered = array_filter($allValues, fn($v) => $v > 0);
+
+        sort($filtered, SORT_NUMERIC);
+        $n = count($filtered);
+        if ($n === 0) {
+            return 0.0;
+        }
+        $mid = (int) floor($n / 2);
+        if ($n % 2 === 1) {
+            return $filtered[$mid];
+        }
+        return ($filtered[$mid - 1] + $filtered[$mid]) / 2;
+    }
+
+
+
     /**
      * Вычисляет медианное значение продаж для похожих товаров в заданном периоде.
      *
@@ -714,19 +767,6 @@ class StorePlanService
             $monthInfo['month'],
             cal_days_in_month(CAL_GREGORIAN, $monthInfo['month'], $monthInfo['year']));
 
-/*        $salesValues = [];
-
-        foreach ($similarProductIds as $simProdId) {
-            $sales = Sales::find()->alias('s')
-                ->innerJoin('sales_products sp', 's.id = sp.check_id')
-                ->innerJoin('products_1c_nomenclature p1c', 'p1c.id = sp.product_id')
-                ->where(['p1c.id' => $simProdId])
-                ->andWhere(['s.store_id' => $storeId])
-                ->andWhere(['between', 's.date', $startDate . ' 00:00:00', $endDate . ' 23:59:59'])
-                ->andWhere(['order_id' => ['', '0']])
-                ->count();
-            $salesValues[] = (int)$sales;
-        }*/
         $initTime = (hrtime(true) - $t0) / 1e6; // миллисекунды
         Yii::warning( "Init (calculateMedianSalesForPeriod): {$initTime} ms\n");
         $t1 = hrtime(true);
index 6b329a848831ccbbc47549f405ebe64acdd15656..ea8d4b5c04a86a55d9b12dcdee30660a3dfa5ce8 100644 (file)
@@ -20,6 +20,26 @@ $saleTypesLabels = [
     3 => 'Маркетплейсы',
 ];
 
+$finalResult = [];
+if ($result['final']) {
+    foreach ($result['final'] as $storeId => $categoryData) {
+        foreach ($categoryData as $category => $subcategoryData) {
+            foreach ($subcategoryData as $subcategory => $speciesData) {
+                foreach ($speciesData as $species => $salesData) {
+                    $finalResult[$storeId][] = [
+
+                        'category' =>$category,
+                        'subcategory' =>$subcategory,
+                        'species' =>$species,
+                        'goal' =>$salesData,
+                        ];
+                }
+            }
+        }
+
+    }
+}
+
 ?>
 <div class="show-goal p-4">
     <h1>Цели букета на месяц: <?= Html::encode($month) ?>/<?= Html::encode($year) ?></h1>
@@ -57,19 +77,18 @@ $saleTypesLabels = [
 
     <h2>Финальные суммы по магазинам</h2>
 <?php if (!empty($result['final'])): ?>
-    <?php foreach ($result['final'] as $storeId => $speciesData): ?>
+    <?php foreach ($finalResult as $storeId => $speciesData): ?>
         <h3>Магазин: <?= Html::encode($storesMap[$storeId] ?? $storeId) ?></h3>
         <?= GridView::widget([
             'dataProvider' => new ArrayDataProvider([
-                'allModels' => array_map(fn($species, $sum) => [
-                    'species' => $species,
-                    'sum'     => $sum,
-                ], array_keys($speciesData), $speciesData),
+                'allModels' => $speciesData,
                 'pagination' => false,
             ]),
             'columns' => [
+                ['attribute' => 'category', 'label' => 'Категория'],
+                ['attribute' => 'subcategory', 'label' => 'Подкатегория'],
                 ['attribute' => 'species', 'label' => 'Вид продукции'],
-                ['attribute' => 'sum',     'label' => 'Сумма'],
+                ['attribute' => 'goal',     'label' => 'Сумма', 'format' => ['decimal', 2]],
             ],
         ]) ?>
     <?php endforeach; ?>