}
$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,
];
$accumulator = [];
foreach ($weightedProductsWithoutHistory as $guid => $info) {
- $quantity = (float)$info['weightedValue'];
+ $quantity = (float)$info;
if ($quantity <= 0) {
continue;
}
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;
+ }
+
+
+
/**
* Вычисляет медианное значение продаж для похожих товаров в заданном периоде.
*
$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);
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>
<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; ?>