Commit 2333c1d17b0 for woocommerce
commit 2333c1d17b02bd0e2f37b9b42fdf57b684686daa
Author: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
Date: Wed Nov 25 12:11:10 2026 +0200
Add a Stock notifications report to Analytics (#69024)
* feat: add a Stock notifications report to Analytics
* fix: inherit the default per_page from the reports base class
* refactor: invalidate the shared reports cache on stock notification writes
* fix: give the stats store a PHPStan-resolvable get_noncached_data return type
* fix: gate the stock notifications report on the feature flag, keep is_enabled() private
* fix: resolve PHPStan return types for the stock notifications stats store
Qualify the stdClass|WP_Error return type on StatsDataStoreTrait so PHPStan
resolves it in every namespace that uses the trait, and drop the wrapper the
stock notifications stats store only had to work around that. Regenerate the
baseline: the six existing stats stores lose their now-fixed entries. Also
apply trunk's prettier formatting to use-reports.js.
* fix: register the stock notifications report data stores only when the feature is enabled
The woocommerce_data_stores filter can run before init, where
feature_is_enabled() would build the translated feature definitions too
early. StockNotifications::register_data_stores() already avoids that by
reading the feature option directly; expose that check as
is_enabled_before_init() and gate the two report data stores on it too.
* refactor: keep the stock notifications report date-bound
* fix: enable stock notifications CSV export and narrow report cache busting
* fix: refresh the analytics cache when a notification changes product or email
* fix: keep multi-word report table titles on one line
* feat: show notified and unsubscribed per product in the stock notifications report
* fix: address review feedback on the stock notifications report columns
* feat: align the stock notifications report tiles, columns and summary
* fix: address quick review feedback on the stock notifications report
- Show a rise in unsubscribes as a negative trend.
- Drop products_count from the interval subtotals schema; it is totals-only.
- Stop busting the reports cache on email-only edits.
- Fix the translator comment for deleted products.
- Cover cache invalidation on delete, real sort order with a tie, and export column keys.
* fix: read the new stock notification ID before invalidating the reports cache
Invalidating the reports cache can add an option row, which overwrites
$wpdb->insert_id, so a new notification could be saved under the wrong ID.
Also give the report controller tests a fresh REST server per test, since
routes depend on the feature option, and split a keyed test array across lines.
* feat: replace unsubscribes with customers in the stock notifications report
* feat: add a Customers tooltip to the stock notifications report
* perf: narrow the stock notifications date_created index to one column
* fix: name stock notification exports in emails and scope the report cache
diff --git a/plugins/woocommerce/changelog/add-wooplug-7570-stock-notifications-analytics-report b/plugins/woocommerce/changelog/add-wooplug-7570-stock-notifications-analytics-report
new file mode 100644
index 00000000000..ca1aa774bde
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-wooplug-7570-stock-notifications-analytics-report
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add a Stock notifications report to Analytics showing back-in-stock sign-ups, notifications sent and customers.
diff --git a/plugins/woocommerce/client/admin/client/analytics/components/report-table/style.scss b/plugins/woocommerce/client/admin/client/analytics/components/report-table/style.scss
index 6a77e8d3877..479e63dbc38 100644
--- a/plugins/woocommerce/client/admin/client/analytics/components/report-table/style.scss
+++ b/plugins/woocommerce/client/admin/client/analytics/components/report-table/style.scss
@@ -23,7 +23,7 @@
.components-card__header {
display: grid;
grid-gap: $gap-small;
- grid-template-columns: min-content 1fr min-content;
+ grid-template-columns: auto 1fr min-content;
}
.woocommerce-table__compare.components-button {
diff --git a/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/config.js b/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/config.js
new file mode 100644
index 00000000000..14f56a353a1
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/config.js
@@ -0,0 +1,106 @@
+/**
+ * External dependencies
+ */
+import { __, _x } from '@wordpress/i18n';
+import { applyFilters } from '@wordpress/hooks';
+
+const STOCK_NOTIFICATIONS_REPORT_CHARTS_FILTER =
+ 'woocommerce_admin_stock_notifications_report_charts';
+const STOCK_NOTIFICATIONS_REPORT_FILTERS_FILTER =
+ 'woocommerce_admin_stock_notifications_report_filters';
+const STOCK_NOTIFICATIONS_REPORT_ADVANCED_FILTERS_FILTER =
+ 'woocommerce_admin_stock_notifications_report_advanced_filters';
+
+/**
+ * @typedef {import('../index.js').chart} chart
+ */
+
+/**
+ * Stock Notifications Report charts filter.
+ *
+ * @filter woocommerce_admin_stock_notifications_report_charts
+ * @param {Array.<chart>} charts Report charts.
+ */
+export const charts = applyFilters( STOCK_NOTIFICATIONS_REPORT_CHARTS_FILTER, [
+ {
+ key: 'signups',
+ label: __( 'Sign-ups', 'woocommerce' ),
+ order: 'desc',
+ orderby: 'signups',
+ type: 'number',
+ },
+ {
+ key: 'notifications_sent',
+ label: __( 'Notifications sent', 'woocommerce' ),
+ order: 'desc',
+ orderby: 'notifications_sent',
+ type: 'number',
+ },
+ {
+ key: 'customers',
+ label: __( 'Customers', 'woocommerce' ),
+ order: 'desc',
+ orderby: 'customers',
+ type: 'number',
+ labelTooltipText: __(
+ 'Unique customers who signed up in the selected period.',
+ 'woocommerce'
+ ),
+ },
+] );
+
+/**
+ * Stock Notifications Report Advanced Filters.
+ *
+ * @filter woocommerce_admin_stock_notifications_report_advanced_filters
+ * @param {Object} advancedFilters Report Advanced Filters.
+ * @param {string} advancedFilters.title Interpolated component string for Advanced Filters title.
+ * @param {Object} advancedFilters.filters An object specifying a report's Advanced Filters.
+ */
+export const advancedFilters = applyFilters(
+ STOCK_NOTIFICATIONS_REPORT_ADVANCED_FILTERS_FILTER,
+ {
+ filters: {},
+ title: _x(
+ 'Stock notifications match <select/> filters',
+ 'A sentence describing filters for Stock notifications. See screen shot for context: https://cloudup.com/cSsUY9VeCVJ',
+ 'woocommerce'
+ ),
+ }
+);
+
+const filterValues = [];
+
+if ( Object.keys( advancedFilters.filters ).length ) {
+ filterValues.push( {
+ label: __( 'All products', 'woocommerce' ),
+ value: 'all',
+ } );
+ filterValues.push( {
+ label: __( 'Advanced filters', 'woocommerce' ),
+ value: 'advanced',
+ } );
+}
+
+/**
+ * @typedef {import('../index.js').filter} filter
+ */
+
+/**
+ * Stock Notifications Report Filters.
+ *
+ * @filter woocommerce_admin_stock_notifications_report_filters
+ * @param {Array.<filter>} filters Report filters.
+ */
+export const filters = applyFilters(
+ STOCK_NOTIFICATIONS_REPORT_FILTERS_FILTER,
+ [
+ {
+ label: __( 'Show', 'woocommerce' ),
+ staticParams: [ 'chartType', 'paged', 'per_page' ],
+ param: 'filter',
+ showFilters: () => filterValues.length > 0,
+ filters: filterValues,
+ },
+ ]
+);
diff --git a/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/index.js b/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/index.js
new file mode 100644
index 00000000000..bcea5874fc2
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/index.js
@@ -0,0 +1,69 @@
+/**
+ * External dependencies
+ */
+import { Component, Fragment } from '@wordpress/element';
+import PropTypes from 'prop-types';
+import { __ } from '@wordpress/i18n';
+
+/**
+ * Internal dependencies
+ */
+import { advancedFilters, charts, filters } from './config';
+import StockNotificationsReportTable from './table';
+import getSelectedChart from '../../../lib/get-selected-chart';
+import ReportChart from '../../components/report-chart';
+import ReportSummary from '../../components/report-summary';
+import { ReportHeader } from '../../components/report-header';
+
+class StockNotificationsReport extends Component {
+ render() {
+ const { isRequesting, query, path } = this.props;
+ const selectedChart = getSelectedChart( query.chart, charts );
+ /* translators: %d: number of sign-ups */
+ const itemsLabel = __( '%d sign-ups', 'woocommerce' );
+
+ return (
+ <Fragment>
+ <ReportHeader
+ query={ query }
+ path={ path }
+ filters={ filters }
+ advancedFilters={ advancedFilters }
+ report="stock-notifications"
+ />
+ <ReportSummary
+ charts={ charts }
+ endpoint="stock-notifications"
+ query={ query }
+ selectedChart={ selectedChart }
+ filters={ filters }
+ advancedFilters={ advancedFilters }
+ />
+ <ReportChart
+ charts={ charts }
+ filters={ filters }
+ advancedFilters={ advancedFilters }
+ mode="time-comparison"
+ endpoint="stock-notifications"
+ path={ path }
+ query={ query }
+ isRequesting={ isRequesting }
+ itemsLabel={ itemsLabel }
+ selectedChart={ selectedChart }
+ />
+ <StockNotificationsReportTable
+ isRequesting={ isRequesting }
+ query={ query }
+ filters={ filters }
+ advancedFilters={ advancedFilters }
+ />
+ </Fragment>
+ );
+ }
+}
+
+StockNotificationsReport.propTypes = {
+ query: PropTypes.object.isRequired,
+};
+
+export default StockNotificationsReport;
diff --git a/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/table.js b/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/table.js
new file mode 100644
index 00000000000..6f34859b553
--- /dev/null
+++ b/plugins/woocommerce/client/admin/client/analytics/report/stock-notifications/table.js
@@ -0,0 +1,172 @@
+/**
+ * External dependencies
+ */
+import { __, _n } from '@wordpress/i18n';
+import { Component } from '@wordpress/element';
+import { decodeEntities } from '@wordpress/html-entities';
+import { map } from 'lodash';
+import { Link } from '@woocommerce/components';
+import { formatValue } from '@woocommerce/number';
+import { CurrencyContext } from '@woocommerce/currency';
+
+/**
+ * Internal dependencies
+ */
+import ReportTable from '../../components/report-table';
+
+class StockNotificationsReportTable extends Component {
+ constructor() {
+ super();
+
+ this.getHeadersContent = this.getHeadersContent.bind( this );
+ this.getRowsContent = this.getRowsContent.bind( this );
+ this.getSummary = this.getSummary.bind( this );
+ }
+
+ getHeadersContent() {
+ return [
+ {
+ label: __( 'Product', 'woocommerce' ),
+ key: 'product_id',
+ required: true,
+ isLeftAligned: true,
+ isSortable: false,
+ },
+ {
+ label: __( 'Sign-ups', 'woocommerce' ),
+ key: 'signups',
+ required: true,
+ defaultSort: true,
+ defaultOrder: 'desc',
+ isSortable: true,
+ isNumeric: true,
+ },
+ {
+ label: __( 'Notifications sent', 'woocommerce' ),
+ key: 'notifications_sent',
+ isSortable: true,
+ isNumeric: true,
+ },
+ {
+ label: __( 'Customers', 'woocommerce' ),
+ key: 'customers',
+ isSortable: true,
+ isNumeric: true,
+ },
+ ];
+ }
+
+ getRowsContent( rows ) {
+ const currency = this.context.getCurrencyConfig();
+ const formatNumber = ( value ) =>
+ formatValue( currency, 'number', value );
+
+ return map( rows, ( row ) => {
+ const {
+ signups,
+ notifications_sent: notificationsSent,
+ customers,
+ } = row;
+ const { edit_url: editUrl } = row.extended_info || {};
+ const name = decodeEntities( row.extended_info?.name || '' );
+
+ return [
+ {
+ display: editUrl ? (
+ <Link href={ editUrl } type="wp-admin">
+ { name }
+ </Link>
+ ) : (
+ name
+ ),
+ value: name,
+ },
+ {
+ display: formatNumber( signups ),
+ value: signups,
+ },
+ {
+ display: formatNumber( notificationsSent ),
+ value: notificationsSent,
+ },
+ {
+ display: formatNumber( customers ),
+ value: customers,
+ },
+ ];
+ } );
+ }
+
+ getSummary( totals ) {
+ const {
+ products_count: productsCount = 0,
+ signups = 0,
+ notifications_sent: notificationsSent = 0,
+ customers = 0,
+ } = totals;
+ const currency = this.context.getCurrencyConfig();
+ return [
+ {
+ label: _n(
+ 'Product',
+ 'Products',
+ productsCount,
+ 'woocommerce'
+ ),
+ value: formatValue( currency, 'number', productsCount ),
+ },
+ {
+ label: _n( 'Sign-up', 'Sign-ups', signups, 'woocommerce' ),
+ value: formatValue( currency, 'number', signups ),
+ },
+ {
+ label: _n(
+ 'Notification sent',
+ 'Notifications sent',
+ notificationsSent,
+ 'woocommerce'
+ ),
+ value: formatValue( currency, 'number', notificationsSent ),
+ },
+ {
+ label: _n( 'Customer', 'Customers', customers, 'woocommerce' ),
+ value: formatValue( currency, 'number', customers ),
+ },
+ ];
+ }
+
+ render() {
+ const { advancedFilters, filters, isRequesting, query } = this.props;
+
+ return (
+ <ReportTable
+ endpoint="stock-notifications"
+ getHeadersContent={ this.getHeadersContent }
+ getRowsContent={ this.getRowsContent }
+ getSummary={ this.getSummary }
+ summaryFields={ [
+ 'products_count',
+ 'signups',
+ 'notifications_sent',
+ 'customers',
+ ] }
+ isRequesting={ isRequesting }
+ itemIdField="product_id"
+ query={ query }
+ tableQuery={ {
+ orderby: query.orderby || 'signups',
+ order: query.order || 'desc',
+ extended_info: true,
+ } }
+ title={ __( 'Stock notifications', 'woocommerce' ) }
+ columnPrefsKey="stock_notifications_report_columns"
+ filters={ filters }
+ advancedFilters={ advancedFilters }
+ />
+ );
+ }
+}
+
+StockNotificationsReportTable.contextType = CurrencyContext;
+
+export default StockNotificationsReportTable;
diff --git a/plugins/woocommerce/client/admin/client/analytics/report/use-reports.js b/plugins/woocommerce/client/admin/client/analytics/report/use-reports.js
index ef5ffff6741..10156a0e1ae 100644
--- a/plugins/woocommerce/client/admin/client/analytics/report/use-reports.js
+++ b/plugins/woocommerce/client/admin/client/analytics/report/use-reports.js
@@ -9,6 +9,7 @@ import { lazy, Fragment } from '@wordpress/element';
* Internal dependencies
*/
import { getAdminSetting } from '~/utils/admin-settings';
+import { isFeatureEnabled } from '~/utils/features';
import { useFilterHook } from '~/utils/use-filter-hook';
import { ScheduledUpdatesPromotionNotice } from '~/analytics/components';
@@ -53,6 +54,12 @@ const DownloadsReport = lazy(
const StockReport = lazy(
() => import( /* webpackChunkName: "analytics-report-stock" */ './stock' )
);
+const StockNotificationsReport = lazy(
+ () =>
+ import(
+ /* webpackChunkName: "analytics-report-stock-notifications" */ './stock-notifications'
+ )
+);
const CustomersReport = lazy(
() =>
import(
@@ -131,6 +138,16 @@ const getReports = () => {
},
}
: null,
+ isFeatureEnabled( 'customer_stock_notifications' )
+ ? {
+ report: 'stock-notifications',
+ title: __( 'Stock notifications', 'woocommerce' ),
+ component: StockNotificationsReport,
+ navArgs: {
+ id: 'woocommerce-analytics-stock-notifications',
+ },
+ }
+ : null,
{
report: 'customers',
title: __( 'Customers', 'woocommerce' ),
diff --git a/plugins/woocommerce/src/Admin/API/Init.php b/plugins/woocommerce/src/Admin/API/Init.php
index 95050d88e54..d45ef5d4cab 100644
--- a/plugins/woocommerce/src/Admin/API/Init.php
+++ b/plugins/woocommerce/src/Admin/API/Init.php
@@ -7,6 +7,7 @@ namespace Automattic\WooCommerce\Admin\API;
use AllowDynamicProperties;
use Automattic\WooCommerce\Admin\Features\Features;
+use Automattic\WooCommerce\Internal\StockNotifications\StockNotifications;
use Automattic\WooCommerce\Utilities\FeaturesUtil;
defined( 'ABSPATH' ) || exit;
@@ -186,6 +187,11 @@ class Init {
'Automattic\WooCommerce\Admin\API\Reports\Customers\Stats\Controller',
);
+ if ( StockNotifications::is_enabled_before_init() ) {
+ $analytics_controllers[] = 'Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Controller';
+ $analytics_controllers[] = 'Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Stats\Controller';
+ }
+
// Registered whenever analytics is enabled (not gated on the
// scheduled-import feature): the status endpoint reports failed
// order imports in both immediate and scheduled modes.
@@ -230,7 +236,7 @@ class Init {
* @return array
*/
public static function add_data_stores( $data_stores ) {
- return array_merge(
+ $data_stores = array_merge(
$data_stores,
array(
'report-revenue-stats' => 'Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore',
@@ -253,6 +259,14 @@ class Init {
'report-stock-stats' => 'Automattic\WooCommerce\Admin\API\Reports\Stock\Stats\DataStore',
)
);
+
+ // This filter can run before `init`, so check the feature without the features controller.
+ if ( StockNotifications::is_enabled_before_init() ) {
+ $data_stores['report-stock-notifications'] = 'Automattic\WooCommerce\Admin\API\Reports\StockNotifications\DataStore';
+ $data_stores['report-stock-notifications-stats'] = 'Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Stats\DataStore';
+ }
+
+ return $data_stores;
}
/**
diff --git a/plugins/woocommerce/src/Admin/API/Reports/Export/Controller.php b/plugins/woocommerce/src/Admin/API/Reports/Export/Controller.php
index ebf02a7a06e..1c1991be5c1 100644
--- a/plugins/woocommerce/src/Admin/API/Reports/Export/Controller.php
+++ b/plugins/woocommerce/src/Admin/API/Reports/Export/Controller.php
@@ -27,7 +27,7 @@ class Controller extends \Automattic\WooCommerce\Admin\API\Reports\Controller {
*
* @var string
*/
- protected $rest_base = 'reports/(?P<type>[a-z]+)/export';
+ protected $rest_base = 'reports/(?P<type>[a-z-]+)/export';
/**
* Register routes.
diff --git a/plugins/woocommerce/src/Admin/API/Reports/StatsDataStoreTrait.php b/plugins/woocommerce/src/Admin/API/Reports/StatsDataStoreTrait.php
index 6ba3da99da3..d189a9b0aff 100644
--- a/plugins/woocommerce/src/Admin/API/Reports/StatsDataStoreTrait.php
+++ b/plugins/woocommerce/src/Admin/API/Reports/StatsDataStoreTrait.php
@@ -28,7 +28,7 @@ use Automattic\WooCommerce\Admin\API\Reports\SqlQuery;
* // ...
* /**
* * Return your results with the help of the interval & total methods and queries.
- * * @return stdClass|WP_Error $data filled with your results.
+ * * @return \stdClass|\WP_Error $data filled with your results.
* */
* public function get_noncached_stats_data( $query_args, $params, &$data, $expected_interval_count ) {
* $this->initialize_queries();
diff --git a/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Controller.php b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Controller.php
new file mode 100644
index 00000000000..fbbc4299642
--- /dev/null
+++ b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Controller.php
@@ -0,0 +1,248 @@
+<?php
+/**
+ * REST API Reports stock notifications controller
+ *
+ * Handles requests to the /reports/stock-notifications endpoint.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Admin\API\Reports\StockNotifications;
+
+defined( 'ABSPATH' ) || exit;
+
+use Automattic\WooCommerce\Admin\API\Reports\ExportableInterface;
+use Automattic\WooCommerce\Admin\API\Reports\GenericController;
+use Automattic\WooCommerce\Admin\API\Reports\GenericQuery;
+use WP_REST_Request;
+use WP_REST_Response;
+
+/**
+ * REST API Reports stock notifications controller class.
+ *
+ * @internal
+ */
+class Controller extends GenericController implements ExportableInterface {
+
+ /**
+ * Route base.
+ *
+ * @var string
+ */
+ protected $rest_base = 'reports/stock-notifications';
+
+ /**
+ * Get data from `'stock-notifications'` GenericQuery.
+ *
+ * @override GenericController::get_datastore_data()
+ *
+ * @param array $query_args Query arguments.
+ * @return mixed Results from the data store.
+ */
+ protected function get_datastore_data( $query_args = array() ) {
+ $query = new GenericQuery( $query_args, 'stock-notifications' );
+ return $query->get_data();
+ }
+
+ /**
+ * Maps query arguments from the REST request.
+ *
+ * @param WP_REST_Request<array<string, mixed>> $request Request array.
+ * @return array
+ */
+ protected function prepare_reports_query( $request ) {
+ $args = array();
+ $args['before'] = $request['before'];
+ $args['after'] = $request['after'];
+ $args['page'] = $request['page'];
+ $args['per_page'] = $request['per_page'];
+ $args['orderby'] = $request['orderby'];
+ $args['order'] = $request['order'];
+ $args['product_includes'] = (array) $request['products'];
+ $args['extended_info'] = $request['extended_info'];
+ $args['force_cache_refresh'] = $request['force_cache_refresh'];
+ return $args;
+ }
+
+ /**
+ * Prepare a report data item for serialization.
+ *
+ * @param array $report Report data item as returned from Data Store.
+ * @param WP_REST_Request<array<string, mixed>> $request Request object.
+ * @return WP_REST_Response
+ */
+ public function prepare_item_for_response( $report, $request ) {
+ $response = parent::prepare_item_for_response( $report, $request );
+ $response->add_links( $this->prepare_links( $report ) );
+
+ /**
+ * Filter a stock notifications report item returned from the API.
+ *
+ * @since 11.4.0
+ *
+ * @param WP_REST_Response $response The response object.
+ * @param array $report The original report item.
+ * @param WP_REST_Request $request Request used to generate the response.
+ */
+ return apply_filters( 'woocommerce_rest_prepare_report_stock_notifications', $response, $report, $request );
+ }
+
+ /**
+ * Prepare links for the request.
+ *
+ * @param array $report Report data item.
+ * @return array
+ */
+ protected function prepare_links( $report ) {
+ return array(
+ 'product' => array(
+ 'href' => rest_url( sprintf( '/%s/products/%d', $this->namespace, $report['product_id'] ) ),
+ ),
+ );
+ }
+
+ /**
+ * Get the Report's schema, conforming to JSON Schema.
+ *
+ * @return array
+ */
+ public function get_item_schema() {
+ $schema = array(
+ '$schema' => 'http://json-schema.org/draft-04/schema#',
+ 'title' => 'report_stock_notifications',
+ 'type' => 'object',
+ 'properties' => array(
+ 'product_id' => array(
+ 'description' => __( 'ID of the product or variation customers signed up for.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'signups' => array(
+ 'description' => __( 'Sign-ups created in the period. Excludes unconfirmed (pending) sign-ups.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'notifications_sent' => array(
+ 'description' => __( 'Back-in-stock emails sent in the period.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'customers' => array(
+ 'description' => __( 'Distinct customers, by email, who signed up in the period.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'extended_info' => array(
+ 'name' => array(
+ 'type' => 'string',
+ 'readonly' => true,
+ 'context' => array( 'view', 'edit' ),
+ 'description' => __( 'Product name.', 'woocommerce' ),
+ ),
+ 'permalink' => array(
+ 'type' => 'string',
+ 'readonly' => true,
+ 'context' => array( 'view', 'edit' ),
+ 'description' => __( 'Product link.', 'woocommerce' ),
+ ),
+ 'edit_url' => array(
+ 'type' => 'string',
+ 'readonly' => true,
+ 'context' => array( 'view', 'edit' ),
+ 'description' => __( 'Product edit link.', 'woocommerce' ),
+ ),
+ ),
+ ),
+ );
+
+ return $this->add_additional_fields_schema( $schema );
+ }
+
+ /**
+ * Get the query params for collections.
+ *
+ * @return array
+ */
+ public function get_collection_params() {
+ $params = parent::get_collection_params();
+ $params['orderby']['default'] = 'signups';
+ $params['orderby']['enum'] = $this->apply_custom_orderby_filters(
+ array(
+ 'product_id',
+ 'signups',
+ 'notifications_sent',
+ 'customers',
+ )
+ );
+ $params['products'] = array(
+ 'description' => __( 'Limit result to items with specified product ids.', 'woocommerce' ),
+ 'type' => 'array',
+ 'sanitize_callback' => 'wp_parse_id_list',
+ 'validate_callback' => 'rest_validate_request_arg',
+ 'items' => array(
+ 'type' => 'integer',
+ ),
+ );
+ $params['extended_info'] = array(
+ 'description' => __( 'Add additional piece of info about each product to the report.', 'woocommerce' ),
+ 'type' => 'boolean',
+ 'default' => false,
+ 'sanitize_callback' => 'wc_string_to_bool',
+ 'validate_callback' => 'rest_validate_request_arg',
+ );
+
+ return $params;
+ }
+
+ /**
+ * Get the column names for export.
+ *
+ * @return array Key value pair of Column ID => Label.
+ */
+ public function get_export_columns() {
+ $export_columns = array(
+ 'product_name' => __( 'Product', 'woocommerce' ),
+ 'signups' => __( 'Sign-ups', 'woocommerce' ),
+ 'notifications_sent' => __( 'Notifications sent', 'woocommerce' ),
+ 'customers' => __( 'Customers', 'woocommerce' ),
+ );
+
+ /**
+ * Filter to add or remove column names from the stock notifications report for export.
+ *
+ * @since 11.4.0
+ *
+ * @param array $export_columns Key value pair of Column ID => Label.
+ */
+ return apply_filters( 'woocommerce_report_stock_notifications_export_columns', $export_columns );
+ }
+
+ /**
+ * Get the column values for export.
+ *
+ * @param array $item Single report item/row.
+ * @return array Key value pair of Column ID => Row Value.
+ */
+ public function prepare_item_for_export( $item ) {
+ $export_item = array(
+ 'product_name' => $item['extended_info']['name'] ?? '',
+ 'signups' => $item['signups'],
+ 'notifications_sent' => $item['notifications_sent'],
+ 'customers' => $item['customers'],
+ );
+
+ /**
+ * Filter to prepare extra columns in the export item for the stock notifications report.
+ *
+ * @since 11.4.0
+ *
+ * @param array $export_item Key value pair of Column ID => Row Value.
+ * @param array $item Single report item/row.
+ */
+ return apply_filters( 'woocommerce_report_stock_notifications_prepare_export_item', $export_item, $item );
+ }
+}
diff --git a/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/DataStore.php b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/DataStore.php
new file mode 100644
index 00000000000..50b0aab7ead
--- /dev/null
+++ b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/DataStore.php
@@ -0,0 +1,431 @@
+<?php
+/**
+ * API\Reports\StockNotifications\DataStore class file.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Admin\API\Reports\StockNotifications;
+
+defined( 'ABSPATH' ) || exit;
+
+use Automattic\WooCommerce\Admin\API\Reports\DataStore as ReportsDataStore;
+use Automattic\WooCommerce\Admin\API\Reports\DataStoreInterface;
+use Automattic\WooCommerce\Admin\API\Reports\SqlQuery;
+use Automattic\WooCommerce\Admin\API\Reports\TimeInterval;
+use Automattic\WooCommerce\Enums\ProductType;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+
+/**
+ * Stock notifications report, one row per product.
+ *
+ * Metrics, per product, each on its own date column:
+ * - signups: rows created in the period, excluding pending ones. Pending rows are unconfirmed
+ * double opt-in and get purged by DataRetentionController, so counting them would shrink history.
+ * Cancelled rows still count on their creation date.
+ * - notifications_sent: rows notified in the period, like the stats report.
+ * - customers: distinct emails among the period's sign-ups.
+ *
+ * The product is the one the customer signed up for, so a variation is its own row.
+ *
+ * The table stores UTC dates while the base class assumes site-time columns, so the date handling
+ * below converts at query time. Intervals use the current UTC offset, which mis-buckets the hour
+ * around a DST switch. Accepted for sign-up counts; the fix would be local-time columns, like wc_order_stats.
+ */
+class DataStore extends ReportsDataStore implements DataStoreInterface {
+
+ /**
+ * Table used to get the data.
+ *
+ * @override ReportsDataStore::$table_name
+ *
+ * @var string
+ */
+ protected static $table_name = 'wc_stock_notifications';
+
+ /**
+ * Cache identifier.
+ *
+ * @override ReportsDataStore::$cache_key
+ *
+ * @var string
+ */
+ protected $cache_key = 'stock_notifications';
+
+ /**
+ * Transient version group for this report's cache, so sign-up changes don't clear other reports.
+ */
+ const CACHE_VERSION_GROUP = 'woocommerce_reports_stock_notifications';
+
+ /**
+ * Data store context used to pass to filters.
+ *
+ * @override ReportsDataStore::$context
+ *
+ * @var string
+ */
+ protected $context = 'stock_notifications';
+
+ /**
+ * Date field name.
+ *
+ * @override ReportsDataStore::$date_column_name
+ *
+ * @var string
+ */
+ protected $date_column_name = 'date_created_gmt';
+
+ /**
+ * Mapping columns to data type to return correct response types.
+ *
+ * @override ReportsDataStore::$column_types
+ *
+ * @var array
+ */
+ protected $column_types = array(
+ 'product_id' => 'intval',
+ 'signups' => 'intval',
+ 'notifications_sent' => 'intval',
+ 'customers' => 'intval',
+ );
+
+ /**
+ * Assign report columns once full table name has been assigned.
+ *
+ * The metrics depend on the period, so get_noncached_data() fills them in.
+ *
+ * @override ReportsDataStore::assign_report_columns()
+ *
+ * @return void
+ */
+ protected function assign_report_columns() {
+ $this->report_columns = array(
+ 'product_id' => self::get_db_table_name() . '.product_id',
+ );
+ }
+
+ /**
+ * Returns the SQL condition for each metric in the period, keyed by metric.
+ *
+ * @param array $query_args Query parameters.
+ * @return array<string, string>
+ */
+ protected function get_metric_conditions( $query_args ) {
+ global $wpdb;
+
+ $table_name = self::get_db_table_name();
+ $after = $this->get_utc_datetime_string( $query_args['after'] );
+ $before = $this->get_utc_datetime_string( $query_args['before'] );
+
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is internal.
+ return array(
+ 'signups' => $wpdb->prepare(
+ "{$table_name}.date_created_gmt BETWEEN %s AND %s AND {$table_name}.status <> %s",
+ $after,
+ $before,
+ NotificationStatus::PENDING
+ ),
+ 'notifications_sent' => $wpdb->prepare(
+ "{$table_name}.date_notified_gmt BETWEEN %s AND %s",
+ $after,
+ $before
+ ),
+ );
+ // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ }
+
+ /**
+ * Formats a site-time date as a UTC SQL datetime string.
+ *
+ * @param \DateTime $datetime Date in the site timezone.
+ * @return string
+ */
+ protected function get_utc_datetime_string( $datetime ) {
+ $utc = clone $datetime;
+ $utc->setTimezone( new \DateTimeZone( 'UTC' ) );
+ return $utc->format( TimeInterval::$sql_datetime_format );
+ }
+
+ /**
+ * Returns SQL that shifts a UTC date column to site time, using the current UTC offset.
+ *
+ * @param string $table_name Table name.
+ * @param string $column Date column name.
+ * @return string
+ */
+ protected function get_local_datetime_sql( $table_name, $column ) {
+ $offset = (int) wc_timezone_offset();
+ return "DATE_ADD( {$table_name}.`{$column}`, INTERVAL {$offset} SECOND )";
+ }
+
+ /**
+ * Returns the interval SELECT expression for a UTC date column, bucketed in site time.
+ *
+ * Reuses TimeInterval::db_datetime_format() so the ids stay in sync with TimeInterval::time_interval_id().
+ *
+ * @param string $interval Time interval, e.g. day, week, month.
+ * @param string $table_name Table name.
+ * @param string $column Date column name.
+ * @return string
+ */
+ protected function get_interval_sql( $interval, $table_name, $column ) {
+ return str_replace(
+ "{$table_name}.`{$column}`",
+ $this->get_local_datetime_sql( $table_name, $column ),
+ TimeInterval::db_datetime_format( $interval, $table_name, $column )
+ );
+ }
+
+ /**
+ * Fills the date WHERE clauses, converting the site-time period to UTC.
+ *
+ * @override ReportsDataStore::add_time_period_sql_params()
+ *
+ * @param array $query_args Parameters supplied by the user.
+ * @param string $table_name Name of the db table relevant for the date constraint.
+ * @return void
+ */
+ protected function add_time_period_sql_params( $query_args, $table_name ) {
+ foreach ( array( 'after', 'before' ) as $key ) {
+ if ( isset( $query_args[ $key ] ) && $query_args[ $key ] instanceof \DateTime ) {
+ $query_args[ $key ] = clone $query_args[ $key ];
+ $query_args[ $key ]->setTimezone( new \DateTimeZone( 'UTC' ) );
+ }
+ }
+
+ parent::add_time_period_sql_params( $query_args, $table_name );
+ }
+
+ /**
+ * Fills the interval SELECT and date WHERE clauses, bucketing UTC dates in site time.
+ *
+ * @override ReportsDataStore::add_intervals_sql_params()
+ *
+ * @param array $query_args Parameters supplied by the user.
+ * @param string $table_name Name of the db table relevant for the date constraint.
+ * @return void
+ */
+ protected function add_intervals_sql_params( $query_args, $table_name ) {
+ $this->clear_sql_clause( array( 'from', 'where_time', 'where' ) );
+ $this->add_time_period_sql_params( $query_args, $table_name );
+
+ if ( ! empty( $query_args['interval'] ) ) {
+ $this->clear_sql_clause( 'select' );
+ $this->add_sql_clause( 'select', $this->get_interval_sql( $query_args['interval'], $table_name, $this->date_column_name ) );
+ }
+ }
+
+ /**
+ * Updates the interval query for pagination, converting the page's date range to UTC.
+ *
+ * The parent writes site-time bounds into the interval query when ordering by date.
+ * `adj_after` and `adj_before` stay in site time for fill_in_missing_intervals().
+ *
+ * @override ReportsDataStore::update_intervals_sql_params()
+ *
+ * @param array $query_args Query arguments.
+ * @param int $db_interval_count Database interval count.
+ * @param int $expected_interval_count Expected interval count on the output.
+ * @param string $table_name Name of the db table relevant for the date constraint.
+ * @return void
+ */
+ protected function update_intervals_sql_params( &$query_args, $db_interval_count, $expected_interval_count, $table_name ) {
+ global $wpdb;
+
+ parent::update_intervals_sql_params( $query_args, $db_interval_count, $expected_interval_count, $table_name );
+
+ if ( $db_interval_count === $expected_interval_count || 'date' !== strtolower( $query_args['orderby'] ) ) {
+ return;
+ }
+
+ $column = "{$table_name}.`{$this->date_column_name}`";
+ $this->interval_query->clear_sql_clause( 'where_time' );
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- column name is internal.
+ $this->interval_query->add_sql_clause( 'where_time', $wpdb->prepare( "AND {$column} <= %s", $this->get_utc_datetime_string( $query_args['adj_before'] ) ) );
+ $this->interval_query->add_sql_clause( 'where_time', $wpdb->prepare( "AND {$column} >= %s", $this->get_utc_datetime_string( $query_args['adj_after'] ) ) );
+ // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ }
+
+ /**
+ * Get the default query arguments to be used by get_data().
+ * These defaults are only partially applied when used via REST API, as that has its own defaults.
+ *
+ * @override ReportsDataStore::get_default_query_vars()
+ *
+ * @return array Query parameters.
+ */
+ public function get_default_query_vars() {
+ $defaults = parent::get_default_query_vars();
+ $defaults['orderby'] = 'signups';
+ $defaults['order'] = 'desc';
+ $defaults['product_includes'] = array();
+ $defaults['extended_info'] = false;
+
+ return $defaults;
+ }
+
+ /**
+ * Clear the cached Stock notifications report data, leaving other reports cached.
+ *
+ * @internal
+ */
+ public static function invalidate_cache(): void {
+ \WC_Cache_Helper::get_transient_version( self::CACHE_VERSION_GROUP, true );
+ }
+
+ /**
+ * Get the current version of this report's cache.
+ *
+ * @internal
+ * @return string
+ */
+ public static function get_cache_version(): string {
+ return (string) \WC_Cache_Helper::get_transient_version( self::CACHE_VERSION_GROUP );
+ }
+
+ /**
+ * Include this report's cache version, so invalidate_cache() expires only these entries.
+ *
+ * @override ReportsDataStore::get_cache_key()
+ *
+ * @param array $params Query parameters.
+ * @return string
+ */
+ protected function get_cache_key( $params ) {
+ return parent::get_cache_key( $params ) . '_' . self::get_cache_version();
+ }
+
+ /**
+ * Returns the report data based on normalized parameters.
+ * Will be called by `get_data` if there is no data in cache.
+ *
+ * @override ReportsDataStore::get_noncached_data()
+ *
+ * @see get_data
+ * @param array $query_args Query parameters.
+ * @return \stdClass|\WP_Error Data object `{ data: array, total: int, pages: int, page_no: int }`, or error.
+ */
+ public function get_noncached_data( $query_args ) {
+ global $wpdb;
+
+ $table_name = self::get_db_table_name();
+
+ $this->initialize_queries();
+
+ $data = (object) array(
+ 'data' => array(),
+ 'total' => 0,
+ 'pages' => 0,
+ 'page_no' => 0,
+ );
+
+ $limit_params = $this->get_limit_sql_params( $query_args );
+ $conditions = $this->get_metric_conditions( $query_args );
+ foreach ( $conditions as $metric => $condition ) {
+ $this->report_columns[ $metric ] = "SUM( {$condition} ) AS {$metric}";
+ }
+ $this->report_columns['customers'] = "COUNT( DISTINCT CASE WHEN {$conditions['signups']} THEN {$table_name}.user_email END ) AS customers";
+ $this->subquery->add_sql_clause( 'where', 'AND ( (' . implode( ') OR (', $conditions ) . ') )' );
+
+ $included_products = $this->get_filtered_ids( $query_args, 'product_includes' );
+ if ( $included_products ) {
+ $this->subquery->add_sql_clause( 'where', "AND {$table_name}.product_id IN ({$included_products})" );
+ }
+
+ $this->subquery->add_sql_clause( 'select', "{$table_name}.product_id" );
+ $count_query = "SELECT COUNT(*) FROM ( {$this->subquery->get_query_statement()} ) AS tt";
+
+ $total_results = (int) $wpdb->get_var(
+ $count_query // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- built from internal clauses.
+ );
+ $total_pages = (int) ceil( $total_results / $limit_params['per_page'] );
+ if ( $query_args['page'] < 1 || $query_args['page'] > $total_pages ) {
+ return $data;
+ }
+
+ $this->subquery->clear_sql_clause( 'select' );
+ $this->subquery->add_sql_clause( 'select', $this->selected_columns( $query_args ) );
+ $this->add_order_by_clause( $query_args, $this->subquery );
+ $this->add_orderby_order_clause( $query_args, $this->subquery );
+ if ( 'product_id' !== $query_args['orderby'] ) {
+ // Stable paging when the sort column ties.
+ $this->subquery->add_sql_clause( 'order_by', ", {$table_name}.product_id ASC" );
+ }
+ $this->subquery->add_sql_clause( 'limit', $this->get_sql_clause( 'limit' ) );
+
+ $rows = $wpdb->get_results(
+ $this->subquery->get_query_statement(), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- built from internal clauses.
+ ARRAY_A
+ );
+ if ( null === $rows ) {
+ return $data;
+ }
+
+ $this->include_extended_info( $rows, $query_args );
+
+ return (object) array(
+ 'data' => array_map( array( $this, 'cast_numbers' ), $rows ),
+ 'total' => $total_results,
+ 'pages' => $total_pages,
+ 'page_no' => (int) $query_args['page'],
+ );
+ }
+
+ /**
+ * Adds product name, permalink and edit link to each row, loading all products at once.
+ *
+ * @param array $rows Report rows.
+ * @param array $query_args Query parameters.
+ * @return void
+ */
+ protected function include_extended_info( &$rows, $query_args ) {
+ $products = array();
+ if ( $query_args['extended_info'] && $rows ) {
+ $found = wc_get_products(
+ array(
+ 'include' => array_map( 'intval', array_column( $rows, 'product_id' ) ),
+ 'type' => array_merge( array_keys( wc_get_product_types() ), array( ProductType::VARIATION ) ),
+ 'limit' => -1,
+ )
+ );
+ foreach ( is_array( $found ) ? $found : array() as $product ) {
+ $products[ $product->get_id() ] = $product;
+ }
+ }
+
+ foreach ( $rows as $idx => $row ) {
+ $extended_info = new \ArrayObject();
+ if ( $query_args['extended_info'] ) {
+ $product = $products[ (int) $row['product_id'] ] ?? null;
+ if ( $product ) {
+ $edit_id = $product->get_parent_id() ? $product->get_parent_id() : $product->get_id();
+ $extended_info = array(
+ 'name' => $product->get_name(),
+ 'permalink' => $product->get_permalink(),
+ 'edit_url' => (string) get_edit_post_link( $edit_id, 'raw' ),
+ );
+ } else {
+ $extended_info = array(
+ /* translators: %s: product ID, e.g. #123 */
+ 'name' => sprintf( __( '%s (Deleted)', 'woocommerce' ), '#' . $row['product_id'] ),
+ 'permalink' => '',
+ 'edit_url' => '',
+ );
+ }
+ }
+ $rows[ $idx ]['extended_info'] = $extended_info;
+ }
+ }
+
+ /**
+ * Initialize query objects.
+ *
+ * @return void
+ */
+ protected function initialize_queries() {
+ $this->clear_all_clauses();
+ $this->subquery = new SqlQuery( $this->context . '_subquery' );
+ $this->subquery->add_sql_clause( 'from', self::get_db_table_name() );
+ $this->subquery->add_sql_clause( 'group_by', self::get_db_table_name() . '.product_id' );
+ }
+}
diff --git a/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Stats/Controller.php b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Stats/Controller.php
new file mode 100644
index 00000000000..39cdea50fc4
--- /dev/null
+++ b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Stats/Controller.php
@@ -0,0 +1,162 @@
+<?php
+/**
+ * REST API Reports stock notifications stats controller
+ *
+ * Handles requests to the /reports/stock-notifications/stats endpoint.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Stats;
+
+defined( 'ABSPATH' ) || exit;
+
+use Automattic\WooCommerce\Admin\API\Reports\GenericQuery;
+use Automattic\WooCommerce\Admin\API\Reports\GenericStatsController;
+use WP_REST_Request;
+use WP_REST_Response;
+
+/**
+ * REST API Reports stock notifications stats controller class.
+ *
+ * @internal
+ */
+class Controller extends GenericStatsController {
+
+ /**
+ * Route base.
+ *
+ * @var string
+ */
+ protected $rest_base = 'reports/stock-notifications/stats';
+
+ /**
+ * Maps query arguments from the REST request.
+ *
+ * @param WP_REST_Request<array<string, mixed>> $request Request array.
+ * @return array
+ */
+ protected function prepare_reports_query( $request ) {
+ $args = array();
+ $args['before'] = $request['before'];
+ $args['after'] = $request['after'];
+ $args['interval'] = $request['interval'];
+ $args['page'] = $request['page'];
+ $args['per_page'] = $request['per_page'];
+ $args['orderby'] = $request['orderby'];
+ $args['order'] = $request['order'];
+ $args['fields'] = $request['fields'];
+ $args['force_cache_refresh'] = $request['force_cache_refresh'];
+
+ return $args;
+ }
+
+ /**
+ * Get data from `'stock-notifications-stats'` GenericQuery.
+ *
+ * @override GenericController::get_datastore_data()
+ *
+ * @param array $query_args Query arguments.
+ * @return mixed Results from the data store.
+ */
+ protected function get_datastore_data( $query_args = array() ) {
+ $query = new GenericQuery( $query_args, 'stock-notifications-stats' );
+ return $query->get_data();
+ }
+
+ /**
+ * Prepare a report data item for serialization.
+ *
+ * @param array $report Report data item as returned from Data Store.
+ * @param WP_REST_Request<array<string, mixed>> $request Request object.
+ * @return WP_REST_Response
+ */
+ public function prepare_item_for_response( $report, $request ) {
+ $response = parent::prepare_item_for_response( $report, $request );
+
+ /**
+ * Filter a stock notifications stats interval returned from the API.
+ *
+ * @since 11.4.0
+ *
+ * @param WP_REST_Response $response The response object.
+ * @param array $report The original report interval.
+ * @param WP_REST_Request $request Request used to generate the response.
+ */
+ return apply_filters( 'woocommerce_rest_prepare_report_stock_notifications_stats', $response, $report, $request );
+ }
+
+ /**
+ * Get the Report's item properties schema.
+ * Will be used by `get_item_schema` as `totals` and `subtotals`.
+ *
+ * @return array
+ */
+ protected function get_item_properties_schema() {
+ return array(
+ 'signups' => array(
+ 'title' => __( 'Sign-ups', 'woocommerce' ),
+ 'description' => __( 'Sign-ups created in the period. Excludes unconfirmed (pending) sign-ups.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'notifications_sent' => array(
+ 'title' => __( 'Notifications sent', 'woocommerce' ),
+ 'description' => __( 'Back-in-stock emails sent in the period. A re-sent notification counts once, on its latest send date.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'customers' => array(
+ 'title' => __( 'Customers', 'woocommerce' ),
+ 'description' => __( 'Distinct customers, by email, who signed up in the period.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'products_count' => array(
+ 'title' => __( 'Products', 'woocommerce' ),
+ 'description' => __( 'Products with sign-ups or notifications sent in the period.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ );
+ }
+
+ /**
+ * Get the Report's schema, conforming to JSON Schema.
+ * It does not have the segments as in GenericStatsController.
+ *
+ * @return array
+ */
+ public function get_item_schema() {
+ $schema = parent::get_item_schema();
+ $schema['title'] = 'report_stock_notifications_stats';
+
+ unset( $schema['properties']['totals']['properties']['segments'] );
+ unset( $schema['properties']['intervals']['items']['properties']['subtotals']['properties']['segments'] );
+ unset( $schema['properties']['intervals']['items']['properties']['subtotals']['properties']['products_count'] );
+
+ return $this->add_additional_fields_schema( $schema );
+ }
+
+ /**
+ * Get the query params for collections.
+ *
+ * @return array
+ */
+ public function get_collection_params() {
+ $params = parent::get_collection_params();
+ $params['interval']['default'] = 'day';
+ $params['orderby']['enum'] = $this->apply_custom_orderby_filters(
+ array(
+ 'date',
+ 'signups',
+ )
+ );
+
+ return $params;
+ }
+}
diff --git a/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Stats/DataStore.php b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Stats/DataStore.php
new file mode 100644
index 00000000000..d74a68b296a
--- /dev/null
+++ b/plugins/woocommerce/src/Admin/API/Reports/StockNotifications/Stats/DataStore.php
@@ -0,0 +1,291 @@
+<?php
+/**
+ * API\Reports\StockNotifications\Stats\DataStore class file.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Stats;
+
+defined( 'ABSPATH' ) || exit;
+
+use Automattic\WooCommerce\Admin\API\Reports\DataStoreInterface;
+use Automattic\WooCommerce\Admin\API\Reports\StatsDataStoreTrait;
+use Automattic\WooCommerce\Admin\API\Reports\StockNotifications\DataStore as StockNotificationsDataStore;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+
+/**
+ * Stock notifications stats report: totals plus per-interval subtotals.
+ *
+ * - signups, notifications_sent, customers: same definitions as the per-product report, each
+ * bucketed on its own date column. date_notified_gmt is overwritten on re-send, so a re-send
+ * moves the count to the new date rather than adding to it. Customers are distinct within each
+ * interval and within the totals, so interval values don't add up to the total.
+ * - products_count: products with sign-ups or notifications sent in the period, i.e. the per-product report's rows.
+ */
+class DataStore extends StockNotificationsDataStore implements DataStoreInterface {
+ use StatsDataStoreTrait;
+
+ /**
+ * Mapping columns to data type to return correct response types.
+ *
+ * @override StockNotificationsDataStore::$column_types
+ *
+ * @var array
+ */
+ protected $column_types = array(
+ 'date_start' => 'strval',
+ 'date_end' => 'strval',
+ 'date_start_gmt' => 'strval',
+ 'date_end_gmt' => 'strval',
+ 'signups' => 'intval',
+ 'notifications_sent' => 'intval',
+ 'customers' => 'intval',
+ 'products_count' => 'intval',
+ );
+
+ /**
+ * SQL columns to select in the db query.
+ *
+ * @override StockNotificationsDataStore::$report_columns
+ *
+ * @var array
+ */
+ protected $report_columns;
+
+ /**
+ * Data store context used to pass to filters.
+ *
+ * @override StockNotificationsDataStore::$context
+ *
+ * @var string
+ */
+ protected $context = 'stock_notifications_stats';
+
+ /**
+ * Cache identifier.
+ *
+ * @override StockNotificationsDataStore::$cache_key
+ *
+ * @var string
+ */
+ protected $cache_key = 'stock_notifications_stats';
+
+ /**
+ * Assign report columns once full table name has been assigned.
+ *
+ * These run on the date_created_gmt series, whose WHERE clause already excludes pending rows.
+ *
+ * @override StockNotificationsDataStore::assign_report_columns()
+ *
+ * @return void
+ */
+ protected function assign_report_columns() {
+ $this->report_columns = array(
+ 'signups' => 'COUNT(*) AS signups',
+ 'customers' => 'COUNT( DISTINCT ' . self::get_db_table_name() . '.user_email ) AS customers',
+ );
+ }
+
+ /**
+ * Get the default query arguments to be used by get_data().
+ * These defaults are only partially applied when used via REST API, as that has its own defaults.
+ *
+ * @override StockNotificationsDataStore::get_default_query_vars()
+ *
+ * @return array Query parameters.
+ */
+ public function get_default_query_vars() {
+ $defaults = parent::get_default_query_vars();
+ $defaults['interval'] = 'day';
+ $defaults['orderby'] = 'date';
+
+ return $defaults;
+ }
+
+ /**
+ * Fills the interval and totals queries for the sign-ups series.
+ *
+ * @param array $query_args Query arguments supplied by the user.
+ * @return void
+ */
+ protected function update_sql_query_params( $query_args ) {
+ global $wpdb;
+
+ $table_name = self::get_db_table_name();
+ $where = $wpdb->prepare(
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is internal.
+ "AND {$table_name}.status <> %s",
+ NotificationStatus::PENDING
+ );
+
+ $this->add_time_period_sql_params( $query_args, $table_name );
+ $this->add_intervals_sql_params( $query_args, $table_name );
+ $this->add_order_by_sql_params( $query_args );
+ $where_time = $this->get_sql_clause( 'where_time' );
+
+ $this->interval_query->add_sql_clause( 'select', $this->get_sql_clause( 'select' ) );
+ $this->interval_query->add_sql_clause( 'select', 'AS time_interval' );
+
+ foreach ( array( $this->interval_query, $this->total_query ) as $query ) {
+ $query->add_sql_clause( 'where_time', $where_time );
+ $query->add_sql_clause( 'where', $where );
+ }
+ }
+
+ /**
+ * Returns the report data based on normalized parameters.
+ * Will be called by `get_data` if there is no data in cache.
+ *
+ * Runs the standard interval flow for sign-ups, then merges in the metrics bucketed on other
+ * date columns and the product count.
+ *
+ * @override StockNotificationsDataStore::get_noncached_stats_data()
+ *
+ * @see get_data
+ * @see get_noncached_stats_data
+ * @param array $query_args Query parameters.
+ * @param array $params Query limit parameters.
+ * @param \stdClass $data Reference to the data object to fill.
+ * @param int $expected_interval_count Number of expected intervals.
+ * @return \stdClass|\WP_Error Data object `{ totals: *, intervals: array, total: int, pages: int, page_no: int }`, or error.
+ */
+ public function get_noncached_stats_data( $query_args, $params, &$data, $expected_interval_count ) {
+ global $wpdb;
+
+ $table_name = self::get_db_table_name();
+
+ $this->initialize_queries();
+
+ // ORDER BY needs the sort column selected, even when `fields` leaves it out.
+ $sql_args = $query_args;
+ $hidden_orderby = is_array( $query_args['fields'] ?? null ) && isset( $this->report_columns[ $query_args['orderby'] ] ) && ! in_array( $query_args['orderby'], $query_args['fields'], true );
+ if ( $hidden_orderby ) {
+ $sql_args['fields'][] = $query_args['orderby'];
+ }
+
+ $selections = $this->selected_columns( $sql_args );
+ $limit_params = $this->get_limit_sql_params( $query_args );
+ $this->update_sql_query_params( $query_args );
+
+ $db_intervals = $wpdb->get_col(
+ // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- cache ok, DB call ok, unprepared SQL ok.
+ $this->interval_query->get_query_statement()
+ );
+
+ $db_interval_count = count( $db_intervals );
+
+ $totals = array();
+ if ( '' !== $selections ) {
+ $this->total_query->add_sql_clause( 'select', $selections );
+ $totals = $wpdb->get_row(
+ // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- cache ok, DB call ok, unprepared SQL ok.
+ $this->total_query->get_query_statement(),
+ ARRAY_A
+ );
+
+ if ( null === $totals ) {
+ return $data;
+ }
+ }
+
+ // Intervals.
+ $this->update_intervals_sql_params( $query_args, $db_interval_count, $expected_interval_count, $table_name );
+ $this->interval_query->add_sql_clause( 'order_by', $this->get_sql_clause( 'order_by' ) );
+ $this->interval_query->add_sql_clause( 'limit', $this->get_sql_clause( 'limit' ) );
+ $this->interval_query->add_sql_clause( 'select', ', MAX( ' . $this->get_local_datetime_sql( $table_name, $this->date_column_name ) . ' ) AS datetime_anchor' );
+
+ if ( '' !== $selections ) {
+ $this->interval_query->add_sql_clause( 'select', ', ' . $selections );
+ }
+
+ $intervals = $wpdb->get_results(
+ // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- cache ok, DB call ok, unprepared SQL ok.
+ $this->interval_query->get_query_statement(),
+ ARRAY_A
+ );
+
+ if ( null === $intervals ) {
+ return $data;
+ }
+
+ // Zero-filled intervals copy their keys from the totals, so set only the per-interval metrics for now.
+ $data->totals = (object) $this->cast_numbers( $totals );
+ $data->intervals = $intervals;
+
+ if ( $this->intervals_missing( $expected_interval_count, $db_interval_count, $limit_params['per_page'], $query_args['page'], $query_args['order'], $query_args['orderby'], count( $intervals ) ) ) {
+ $this->fill_in_missing_intervals( $db_intervals, $query_args['adj_after'], $query_args['adj_before'], $query_args['interval'], $data );
+ $this->sort_intervals( $data, $query_args['orderby'], $query_args['order'] );
+ $this->remove_extra_records( $data, $query_args['page'], $limit_params['per_page'], $db_interval_count, $expected_interval_count, $query_args['orderby'], $query_args['order'] );
+ } else {
+ $this->update_interval_boundary_dates( $query_args['after'], $query_args['before'], $query_args['interval'], $data->intervals );
+ }
+
+ /**
+ * The base class docblocks type $data as an unqualified stdClass.
+ *
+ * @var \stdClass $data
+ */
+
+ if ( $hidden_orderby ) {
+ unset( $data->totals->{$query_args['orderby']} );
+ foreach ( $data->intervals as $idx => $interval ) {
+ unset( $data->intervals[ $idx ][ $query_args['orderby'] ] );
+ }
+ }
+
+ $conditions = $this->get_metric_conditions( $query_args );
+ if ( $this->is_field_requested( $query_args, 'notifications_sent' ) ) {
+ $by_interval = $this->get_count_by_interval( $query_args, 'date_notified_gmt', $conditions['notifications_sent'] );
+ foreach ( $data->intervals as $idx => $interval ) {
+ $data->intervals[ $idx ]['notifications_sent'] = $by_interval[ $interval['time_interval'] ] ?? 0;
+ }
+ $data->totals->notifications_sent = array_sum( $by_interval );
+ }
+
+ if ( $this->is_field_requested( $query_args, 'products_count' ) ) {
+ $data->totals->products_count = (int) $wpdb->get_var(
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- built from internal clauses and prepared conditions.
+ "SELECT COUNT( DISTINCT product_id ) FROM {$table_name} WHERE (" . implode( ') OR (', $conditions ) . ')'
+ );
+ }
+
+ return $data;
+ }
+
+ /**
+ * Returns the rows matching a metric condition in the query period, keyed by time interval id.
+ *
+ * Covers the whole period, not just the current page, so any page can look up its intervals.
+ *
+ * @param array $query_args Query parameters.
+ * @param string $column Date column the metric is bucketed on.
+ * @param string $condition Prepared SQL condition for the metric, including the period.
+ * @return array<string, int>
+ */
+ protected function get_count_by_interval( $query_args, $column, $condition ) {
+ global $wpdb;
+
+ $table_name = self::get_db_table_name();
+ $interval = $this->get_interval_sql( $query_args['interval'], $table_name, $column );
+
+ $rows = $wpdb->get_results(
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- built from internal clauses and a prepared condition.
+ "SELECT {$interval} AS time_interval, COUNT(*) AS total FROM {$table_name} WHERE {$condition} GROUP BY time_interval",
+ ARRAY_A
+ );
+
+ return array_map( 'intval', array_column( (array) $rows, 'total', 'time_interval' ) );
+ }
+
+ /**
+ * Whether the request asks for a field, either explicitly or by not limiting fields.
+ *
+ * @param array $query_args Query parameters.
+ * @param string $field Field name.
+ * @return bool
+ */
+ protected function is_field_requested( $query_args, $field ) {
+ return ! isset( $query_args['fields'] ) || ! is_array( $query_args['fields'] ) || in_array( $field, $query_args['fields'], true );
+ }
+}
diff --git a/plugins/woocommerce/src/Admin/ReportCSVEmail.php b/plugins/woocommerce/src/Admin/ReportCSVEmail.php
index 68c80692708..66bde6eb2c6 100644
--- a/plugins/woocommerce/src/Admin/ReportCSVEmail.php
+++ b/plugins/woocommerce/src/Admin/ReportCSVEmail.php
@@ -72,16 +72,17 @@ class ReportCSVEmail extends \WC_Email {
$this->report_labels = apply_filters(
'woocommerce_report_export_email_labels',
array(
- 'categories' => __( 'Categories', 'woocommerce' ),
- 'coupons' => __( 'Coupons', 'woocommerce' ),
- 'customers' => __( 'Customers', 'woocommerce' ),
- 'downloads' => __( 'Downloads', 'woocommerce' ),
- 'orders' => __( 'Orders', 'woocommerce' ),
- 'products' => __( 'Products', 'woocommerce' ),
- 'revenue' => __( 'Revenue', 'woocommerce' ),
- 'stock' => __( 'Stock', 'woocommerce' ),
- 'taxes' => __( 'Taxes', 'woocommerce' ),
- 'variations' => __( 'Variations', 'woocommerce' ),
+ 'categories' => __( 'Categories', 'woocommerce' ),
+ 'coupons' => __( 'Coupons', 'woocommerce' ),
+ 'customers' => __( 'Customers', 'woocommerce' ),
+ 'downloads' => __( 'Downloads', 'woocommerce' ),
+ 'orders' => __( 'Orders', 'woocommerce' ),
+ 'products' => __( 'Products', 'woocommerce' ),
+ 'revenue' => __( 'Revenue', 'woocommerce' ),
+ 'stock' => __( 'Stock', 'woocommerce' ),
+ 'stock-notifications' => __( 'Stock notifications', 'woocommerce' ),
+ 'taxes' => __( 'Taxes', 'woocommerce' ),
+ 'variations' => __( 'Variations', 'woocommerce' ),
)
);
diff --git a/plugins/woocommerce/src/Admin/ReportCSVExporter.php b/plugins/woocommerce/src/Admin/ReportCSVExporter.php
index 9f4be6678b2..c0bfad7b8ce 100644
--- a/plugins/woocommerce/src/Admin/ReportCSVExporter.php
+++ b/plugins/woocommerce/src/Admin/ReportCSVExporter.php
@@ -10,6 +10,7 @@ if ( ! defined( 'ABSPATH' ) ) {
}
use Automattic\WooCommerce\Admin\API\Reports\ExportableInterface;
+use Automattic\WooCommerce\Internal\StockNotifications\StockNotifications;
/**
* Include dependencies.
@@ -270,27 +271,30 @@ class ReportCSVExporter extends \WC_CSV_Batch_Exporter {
* @return array Report type to report controller class map.
*/
private static function get_report_controller_map() {
+ $controller_map = array(
+ 'products' => 'Automattic\WooCommerce\Admin\API\Reports\Products\Controller',
+ 'variations' => 'Automattic\WooCommerce\Admin\API\Reports\Variations\Controller',
+ 'orders' => 'Automattic\WooCommerce\Admin\API\Reports\Orders\Controller',
+ 'categories' => 'Automattic\WooCommerce\Admin\API\Reports\Categories\Controller',
+ 'taxes' => 'Automattic\WooCommerce\Admin\API\Reports\Taxes\Controller',
+ 'coupons' => 'Automattic\WooCommerce\Admin\API\Reports\Coupons\Controller',
+ 'stock' => 'Automattic\WooCommerce\Admin\API\Reports\Stock\Controller',
+ 'downloads' => 'Automattic\WooCommerce\Admin\API\Reports\Downloads\Controller',
+ 'customers' => 'Automattic\WooCommerce\Admin\API\Reports\Customers\Controller',
+ 'revenue' => 'Automattic\WooCommerce\Admin\API\Reports\Revenue\Stats\Controller',
+ );
+
+ if ( StockNotifications::is_enabled_before_init() ) {
+ $controller_map['stock-notifications'] = 'Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Controller';
+ }
+
/**
* Used to add custom report controllers.
*
* @since 9.8.0
* @param array $controller_map A report type to report controller class map.
*/
- return apply_filters(
- 'woocommerce_export_report_controller_map',
- array(
- 'products' => 'Automattic\WooCommerce\Admin\API\Reports\Products\Controller',
- 'variations' => 'Automattic\WooCommerce\Admin\API\Reports\Variations\Controller',
- 'orders' => 'Automattic\WooCommerce\Admin\API\Reports\Orders\Controller',
- 'categories' => 'Automattic\WooCommerce\Admin\API\Reports\Categories\Controller',
- 'taxes' => 'Automattic\WooCommerce\Admin\API\Reports\Taxes\Controller',
- 'coupons' => 'Automattic\WooCommerce\Admin\API\Reports\Coupons\Controller',
- 'stock' => 'Automattic\WooCommerce\Admin\API\Reports\Stock\Controller',
- 'downloads' => 'Automattic\WooCommerce\Admin\API\Reports\Downloads\Controller',
- 'customers' => 'Automattic\WooCommerce\Admin\API\Reports\Customers\Controller',
- 'revenue' => 'Automattic\WooCommerce\Admin\API\Reports\Revenue\Stats\Controller',
- )
- );
+ return apply_filters( 'woocommerce_export_report_controller_map', $controller_map );
}
/**
diff --git a/plugins/woocommerce/src/Internal/Admin/Analytics.php b/plugins/woocommerce/src/Internal/Admin/Analytics.php
index 23b2d503949..19208ca3f94 100644
--- a/plugins/woocommerce/src/Internal/Admin/Analytics.php
+++ b/plugins/woocommerce/src/Internal/Admin/Analytics.php
@@ -14,6 +14,7 @@ use Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore as OrderStat
use Automattic\WooCommerce\Internal\Admin\Notes\RefundDoubleCountToolNotice;
use Automattic\WooCommerce\Internal\Admin\Schedulers\OrdersScheduler;
use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;
+use Automattic\WooCommerce\Internal\StockNotifications\StockNotifications;
/**
* Contains backend logic for the Analytics feature.
@@ -1346,6 +1347,12 @@ class Analytics {
'parent' => 'woocommerce-analytics',
'path' => '/analytics/stock',
) : null,
+ StockNotifications::is_enabled_before_init() ? array(
+ 'id' => 'woocommerce-analytics-stock-notifications',
+ 'title' => __( 'Stock notifications', 'woocommerce' ),
+ 'parent' => 'woocommerce-analytics',
+ 'path' => '/analytics/stock-notifications',
+ ) : null,
array(
'id' => 'woocommerce-analytics-customers',
'title' => __( 'Customers', 'woocommerce' ),
diff --git a/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php b/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php
index 58751b41b44..65a82b0148e 100644
--- a/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php
+++ b/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php
@@ -7,6 +7,7 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\DataStores\StockNotifications;
+use Automattic\WooCommerce\Admin\API\Reports\StockNotifications\DataStore as StockNotificationsReportDataStore;
use Automattic\WooCommerce\Internal\StockNotifications\Notification;
use Automattic\WooCommerce\Internal\Utilities\DatabaseUtil;
use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
@@ -98,7 +99,9 @@ CREATE TABLE $table_name (
PRIMARY KEY (id),
KEY product_status_attempt (product_id, status, date_last_attempt_gmt, id),
KEY user_lookup (user_id, product_id, status),
- KEY email_lookup (user_email, product_id, status)
+ KEY email_lookup (user_email, product_id, status),
+ KEY date_created (date_created_gmt),
+ KEY date_notified (date_notified_gmt)
) $collate;
CREATE TABLE $meta_table_name (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
@@ -198,6 +201,9 @@ CREATE TABLE $meta_table_name (
$notification->save_meta_data();
$notification->apply_changes();
+ // After reading insert_id: invalidating can add an option row, which overwrites it.
+ StockNotificationsReportDataStore::invalidate_cache();
+
/**
* Action: woocommerce_new_stock_notification
*
@@ -313,6 +319,11 @@ CREATE TABLE $meta_table_name (
if ( false === $result ) {
return new \WP_Error( 'db_update_error', 'Could not update stock notification in the database.' );
}
+
+ // Only the props the Analytics report reads; bookkeeping saves such as send attempts keep the cache.
+ if ( array_intersect( array( 'product_id', 'user_email', 'status', 'date_created', 'date_notified' ), array_keys( $changes ) ) ) {
+ StockNotificationsReportDataStore::invalidate_cache();
+ }
}
$notification->save_meta_data();
@@ -367,6 +378,7 @@ CREATE TABLE $meta_table_name (
if ( $deleted > 0 ) {
$this->data_store_meta->delete_by_notification_id( $notification_id );
+ StockNotificationsReportDataStore::invalidate_cache();
/**
* Action: woocommerce_delete_stock_notification
diff --git a/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php b/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
index 0e27f93eeb0..4b97e6de69e 100644
--- a/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
+++ b/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
@@ -175,10 +175,8 @@ class StockNotifications implements RegisterHooksInterface {
public function register_data_stores( $data_stores ) {
// WC_Data_Store::__construct() re-applies this filter on every data store load,
// so re-check the feature: it can be switched off after this callback was
- // attached at `init`. Read the option directly rather than through
- // feature_is_enabled(): a data store can be loaded before `init`, and building
- // the translated feature definitions that early is not safe.
- if ( 'yes' !== get_option( self::ENABLE_OPTION_NAME, 'no' ) && ! self::is_alpha_enabled() ) {
+ // attached at `init`.
+ if ( ! self::is_enabled_before_init() ) {
return $data_stores;
}
@@ -202,6 +200,22 @@ class StockNotifications implements RegisterHooksInterface {
return FeaturesUtil::feature_is_enabled( self::FEATURE_NAME ) || self::is_alpha_enabled();
}
+ /**
+ * Check whether the feature is enabled, without going through the features controller.
+ *
+ * Reads the feature option directly, so it is safe in callbacks that can run before
+ * `init`, such as `woocommerce_data_stores`: feature_is_enabled() would build the
+ * translated feature definitions too early. Also honours the alpha constant, so it is
+ * the single gate for code outside this class, such as the Analytics report routes,
+ * menu item and data stores.
+ *
+ * @internal
+ * @return bool
+ */
+ public static function is_enabled_before_init(): bool {
+ return 'yes' === get_option( self::ENABLE_OPTION_NAME, 'no' ) || self::is_alpha_enabled();
+ }
+
/**
* Check whether the site opted in through the alpha constant.
*
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/reports-export.php b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/reports-export.php
index 2ada0414f72..67d52fc594a 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/reports-export.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/api/reports-export.php
@@ -17,14 +17,14 @@ class WC_Admin_Tests_API_Reports_Export extends WC_REST_Unit_Test_Case {
*
* @var string
*/
- protected $export_route = '/wc-analytics/reports/(?P<type>[a-z]+)/export';
+ protected $export_route = '/wc-analytics/reports/(?P<type>[a-z-]+)/export';
/**
* Export status route.
*
* @var string
*/
- protected $status_route = '/wc-analytics/reports/(?P<type>[a-z]+)/export/(?P<export_id>[a-z0-9]+)/status';
+ protected $status_route = '/wc-analytics/reports/(?P<type>[a-z-]+)/export/(?P<export_id>[a-z0-9]+)/status';
/**
* Setup test reports categories data.
diff --git a/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/ControllerTest.php b/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/ControllerTest.php
new file mode 100644
index 00000000000..6136b845923
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/ControllerTest.php
@@ -0,0 +1,395 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Admin\API\Reports\StockNotifications;
+
+use Automattic\WooCommerce\Admin\API\Reports\Cache as ReportsCache;
+use Automattic\WooCommerce\Admin\API\Reports\StockNotifications\Controller;
+use Automattic\WooCommerce\Admin\API\Reports\StockNotifications\DataStore as ReportDataStore;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+use Automattic\WooCommerce\Internal\StockNotifications\Notification;
+use Automattic\WooCommerce\Internal\StockNotifications\StockNotifications;
+use Exception;
+use WC_Data_Store;
+use WC_Helper_Product;
+use WC_REST_Unit_Test_Case;
+use WP_REST_Request;
+
+/**
+ * Stock notifications report API controller test.
+ */
+class ControllerTest extends WC_REST_Unit_Test_Case {
+
+ use ReportTestTrait;
+
+ /**
+ * Routes depend on the feature option, so each test needs a fresh server.
+ *
+ * @var bool
+ */
+ protected static $reuse_rest_server = false;
+
+ /**
+ * Endpoint.
+ *
+ * @var string
+ */
+ const ENDPOINT = '/wc-analytics/reports/stock-notifications';
+
+ /**
+ * Period covering 2026-03-01 to 2026-03-07.
+ *
+ * @var array
+ */
+ const PERIOD = array(
+ 'after' => '2026-03-01T00:00:00',
+ 'before' => '2026-03-07T23:59:59',
+ );
+
+ /**
+ * Set up.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->set_up_stock_notifications_report();
+ }
+
+ /**
+ * Tear down.
+ */
+ public function tearDown(): void {
+ try {
+ $this->tear_down_stock_notifications_report();
+ } finally {
+ parent::tearDown();
+ }
+ }
+
+ /**
+ * @testdox Should register the report routes only when the feature is enabled.
+ * @testWith ["yes", 200]
+ * ["no", 404]
+ *
+ * @param string $enabled Feature option value.
+ * @param int $expected_status Expected response status.
+ */
+ public function test_routes_follow_the_feature_state( string $enabled, int $expected_status ): void {
+ update_option( StockNotifications::ENABLE_OPTION_NAME, $enabled );
+
+ $this->assertSame( 200, $this->request( '/wc-analytics/reports/stock', array() )->get_status(), 'Other analytics routes should exist either way.' );
+ foreach ( array( self::ENDPOINT, self::ENDPOINT . '/stats' ) as $route ) {
+ $this->assertSame( $expected_status, $this->request( $route, self::PERIOD )->get_status(), "Unexpected status for {$route}." );
+ }
+ }
+
+ /**
+ * @testdox Should register the report data stores only when the feature is enabled.
+ * @testWith ["yes", true]
+ * ["no", false]
+ *
+ * @param string $enabled Feature option value.
+ * @param bool $registered Whether the data stores should load.
+ */
+ public function test_data_stores_follow_the_feature_state( string $enabled, bool $registered ): void {
+ update_option( StockNotifications::ENABLE_OPTION_NAME, $enabled );
+
+ foreach ( array( 'report-stock-notifications', 'report-stock-notifications-stats' ) as $name ) {
+ try {
+ WC_Data_Store::load( $name );
+ $loaded = true;
+ } catch ( Exception $e ) {
+ $loaded = false;
+ }
+ $this->assertSame( $registered, $loaded, "Unexpected data store state for {$name}." );
+ }
+ }
+
+ /**
+ * @testdox Should count a sign-up on the site-time day it was made, not the next UTC day.
+ */
+ public function test_signups_use_site_timezone(): void {
+ update_option( 'timezone_string', 'America/Los_Angeles' );
+ $this->insert_row( 5, NotificationStatus::ACTIVE, '2026-03-10 06:30:00' );
+
+ $local_day = $this->get_rows(
+ array(
+ 'after' => '2026-03-09T00:00:00',
+ 'before' => '2026-03-09T23:59:59',
+ )
+ );
+ $next_day = $this->get_rows(
+ array(
+ 'after' => '2026-03-10T00:00:00',
+ 'before' => '2026-03-10T23:59:59',
+ )
+ );
+
+ $this->assertSame( 1, $local_day[5]['signups'], 'A sign-up at 23:30 local time belongs to that local day.' );
+ $this->assertArrayNotHasKey( 5, $next_day, 'A sign-up at 23:30 local time does not belong to the next UTC day.' );
+ }
+
+ /**
+ * @testdox Should count cancelled and sent sign-ups but leave pending ones out entirely.
+ */
+ public function test_signups_exclude_only_pending_rows(): void {
+ $this->insert_row( 1, NotificationStatus::PENDING, '2026-03-02 10:00:00', 'a@example.com' );
+ $this->insert_row( 1, NotificationStatus::CANCELLED, '2026-03-02 10:00:00', 'b@example.com' );
+ $this->insert_row( 1, NotificationStatus::SENT, '2026-03-03 10:00:00', 'c@example.com' );
+ $this->insert_row( 2, NotificationStatus::PENDING, '2026-03-02 10:00:00', 'd@example.com' );
+
+ $rows = $this->get_rows( self::PERIOD );
+
+ $this->assertSame( array( 1 ), array_keys( $rows ), 'A product with only pending sign-ups should not be listed.' );
+ $this->assertSame( 2, $rows[1]['signups'], 'Cancelled and sent sign-ups count, pending ones do not.' );
+ }
+
+ /**
+ * @testdox Should count sends on their own date, listing products with no sign-ups in the period.
+ */
+ public function test_notified_uses_its_own_date(): void {
+ $before = '2026-02-01 10:00:00';
+ $during = '2026-03-03 10:00:00';
+ $this->insert_row( 1, NotificationStatus::SENT, $before, 'a@example.com', $during );
+ $this->insert_row( 2, NotificationStatus::SENT, $during, 'd@example.com', $before );
+ $this->insert_row( 3, NotificationStatus::CANCELLED, $before, 'e@example.com' );
+
+ $rows = $this->get_rows( self::PERIOD );
+
+ $this->assertEqualsCanonicalizing( array( 1, 2 ), array_keys( $rows ), 'A product with no activity in the period is not listed.' );
+ $this->assertSame( 0, $rows[1]['signups'], 'Rows created before the period are not sign-ups.' );
+ $this->assertSame( 0, $rows[1]['customers'], 'A send alone does not make a customer in the period.' );
+ $this->assertSame( 1, $rows[1]['notifications_sent'], 'A send in the period counts, whenever the sign-up was made.' );
+ $this->assertSame( 1, $rows[2]['signups'] );
+ $this->assertSame( 0, $rows[2]['notifications_sent'], 'A send before the period does not count.' );
+ }
+
+ /**
+ * @testdox Should count customers as distinct emails among the period's sign-ups.
+ */
+ public function test_customers_count_distinct_emails_that_signed_up(): void {
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00', 'a@example.com' );
+ $this->insert_row( 1, NotificationStatus::CANCELLED, '2026-03-03 10:00:00', 'a@example.com' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00', 'b@example.com' );
+ $this->insert_row( 1, NotificationStatus::PENDING, '2026-03-02 10:00:00', 'c@example.com' );
+ $this->insert_row( 1, NotificationStatus::SENT, '2026-02-01 10:00:00', 'd@example.com', '2026-03-03 10:00:00' );
+
+ $rows = $this->get_rows( self::PERIOD );
+
+ $this->assertSame( 3, $rows[1]['signups'] );
+ $this->assertSame( 2, $rows[1]['customers'], 'Repeat, pending and earlier sign-ups do not add customers.' );
+ }
+
+ /**
+ * @testdox Should reject an unknown orderby and sort by sign-ups, descending, by default.
+ */
+ public function test_default_order_and_invalid_orderby(): void {
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+ $this->insert_row( 2, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+ $this->insert_row( 2, NotificationStatus::SENT, '2026-03-03 10:00:00' );
+ $this->insert_row( 3, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+ $this->insert_row( 3, NotificationStatus::SENT, '2026-03-03 10:00:00' );
+ $this->insert_row( 3, NotificationStatus::CANCELLED, '2026-03-04 10:00:00' );
+ $this->insert_row( 3, NotificationStatus::ACTIVE, '2026-02-01 10:00:00' );
+
+ $this->assertSame( array( 3, 2, 1 ), array_column( $this->request( self::ENDPOINT, self::PERIOD )->get_data(), 'product_id' ) );
+ $this->assertSame( 400, $this->request( self::ENDPOINT, array_merge( self::PERIOD, array( 'orderby' => 'date' ) ) )->get_status() );
+ }
+
+ /**
+ * @testdox Should sort by $orderby, descending, breaking ties by product ID.
+ * @testWith ["product_id", [3, 2, 1]]
+ * ["signups", [2, 3, 1]]
+ * ["notifications_sent", [1, 3, 2]]
+ * ["customers", [3, 1, 2]]
+ *
+ * @param string $orderby Orderby value.
+ * @param array $expected Product IDs in the expected order.
+ */
+ public function test_accepts_orderby( string $orderby, array $expected ): void {
+ $before = '2026-02-01 10:00:00';
+ $during = '2026-03-03 10:00:00';
+ // Sign-ups: 1, 3 and 2. Customers: 1, 1 (one email signing up three times) and 2. Notifications sent: 1, 0 and 1.
+ $signups_by_product = array(
+ 1 => 1,
+ 2 => 3,
+ 3 => 2,
+ );
+ foreach ( $signups_by_product as $product_id => $signups ) {
+ for ( $i = 0; $i < $signups; $i++ ) {
+ $email = 2 === $product_id ? 'repeat@example.com' : "{$product_id}-{$i}@example.com";
+ $this->insert_row( $product_id, NotificationStatus::ACTIVE, $during, $email );
+ }
+ }
+ foreach ( array( 1, 3 ) as $product_id ) {
+ $this->insert_row( $product_id, NotificationStatus::SENT, $before, "sent-{$product_id}@example.com", $during );
+ }
+
+ $response = $this->request( self::ENDPOINT, array_merge( self::PERIOD, array( 'orderby' => $orderby ) ) );
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertSame( $expected, array_column( $response->get_data(), 'product_id' ) );
+ }
+
+ /**
+ * @testdox Should paginate the rows and report the totals in headers.
+ */
+ public function test_pagination_headers(): void {
+ foreach ( array( 1, 2, 3 ) as $product_id ) {
+ $this->insert_row( $product_id, NotificationStatus::SENT, '2026-03-02 10:00:00' );
+ }
+ $args = array_merge(
+ self::PERIOD,
+ array(
+ 'per_page' => 2,
+ 'orderby' => 'product_id',
+ 'order' => 'asc',
+ )
+ );
+
+ $first = $this->request( self::ENDPOINT, $args );
+ $second = $this->request( self::ENDPOINT, array_merge( $args, array( 'page' => 2 ) ) );
+
+ $this->assertSame( 3, (int) $first->get_headers()['X-WP-Total'] );
+ $this->assertSame( 2, (int) $first->get_headers()['X-WP-TotalPages'] );
+ $this->assertSame( array( 1, 2 ), array_column( $first->get_data(), 'product_id' ) );
+ $this->assertSame( array( 3 ), array_column( $second->get_data(), 'product_id' ) );
+ }
+
+ /**
+ * @testdox Should restrict the rows to the requested products.
+ */
+ public function test_products_filter(): void {
+ foreach ( array( 1, 2, 3 ) as $product_id ) {
+ $this->insert_row( $product_id, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+ }
+
+ $rows = $this->get_rows( array_merge( self::PERIOD, array( 'products' => '1,3' ) ) );
+
+ $this->assertEqualsCanonicalizing( array( 1, 3 ), array_keys( $rows ) );
+ }
+
+ /**
+ * @testdox Should add product details, with a placeholder for deleted products.
+ */
+ public function test_extended_info(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $deleted_id = $product->get_id() + 1000;
+ $this->insert_row( $product->get_id(), NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+ $this->insert_row( $deleted_id, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+
+ $rows = $this->get_rows( array_merge( self::PERIOD, array( 'extended_info' => 'true' ) ) );
+
+ $this->assertSame(
+ array(
+ 'name' => $product->get_name(),
+ 'permalink' => $product->get_permalink(),
+ 'edit_url' => get_edit_post_link( $product->get_id(), 'raw' ),
+ ),
+ $rows[ $product->get_id() ]['extended_info']
+ );
+ $this->assertSame(
+ array(
+ 'name' => "#{$deleted_id} (Deleted)",
+ 'permalink' => '',
+ 'edit_url' => '',
+ ),
+ $rows[ $deleted_id ]['extended_info']
+ );
+ }
+
+ /**
+ * @testdox Should serve cached data until a notification write that changes report data bumps this report's cache version only.
+ */
+ public function test_notification_write_invalidates_cache(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $period = array(
+ 'after' => gmdate( 'Y-m-d', time() - DAY_IN_SECONDS ) . 'T00:00:00',
+ 'before' => gmdate( 'Y-m-d', time() + DAY_IN_SECONDS ) . 'T23:59:59',
+ );
+ $this->insert_row( $product->get_id(), NotificationStatus::ACTIVE, gmdate( 'Y-m-d H:i:s' ) );
+ $this->assertSame( 1, $this->get_rows( $period )[ $product->get_id() ]['signups'] );
+
+ $this->insert_row( $product->get_id(), NotificationStatus::ACTIVE, gmdate( 'Y-m-d H:i:s' ) );
+ $this->assertSame( 1, $this->get_rows( $period )[ $product->get_id() ]['signups'], 'A direct insert should not invalidate the cache.' );
+
+ $version = ReportDataStore::get_cache_version();
+ $global = ReportsCache::get_version();
+ $notification = new Notification();
+ $notification->set_product_id( $product->get_id() );
+ $notification->set_user_email( 'crud@example.com' );
+ $notification->set_status( NotificationStatus::ACTIVE );
+ $notification->save();
+
+ $this->assertNotSame( $version, ReportDataStore::get_cache_version(), 'Saving a notification should invalidate the report cache.' );
+ $this->assertSame( $global, ReportsCache::get_version(), 'Other reports should keep their cache.' );
+ $this->assertSame( 3, $this->get_rows( $period )[ $product->get_id() ]['signups'], 'The report should be recomputed after the bump.' );
+
+ $version = ReportDataStore::get_cache_version();
+ $notification->set_date_last_attempt( time() );
+ $notification->save();
+ $this->assertSame( $version, ReportDataStore::get_cache_version(), 'A send-attempt bookkeeping save should keep the report cache.' );
+
+ $notification->set_status( NotificationStatus::CANCELLED );
+ $notification->save();
+ $this->assertNotSame( $version, ReportDataStore::get_cache_version(), 'A status change should invalidate the report cache.' );
+
+ $version = ReportDataStore::get_cache_version();
+ $notification->delete( true );
+ $this->assertNotSame( $version, ReportDataStore::get_cache_version(), 'Deleting a notification should invalidate the report cache.' );
+ }
+
+ /**
+ * @testdox Should accept a server-side CSV export of the report.
+ */
+ public function test_export_route_accepts_the_report(): void {
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+
+ $request = new WP_REST_Request( 'POST', self::ENDPOINT . '/export' );
+ $request->set_body_params( array( 'report_args' => self::PERIOD ) );
+ $response = $this->server->dispatch( $request );
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertStringContainsString( '/reports/stock-notifications/export/', $response->get_data()['_links']['status'][0]['href'] );
+ }
+
+ /**
+ * @testdox Should export the product name, sign-ups, notifications sent and customers columns.
+ */
+ public function test_export_columns_and_rows(): void {
+ $controller = new Controller();
+ $item = array(
+ 'product_id' => 7,
+ 'signups' => 3,
+ 'notifications_sent' => 2,
+ 'customers' => 1,
+ 'extended_info' => array( 'name' => 'Hoodie' ),
+ );
+
+ $this->assertSame(
+ array( 'product_name', 'signups', 'notifications_sent', 'customers' ),
+ array_keys( $controller->get_export_columns() )
+ );
+ $this->assertSame(
+ array(
+ 'product_name' => 'Hoodie',
+ 'signups' => 3,
+ 'notifications_sent' => 2,
+ 'customers' => 1,
+ ),
+ $controller->prepare_item_for_export( $item )
+ );
+ }
+
+ /**
+ * Get the report rows keyed by product ID.
+ *
+ * @param array $params Query parameters.
+ * @return array<int, array>
+ */
+ private function get_rows( array $params ): array {
+ $response = $this->request( self::ENDPOINT, $params );
+ $this->assertSame( 200, $response->get_status(), 'The report request failed.' );
+
+ return array_column( $response->get_data(), null, 'product_id' );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/ReportTestTrait.php b/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/ReportTestTrait.php
new file mode 100644
index 00000000000..57ffc5ee22d
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/ReportTestTrait.php
@@ -0,0 +1,75 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Admin\API\Reports\StockNotifications;
+
+use Automattic\WooCommerce\Tests\Internal\StockNotifications\StockNotificationsFeatureTrait;
+use WP_REST_Request;
+use WP_REST_Response;
+
+/**
+ * Shared setup and helpers for the stock notifications report tests.
+ */
+trait ReportTestTrait {
+
+ use StockNotificationsFeatureTrait;
+
+ /**
+ * Enable the feature before the first dispatch registers the routes, and start from an empty UTC store.
+ */
+ private function set_up_stock_notifications_report(): void {
+ global $wpdb;
+
+ $this->enable_stock_notifications_feature();
+ wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) );
+ update_option( 'timezone_string', 'UTC' );
+ update_option( 'gmt_offset', 0 );
+ $wpdb->query( "DELETE FROM {$wpdb->prefix}wc_stock_notifications" );
+ }
+
+ /**
+ * Restore the feature option that the transaction rollback does not cover.
+ */
+ private function tear_down_stock_notifications_report(): void {
+ $this->restore_stock_notifications_feature_option();
+ }
+
+ /**
+ * Insert a notification row directly, with exact GMT dates.
+ *
+ * @param int $product_id Product ID.
+ * @param string $status Notification status.
+ * @param string $date_created GMT creation date.
+ * @param string $email Customer email.
+ * @param string|null $date_notified GMT notified date.
+ */
+ private function insert_row( int $product_id, string $status, string $date_created, string $email = 'customer@example.com', ?string $date_notified = null ): void {
+ global $wpdb;
+
+ $wpdb->insert(
+ $wpdb->prefix . 'wc_stock_notifications',
+ array(
+ 'product_id' => $product_id,
+ 'user_id' => 0,
+ 'user_email' => $email,
+ 'status' => $status,
+ 'date_created_gmt' => $date_created,
+ 'date_notified_gmt' => $date_notified,
+ )
+ );
+ }
+
+ /**
+ * Request a report endpoint.
+ *
+ * @param string $route Route.
+ * @param array $params Query parameters.
+ * @return WP_REST_Response
+ */
+ private function request( string $route, array $params ): WP_REST_Response {
+ $request = new WP_REST_Request( 'GET', $route );
+ $request->set_query_params( $params );
+
+ return $this->server->dispatch( $request );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/Stats/ControllerTest.php b/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/Stats/ControllerTest.php
new file mode 100644
index 00000000000..70590ecb2f8
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Admin/API/Reports/StockNotifications/Stats/ControllerTest.php
@@ -0,0 +1,237 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Admin\API\Reports\StockNotifications\Stats;
+
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+use Automattic\WooCommerce\Tests\Admin\API\Reports\StockNotifications\ReportTestTrait;
+use WC_REST_Unit_Test_Case;
+
+/**
+ * Stock notifications stats report API controller test.
+ */
+class ControllerTest extends WC_REST_Unit_Test_Case {
+
+ use ReportTestTrait;
+
+ /**
+ * Endpoint.
+ *
+ * @var string
+ */
+ const ENDPOINT = '/wc-analytics/reports/stock-notifications/stats';
+
+ /**
+ * Period covering 2026-03-01 to 2026-03-07.
+ *
+ * @var array
+ */
+ const PERIOD = array(
+ 'after' => '2026-03-01T00:00:00',
+ 'before' => '2026-03-07T23:59:59',
+ );
+
+ /**
+ * Set up.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->set_up_stock_notifications_report();
+ }
+
+ /**
+ * Tear down.
+ */
+ public function tearDown(): void {
+ try {
+ $this->tear_down_stock_notifications_report();
+ } finally {
+ parent::tearDown();
+ }
+ }
+
+ /**
+ * @testdox Should bucket a sign-up on the site-time day it was made, not the next UTC day.
+ */
+ public function test_intervals_use_site_timezone(): void {
+ update_option( 'timezone_string', 'America/Los_Angeles' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-10 06:30:00' );
+
+ $stats = $this->get_stats(
+ array(
+ 'after' => '2026-03-09T00:00:00',
+ 'before' => '2026-03-10T23:59:59',
+ 'order' => 'asc',
+ )
+ );
+ $next_day = $this->get_stats(
+ array(
+ 'after' => '2026-03-10T00:00:00',
+ 'before' => '2026-03-10T23:59:59',
+ )
+ );
+
+ $this->assertSame(
+ array(
+ '2026-03-09' => 1,
+ '2026-03-10' => 0,
+ ),
+ array_column( array_map( array( $this, 'flatten_interval' ), $stats['intervals'] ), 'signups', 'interval' )
+ );
+ $this->assertSame( 0, $next_day['totals']['signups'], 'A sign-up at 23:30 local time does not belong to the next UTC day.' );
+ }
+
+ /**
+ * @testdox Should compute totals from non-pending sign-ups and sends in the period.
+ */
+ public function test_totals(): void {
+ $this->insert_row( 1, NotificationStatus::PENDING, '2026-03-02 10:00:00', 'pending@example.com' );
+ $this->insert_row( 1, NotificationStatus::CANCELLED, '2026-03-02 10:00:00', 'a@example.com' );
+ $this->insert_row( 1, NotificationStatus::SENT, '2026-03-03 10:00:00', 'a@example.com', '2026-03-04 10:00:00' );
+ $this->insert_row( 2, NotificationStatus::ACTIVE, '2026-03-05 10:00:00', 'b@example.com' );
+ $this->insert_row( 2, NotificationStatus::ACTIVE, '2026-01-01 10:00:00', 'c@example.com', '2026-03-06 10:00:00' );
+ $this->insert_row( 3, NotificationStatus::SENT, '2026-01-01 10:00:00', 'd@example.com', '2026-02-01 10:00:00' );
+
+ $stats = $this->get_stats( self::PERIOD );
+
+ $this->assertEquals(
+ array(
+ 'signups' => 3,
+ 'notifications_sent' => 2,
+ 'customers' => 2,
+ 'products_count' => 2,
+ ),
+ $stats['totals'],
+ 'Products 1 and 2 have activity in the period; 3 was sent before it. a@ signed up twice.'
+ );
+ $sent = array_column( array_map( array( $this, 'flatten_interval' ), $stats['intervals'] ), 'notifications_sent', 'interval' );
+ $this->assertSame( 1, $sent['2026-03-04'] );
+ $this->assertSame( 1, $sent['2026-03-06'] );
+ }
+
+ /**
+ * @testdox Should count customers as distinct within each interval and within the totals.
+ */
+ public function test_customers_are_distinct_per_interval_and_period(): void {
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00', 'a@example.com' );
+ $this->insert_row( 2, NotificationStatus::ACTIVE, '2026-03-02 11:00:00', 'a@example.com' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-03 10:00:00', 'a@example.com' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-03 10:00:00', 'b@example.com' );
+
+ $stats = $this->get_stats( self::PERIOD );
+
+ $customers = array_column( array_map( array( $this, 'flatten_interval' ), $stats['intervals'] ), 'customers', 'interval' );
+ $this->assertSame( 1, $customers['2026-03-02'] );
+ $this->assertSame( 2, $customers['2026-03-03'] );
+ $this->assertSame( 2, $stats['totals']['customers'], 'A customer signing up on two days counts once in the totals.' );
+ }
+
+ /**
+ * @testdox Should sort intervals by a metric left out of the requested fields.
+ */
+ public function test_orderby_a_field_that_is_not_requested(): void {
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00', 'a@example.com', '2026-03-02 12:00:00' );
+
+ $stats = $this->get_stats(
+ array(
+ 'after' => '2026-03-02T00:00:00',
+ 'before' => '2026-03-02T23:59:59',
+ 'fields' => array( 'notifications_sent' ),
+ 'orderby' => 'signups',
+ )
+ );
+
+ $this->assertSame( array( 'notifications_sent' => 1 ), $stats['totals'] );
+ $this->assertCount( 1, $stats['intervals'] );
+ $this->assertSame( array( 'notifications_sent' => 1 ), $stats['intervals'][0]['subtotals'] );
+ }
+
+ /**
+ * @testdox Should zero-fill every interval of a period without rows.
+ */
+ public function test_intervals_are_zero_filled(): void {
+ $stats = $this->get_stats( self::PERIOD );
+
+ $this->assertCount( 7, $stats['intervals'] );
+ foreach ( $stats['intervals'] as $interval ) {
+ $this->assertEquals(
+ array(
+ 'signups' => 0,
+ 'customers' => 0,
+ 'notifications_sent' => 0,
+ ),
+ $interval['subtotals'],
+ "Interval {$interval['interval']} should be zero-filled."
+ );
+ }
+ }
+
+ /**
+ * @testdox Should return only the requested fields.
+ */
+ public function test_fields_param(): void {
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-02 10:00:00' );
+
+ $stats = $this->get_stats( array_merge( self::PERIOD, array( 'fields' => array( 'signups' ) ) ) );
+
+ $this->assertSame( array( 'signups' => 1 ), $stats['totals'] );
+ foreach ( $stats['intervals'] as $interval ) {
+ $this->assertSame( array( 'signups' ), array_keys( $interval['subtotals'] ), "Interval {$interval['interval']} has unrequested fields." );
+ }
+ }
+
+ /**
+ * @testdox Should page date-ordered intervals on site-time days when rows are sparse.
+ */
+ public function test_date_ordered_paging_uses_site_timezone(): void {
+ update_option( 'timezone_string', 'America/Los_Angeles' );
+ // Local times (UTC-8): 03-02 20:00, 03-03 00:30, 03-03 23:30, 03-04 20:00. 03-01 and 03-05 stay empty.
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-03 04:00:00', 'b@example.com' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-03 08:30:00', 'c@example.com' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-04 07:30:00', 'd@example.com' );
+ $this->insert_row( 1, NotificationStatus::ACTIVE, '2026-03-05 04:00:00', 'e@example.com' );
+
+ $stats = $this->get_stats(
+ array(
+ 'after' => '2026-03-01T00:00:00',
+ 'before' => '2026-03-05T23:59:59',
+ 'interval' => 'day',
+ 'orderby' => 'date',
+ 'order' => 'asc',
+ 'per_page' => 2,
+ 'page' => 2,
+ )
+ );
+
+ $this->assertSame(
+ array(
+ '2026-03-03' => 2,
+ '2026-03-04' => 1,
+ ),
+ array_column( array_map( array( $this, 'flatten_interval' ), $stats['intervals'] ), 'signups', 'interval' )
+ );
+ }
+
+ /**
+ * Get the stats response data.
+ *
+ * @param array $params Query parameters.
+ * @return array
+ */
+ private function get_stats( array $params ): array {
+ $response = $this->request( self::ENDPOINT, $params );
+ $this->assertSame( 200, $response->get_status(), 'The stats request failed.' );
+
+ return json_decode( (string) wp_json_encode( $response->get_data() ), true );
+ }
+
+ /**
+ * Flatten an interval to its id and subtotals.
+ *
+ * @param array $interval Interval.
+ * @return array
+ */
+ private function flatten_interval( array $interval ): array {
+ return array_merge( array( 'interval' => $interval['interval'] ), $interval['subtotals'] );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Admin/ReportCSVEmailTest.php b/plugins/woocommerce/tests/php/src/Admin/ReportCSVEmailTest.php
index 99f7f784ad9..038690be869 100644
--- a/plugins/woocommerce/tests/php/src/Admin/ReportCSVEmailTest.php
+++ b/plugins/woocommerce/tests/php/src/Admin/ReportCSVEmailTest.php
@@ -128,6 +128,15 @@ class ReportCSVEmailTest extends WC_Unit_Test_Case {
);
}
+ /**
+ * @testdox The Stock notifications report export names its report in the subject.
+ */
+ public function test_subject_names_the_stock_notifications_report(): void {
+ $subject = $this->trigger_and_get_subject( '', 'stock-notifications' );
+
+ $this->assertStringContainsString( 'Your Stock notifications Report download is ready', $subject );
+ }
+
/**
* @testdox trigger() keeps the parameters it shipped with, so a subclass overriding it still loads.
*/
@@ -144,10 +153,11 @@ class ReportCSVEmailTest extends WC_Unit_Test_Case {
/**
* Send the email to a user and return the subject it went out with.
*
- * @param string $date_range Optional. Date range the report covers, formatted for display.
+ * @param string $date_range Optional. Date range the report covers, formatted for display.
+ * @param string $report_type Optional. Report type being exported.
* @return string
*/
- private function trigger_and_get_subject( string $date_range = '' ): string {
+ private function trigger_and_get_subject( string $date_range = '', string $report_type = 'orders' ): string {
$user_id = $this->factory->user->create( array( 'role' => 'administrator' ) );
$mailer = tests_retrieve_phpmailer_instance();
$email = new ReportCSVEmail();
@@ -155,8 +165,8 @@ class ReportCSVEmailTest extends WC_Unit_Test_Case {
$email->set_report_date_range( $date_range );
$email->trigger(
$user_id,
- 'orders',
- 'https://example.org/?action=woocommerce_admin_download_report_csv&filename=wc-orders-report-export'
+ $report_type,
+ "https://example.org/?action=woocommerce_admin_download_report_csv&filename=wc-{$report_type}-report-export"
);
$sent = end( $mailer->mock_sent );