Skip to content

Commit ac9fe76

Browse files
committed
Fixed the ‘new customers’ widget query
1 parent 01b02fd commit ac9fe76

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Release Notes for Craft Commerce
22

3+
## Unreleased
4+
5+
- Fixed a bug where the "New Customers" stat was counting all customers with orders in the date range, rather than only customers whose first order was in the date range.
6+
37
## 5.5.1 - 2025-12-04
48

59
- Added `craft\commerce\models\CatalogPricingRule::afterPreparePurchasableQuery()`.

src/stats/NewCustomers.php

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@
88
namespace craft\commerce\stats;
99

1010
use craft\commerce\base\Stat;
11+
use craft\commerce\db\Table;
12+
use craft\db\Query;
13+
use craft\helpers\Db;
1114
use yii\db\Expression;
1215

1316
/**
14-
* Total Orders Stat
17+
* New Customers Stat
1518
*
1619
* @author Pixel & Tonic, Inc. <[email protected]>
1720
* @since 3.0
@@ -29,7 +32,18 @@ class NewCustomers extends Stat
2932
public function getData(): string|int|bool|null
3033
{
3134
$query = $this->_createStatQuery();
32-
$query->select([new Expression('COUNT(DISTINCT [[customerId]]) as newCustomers')]);
35+
36+
// Subquery to find customers who have orders before the start date
37+
$existingCustomersQuery = (new Query())
38+
->select(['customerId'])
39+
->from(Table::ORDERS)
40+
->where(['isCompleted' => true])
41+
->andWhere(['not', ['customerId' => null]])
42+
->andWhere(['<', 'dateOrdered', Db::prepareDateForDb($this->getStartDate())]);
43+
44+
$query->select([new Expression('COUNT(DISTINCT [[customerId]]) as newCustomers')])
45+
->andWhere(['not', ['customerId' => null]])
46+
->andWhere(['not in', 'customerId', $existingCustomersQuery]);
3347

3448
return $query->scalar();
3549
}

0 commit comments

Comments
 (0)