'total_sum' => 'main.total_sum',
'percent' => new Expression('ROUND(CAST(main.total_sum AS DECIMAL) / NULLIF(totals.total, 0), 4)'),
'type' => new Expression(':type', ['type' => $type]),
+ 'totals_total' => 'totals.total'
])
->from([
'main' => (new Query())
->andWhere(['<=', "$alias.date", (new \DateTime($month3 . '-01'))->modify('last day of this month')->format('Y-m-d')])
->groupBy(['ex.entity_id']),
], 'main.ex_entity_id = totals.store_id')
- ->orderBy('category');
+ ->orderBy('category');
// Выполнение запроса и форматирование
$rows = $query->all();
- $result = [];
- foreach ($rows as $row) {
- $storeId = $row['store_id'];
- $result[$storeId][] = [
- 'category' => $row['category'],
- 'total_sum' => $row['total_sum'],
- 'percent' => $row['percent'],
- 'type' => $row['type'],
+ $months = [$month3 => 3];
+ $months[$month2] = 2;
+ $months[$month1] = 1;
+
+ $componentAdds = [];
+ $componentAddsSumAll = [];
+
+ foreach ($storeIds as $storeId) {
+ foreach ($months as $m => $weight) {
+ [$year, $mon] = explode('-', $m);
+ $items = $this->getUnmarkedProductsComponents(
+ (int)$storeId,
+ (int)$mon,
+ (int)$year,
+ $type
+ );
+ $sums = $this->sumUnmarkedProductsComponentsByCategory($items, $type);
+
+ foreach ($sums as $sumRow) {
+ $sid = $sumRow['store_id'];
+ $cat = $sumRow['category'];
+ $val = $sumRow['sum'] * $weight;
+
+ $componentAdds[$sid][$cat] = ($componentAdds[$sid][$cat] ?? 0) + $val;
+ $componentAddsSumAll[$sid] = ($componentAddsSumAll[$sid] ?? 0) + $val;
+ }
+ }
+ }
+
+ $result = [];
+ foreach ($rows as $r) {
+ $sid = $r['store_id'];
+ $baseTotal = (float)$r['totals_total'];
+ $addAllCategories = $componentAddsSumAll[$sid] ?? 0.0;
+ $newDenominator = $baseTotal + $addAllCategories;
+
+ $newTotal = (float)$r['total_sum']
+ + ($componentAdds[$sid][$r['category']] ?? 0);
+ $percent = $newDenominator > 0
+ ? round($newTotal / $newDenominator, 4)
+ : 0.0;
+
+ $result[$sid][] = [
+ 'category' => $r['category'],
+ 'total_sum' => $newTotal,
+ 'percent' => $percent,
+ 'type' => $r['type'],
+ 'new_total_store' => $newDenominator,
+ 'base_total_store' => $baseTotal
];
}
return CityStore::findOne($data['store_id'])->name ?? null;
}],
['attribute' => 'category', 'label' => 'Категория'],
- ['attribute' => 'total_sum', 'label' => 'Сумма', 'format' => ['decimal', 2]],
+ ['attribute' => 'base_total_store', 'label' => 'Сумма продаж', 'format' => ['decimal', 2]],
+ ['attribute' => 'new_total_store', 'label' => 'Сумма с немаркированными', 'format' => ['decimal', 2]],
+ ['attribute' => 'total_sum', 'label' => 'Сумма категории', 'format' => ['decimal', 2]],
['attribute' => 'percent', 'label' => 'Доля', 'format' => ['percent', 2]],
],
]); ?>