$where = implode(' AND ', $conditions);
$query = Yii::$app->db->createCommand("
- SELECT
- c.name AS city_name,
- p1.name AS product_name,
- p1.category,
- p1.subcategory,
- SUM(sp.quantity) AS count,
- SUM(sp.summ) AS sum
- FROM sales s
- LEFT JOIN sales_products sp ON sp.check_id = s.id
- LEFT JOIN products_1c_nomenclature p1 ON p1.id = sp.product_id
- LEFT JOIN export_import_table ex ON ex.export_val = store_id_1c
- LEFT JOIN city_store c ON c.id = entity_id
- WHERE $where
- GROUP BY p1.name, p1.category, p1.subcategory, c.name, c.id
- ORDER BY c.id DESC, category, subcategory, p1.name
- ")->bindValues($params)->queryAll();
+ SELECT
+ c.name AS city_name,
+ p1.name AS product_name,
+ p1.category,
+ p1.subcategory,
+ SUM(CASE
+ WHEN s.operation = 'Продажа' THEN sp.quantity
+ WHEN s.operation = 'Возврат' THEN -sp.quantity
+ ELSE 0
+ END) AS count,
+ SUM(CASE
+ WHEN s.operation = 'Продажа' THEN sp.summ
+ WHEN s.operation = 'Возврат' THEN -sp.summ
+ ELSE 0
+ END) AS sum
+ FROM sales s
+ LEFT JOIN sales_products sp ON sp.check_id = s.id
+ LEFT JOIN products_1c_nomenclature p1 ON p1.id = sp.product_id
+ LEFT JOIN export_import_table ex ON ex.export_val = store_id_1c
+ LEFT JOIN city_store c ON c.id = entity_id
+ WHERE $where
+ GROUP BY p1.name, p1.category, p1.subcategory, c.name, c.id
+ ORDER BY c.id DESC, category, subcategory, p1.name
+")->bindValues($params)->queryAll();
$dataProvider = new ArrayDataProvider([
'allModels' => $query,
return CityStore::findAll(['visible' => CityStore::IS_VISIBLE]);
}
- private function getStoreSalesTotals(array $storeIds, $dateFrom, $productFilter = null): array
+ private function getStoreSalesTotals(array $storeIds, string $dateFrom, $productFilter = null): array
{
$query = (new Query())
->select([
'store_id' => 'ex.entity_id',
- 'total_sum' => new Expression('SUM(sp.summ)')
+ 'total_sum' => new Expression("
+ SUM(CASE
+ WHEN s.operation = 'Продажа' THEN sp.summ
+ WHEN s.operation = 'Возврат' THEN -sp.summ
+ ELSE 0
+ END)
+ ")
])
->from(['s' => 'sales'])
->leftJoin('sales_products sp', 'sp.check_id = s.id')
->leftJoin('export_import_table ex', 'ex.export_val = s.store_id_1c')
->where(['>=', 's.date', $dateFrom])
+ ->andWhere(['ex.entity_id' => $storeIds])
->groupBy('ex.entity_id');
if ($productFilter !== null) {
$rows = $query->all();
$totals = [];
+
foreach ($rows as $row) {
- $totals[$row['store_id']] = $row['total_sum'];
+ $totals[(int)$row['store_id']] = (float)$row['total_sum'];
}
return $totals;