Commit 78a273bece8 for woocommerce

commit 78a273bece87b23cbd80c745984273907146c1b3
Author: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
Date:   Mon Nov 30 12:05:35 2026 +0200

    Add stock notification columns to the Analytics Stock report (#70667)

    * feat: add stock notification columns to the Analytics Stock report

    * fix: show no days waiting when a product has no active sign-ups

    * refactor: move stock report notification columns into a subscriber

    * fix: scope stock report sign-up sorting and fix one-product pages

    * fix: skip cached post IDs when sorting the stock report by sign-ups

    * refactor: sort the stock report by sign-ups through analytics clause filters

    * refactor: keep only a Waiting for stock column in the stock report

    * test: clear all stock report REST fields in feature test cleanup

    * test: build stock report routes per test so sorting by sign-ups is allowed

    * fix: tolerate one-arg stock clause filters and test the real CSV export path

    * fix: Join only string stock report clauses and tag new hooks 11.5.0

diff --git a/plugins/woocommerce/changelog/add-stock-report-notification-columns b/plugins/woocommerce/changelog/add-stock-report-notification-columns
new file mode 100644
index 00000000000..0253678f333
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-stock-report-notification-columns
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add a Waiting for stock column to the Analytics Stock report when Back in stock notifications is enabled.
diff --git a/plugins/woocommerce/client/admin/client/analytics/report/stock/table.js b/plugins/woocommerce/client/admin/client/analytics/report/stock/table.js
index 92473f7a072..09b67856aab 100644
--- a/plugins/woocommerce/client/admin/client/analytics/report/stock/table.js
+++ b/plugins/woocommerce/client/admin/client/analytics/report/stock/table.js
@@ -16,8 +16,12 @@ import { CurrencyContext } from '@woocommerce/currency';
 import ReportTable from '../../components/report-table';
 import { isLowStock } from './utils';
 import { getAdminSetting } from '~/utils/admin-settings';
+import { isFeatureEnabled } from '~/utils/features';

 const stockStatuses = getAdminSetting( 'stockStatuses', {} );
+const showStockNotifications = isFeatureEnabled(
+	'customer_stock_notifications'
+);

 class StockReportTable extends Component {
 	constructor() {
@@ -29,7 +33,7 @@ class StockReportTable extends Component {
 	}

 	getHeadersContent() {
-		return [
+		const headers = [
 			{
 				label: __( 'Product / Variation', 'woocommerce' ),
 				key: 'title',
@@ -54,6 +58,17 @@ class StockReportTable extends Component {
 				isSortable: true,
 			},
 		];
+
+		if ( showStockNotifications ) {
+			headers.push( {
+				label: __( 'Waiting for stock', 'woocommerce' ),
+				key: 'active_signups',
+				isSortable: true,
+				isNumeric: true,
+			} );
+		}
+
+		return headers;
 	}

 	getRowsContent( products = [] ) {
@@ -69,6 +84,7 @@ class StockReportTable extends Component {
 				stock_quantity: stockQuantity,
 				stock_status: stockStatus,
 				low_stock_amount: lowStockAmount,
+				active_signups: activeSignups = 0,
 			} = product;

 			const name = decodeEntities( product.name );
@@ -109,7 +125,7 @@ class StockReportTable extends Component {
 				</Link>
 			);

-			return [
+			const row = [
 				{
 					display: nameLink,
 					value: name,
@@ -133,6 +149,19 @@ class StockReportTable extends Component {
 					value: stockQuantity,
 				},
 			];
+
+			if ( showStockNotifications ) {
+				row.push( {
+					display: formatValue(
+						this.context.getCurrencyConfig(),
+						'number',
+						activeSignups
+					),
+					value: activeSignups,
+				} );
+			}
+
+			return row;
 		} );
 	}

diff --git a/plugins/woocommerce/src/Admin/API/Reports/Stock/Controller.php b/plugins/woocommerce/src/Admin/API/Reports/Stock/Controller.php
index a8b8fd167e0..bbc2bc408cd 100644
--- a/plugins/woocommerce/src/Admin/API/Reports/Stock/Controller.php
+++ b/plugins/woocommerce/src/Admin/API/Reports/Stock/Controller.php
@@ -135,6 +135,18 @@ class Controller extends GenericController implements ExportableInterface {
 		remove_filter( 'posts_groupby', array( __CLASS__, 'add_wp_query_group_by' ), 10 );
 		remove_filter( 'posts_clauses', array( __CLASS__, 'add_wp_query_orderby' ), 10 );

+		/**
+		 * Fires after a page of stock report products is loaded, before its items are prepared.
+		 *
+		 * Lets code that adds fields to the report load their data with one query per page.
+		 *
+		 * @since 11.5.0
+		 *
+		 * @param WP_REST_Request $request  The request.
+		 * @param array           $products The products on this page.
+		 */
+		do_action( 'woocommerce_analytics_stock_report_products_loaded', $request, $query_results['objects'] );
+
 		$objects = array();
 		foreach ( $query_results['objects'] as $object ) {
 			$data      = $this->prepare_item_for_response( $object, $request );
@@ -276,6 +288,29 @@ class Controller extends GenericController implements ExportableInterface {
 				break;
 		}

+		/**
+		 * Filters the stock report's JOIN clauses, like `woocommerce_analytics_clauses_join_{context}` in the other reports.
+		 *
+		 * @since 11.5.0
+		 *
+		 * @param string[] $clauses  The JOIN clauses.
+		 * @param object   $wp_query The stock report `WP_Query`.
+		 */
+		$join = apply_filters( 'woocommerce_analytics_clauses_join_stock', array( $args['join'] ), $wp_query );
+
+		/**
+		 * Filters the stock report's ORDER BY clauses, like `woocommerce_analytics_clauses_order_by_{context}` in the other reports.
+		 *
+		 * @since 11.5.0
+		 *
+		 * @param string[] $clauses  The ORDER BY clauses, without the `ORDER BY` keyword.
+		 * @param object   $wp_query The stock report `WP_Query`.
+		 */
+		$order_by = apply_filters( 'woocommerce_analytics_clauses_order_by_stock', array( $args['orderby'] ), $wp_query );
+
+		$args['join']    = is_array( $join ) ? implode( ' ', array_filter( $join, 'is_string' ) ) : $args['join'];
+		$args['orderby'] = is_array( $order_by ) ? implode( ' ', array_filter( $order_by, 'is_string' ) ) : $args['orderby'];
+
 		return $args;
 	}

diff --git a/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php b/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
index 9840c2a0422..3a42685b135 100644
--- a/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
+++ b/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
@@ -121,6 +121,7 @@ class StockNotifications implements RegisterHooksInterface {
 		$container->get( DataRetentionController::class );
 		$container->get( Telemetry::class );
 		$container->get( StockNotificationsRestController::class )->register();
+		$container->get( StockReportColumns::class );

 		$container->get( NotificationManagementService::class );
 		$container->get( MyAccountEndpoint::class );
diff --git a/plugins/woocommerce/src/Internal/StockNotifications/StockReportColumns.php b/plugins/woocommerce/src/Internal/StockNotifications/StockReportColumns.php
new file mode 100644
index 00000000000..c296bbd7ef6
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/StockNotifications/StockReportColumns.php
@@ -0,0 +1,210 @@
+<?php
+/**
+ * Back in stock notification columns for the Analytics Stock report.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\StockNotifications;
+
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Adds the Waiting for stock column to the Analytics Stock report.
+ */
+class StockReportColumns {
+
+	/**
+	 * Active sign-up counts for the current report page, keyed by product ID.
+	 *
+	 * @var array<int, int>
+	 */
+	private array $counts = array();
+
+	/**
+	 * Constructor.
+	 */
+	public function __construct() {
+		add_filter( 'woocommerce_analytics_orderby_enum_reports/stock', array( $this, 'add_orderby_options' ) );
+		add_filter( 'woocommerce_analytics_clauses_join_stock', array( $this, 'add_orderby_join' ), 10, 2 );
+		add_filter( 'woocommerce_analytics_clauses_order_by_stock', array( $this, 'add_orderby_clauses' ), 10, 2 );
+		add_action( 'woocommerce_analytics_stock_report_products_loaded', array( $this, 'load_counts' ), 10, 2 );
+		add_filter( 'woocommerce_report_stock_export_columns', array( $this, 'add_export_columns' ) );
+		add_filter( 'woocommerce_report_stock_prepare_export_item', array( $this, 'add_export_values' ), 10, 2 );
+
+		// Registered here, not on `rest_api_init`: the CSV export reads the report outside a REST request.
+		register_rest_field(
+			'report_stock',
+			'active_signups',
+			array(
+				'get_callback' => fn( $item ) => $this->counts[ $item['id'] ] ?? 0,
+				'schema'       => array(
+					'description' => __( 'Number of customers waiting for a back in stock notification.', 'woocommerce' ),
+					'type'        => 'integer',
+					'context'     => array( 'view', 'edit' ),
+					'readonly'    => true,
+				),
+			)
+		);
+	}
+
+	/**
+	 * Allow sorting the report by the new column.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $options The orderby enum.
+	 * @return mixed
+	 */
+	public function add_orderby_options( $options ) {
+		return is_array( $options ) ? array_merge( $options, array( 'active_signups' ) ) : $options;
+	}
+
+	/**
+	 * Join the active sign-up counts when the stock report is sorted by them.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $clauses  The JOIN clauses.
+	 * @param mixed $wp_query The stock report query.
+	 * @return mixed
+	 */
+	public function add_orderby_join( $clauses, $wp_query = null ) {
+		if ( ! is_array( $clauses ) || ! $this->is_sorted_by_signups( $wp_query ) ) {
+			return $clauses;
+		}
+
+		// Sign-up changes don't bust WP_Query's cached post IDs, so a cached order would go stale.
+		$wp_query->set( 'cache_results', false );
+
+		$clauses[] = $this->get_counts_join();
+
+		return $clauses;
+	}
+
+	/**
+	 * Sort the stock report by active sign-ups.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $clauses  The ORDER BY clauses.
+	 * @param mixed $wp_query The stock report query.
+	 * @return mixed
+	 */
+	public function add_orderby_clauses( $clauses, $wp_query = null ) {
+		if ( ! is_array( $clauses ) || ! $this->is_sorted_by_signups( $wp_query ) ) {
+			return $clauses;
+		}
+
+		global $wpdb;
+
+		$order = $wp_query->get( 'order' );
+		$order = is_string( $order ) && 'ASC' === strtoupper( $order ) ? 'ASC' : 'DESC';
+
+		return array( " COALESCE( sn.sn_count, 0 ) {$order}, {$wpdb->posts}.ID {$order} " );
+	}
+
+	/**
+	 * Load the active sign-up counts for a page of report products with one query.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $request  The report request.
+	 * @param mixed $products The products on this page.
+	 */
+	public function load_counts( $request, $products ): void {
+		global $wpdb;
+
+		$this->counts = array();
+
+		$product_ids = array_map( fn( $product ) => $product->get_id(), array_filter( is_array( $products ) ? $products : array(), fn( $product ) => $product instanceof \WC_Product ) );
+		if ( empty( $product_ids ) ) {
+			return;
+		}
+
+		$placeholders = implode( ', ', array_fill( 0, count( $product_ids ), '%d' ) );
+
+		// phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $placeholders is a list of %d placeholders.
+		$rows = $wpdb->get_results(
+			$wpdb->prepare(
+				"SELECT product_id, COUNT(*) AS active_signups
+				FROM {$wpdb->prefix}wc_stock_notifications
+				WHERE status = %s AND product_id IN ( {$placeholders} )
+				GROUP BY product_id",
+				array_merge( array( NotificationStatus::ACTIVE ), $product_ids )
+			)
+		);
+		// phpcs:enable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+
+		foreach ( (array) $rows as $row ) {
+			$this->counts[ (int) $row->product_id ] = (int) $row->active_signups;
+		}
+	}
+
+	/**
+	 * Add the new column to the CSV export.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $columns Column labels keyed by ID.
+	 * @return mixed
+	 */
+	public function add_export_columns( $columns ) {
+		if ( ! is_array( $columns ) ) {
+			return $columns;
+		}
+
+		$columns['active_signups'] = __( 'Waiting for stock', 'woocommerce' );
+
+		return $columns;
+	}
+
+	/**
+	 * Add the new column's value to a CSV export row.
+	 *
+	 * @internal
+	 *
+	 * @param mixed $export_item The export row.
+	 * @param mixed $item        The report item.
+	 * @return mixed
+	 */
+	public function add_export_values( $export_item, $item ) {
+		if ( ! is_array( $export_item ) || ! is_array( $item ) ) {
+			return $export_item;
+		}
+
+		$export_item['active_signups'] = $item['active_signups'] ?? 0;
+
+		return $export_item;
+	}
+
+	/**
+	 * Whether the stock report query is sorted by active sign-ups.
+	 *
+	 * @param mixed $wp_query The stock report query.
+	 * @return bool
+	 */
+	private function is_sorted_by_signups( $wp_query ): bool {
+		return $wp_query instanceof \WP_Query && 'active_signups' === $wp_query->get( 'orderby' );
+	}
+
+	/**
+	 * Join the active sign-up count per product, for sorting.
+	 *
+	 * @return string
+	 */
+	private function get_counts_join(): string {
+		global $wpdb;
+
+		$status = NotificationStatus::ACTIVE;
+
+		return " LEFT JOIN (
+			SELECT product_id, COUNT(*) AS sn_count
+			FROM {$wpdb->prefix}wc_stock_notifications
+			WHERE status = '{$status}'
+			GROUP BY product_id
+		) sn ON sn.product_id = {$wpdb->posts}.ID ";
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Admin/API/Reports/Stock/ControllerTest.php b/plugins/woocommerce/tests/php/src/Admin/API/Reports/Stock/ControllerTest.php
index 624060272ea..be07305c7ff 100644
--- a/plugins/woocommerce/tests/php/src/Admin/API/Reports/Stock/ControllerTest.php
+++ b/plugins/woocommerce/tests/php/src/Admin/API/Reports/Stock/ControllerTest.php
@@ -4,8 +4,15 @@ declare( strict_types = 1 );

 namespace Automattic\WooCommerce\Tests\Admin\API\Reports\Stock;

+use Automattic\WooCommerce\Admin\API\Reports\Stock\Controller;
 use Automattic\WooCommerce\Enums\ProductStatus;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+use Automattic\WooCommerce\Internal\StockNotifications\StockNotifications;
+use Automattic\WooCommerce\Internal\StockNotifications\StockReportColumns;
+use Automattic\WooCommerce\Tests\Internal\StockNotifications\StockNotificationsFeatureTrait;
 use WC_Product_Simple;
+use WC_Product_Variable;
+use WC_Product_Variation;
 use WC_REST_Unit_Test_Case;
 use WP_REST_Request;

@@ -13,6 +20,8 @@ use WP_REST_Request;
  * Stock report API controller test.
  */
 class ControllerTest extends WC_REST_Unit_Test_Case {
+	use StockNotificationsFeatureTrait;
+
 	/**
 	 * Endpoint.
 	 *
@@ -20,12 +29,22 @@ class ControllerTest extends WC_REST_Unit_Test_Case {
 	 */
 	const ENDPOINT = '/wc-analytics/reports/stock';

+	/**
+	 * Build routes per test: the orderby enum depends on whether the feature's columns are attached.
+	 *
+	 * @var bool
+	 */
+	protected static $reuse_rest_server = false;
+
 	/**
 	 * Set up.
 	 */
 	public function setUp(): void {
 		parent::setUp();

+		$this->stock_notifications_original_feature_option = get_option( StockNotifications::ENABLE_OPTION_NAME, false );
+		update_option( StockNotifications::ENABLE_OPTION_NAME, 'no' );
+
 		wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) );
 	}

@@ -34,6 +53,7 @@ class ControllerTest extends WC_REST_Unit_Test_Case {
 	 */
 	public function tearDown(): void {
 		unset( $GLOBALS['current_screen'] );
+		$this->restore_stock_notifications_feature_option();

 		parent::tearDown();
 	}
@@ -76,6 +96,253 @@ class ControllerTest extends WC_REST_Unit_Test_Case {
 		$this->assertSame( $expected, $this->get_report( $ids ), 'The stock report lists the wrong products in an admin context.' );
 	}

+	/**
+	 * @testdox Should leave out the stock notification columns and sorts when the feature is disabled.
+	 */
+	public function test_notification_columns_absent_when_feature_disabled(): void {
+		$product = $this->create_product( ProductStatus::PUBLISH );
+		$this->insert_notification( $product->get_id(), NotificationStatus::ACTIVE );
+
+		$request  = new WP_REST_Request( 'GET', self::ENDPOINT );
+		$response = $this->server->dispatch( $request );
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertNotEmpty( $response->get_data() );
+		$this->assertArrayNotHasKey( 'active_signups', $response->get_data()[0] );
+
+		$schema = $this->server->dispatch( new WP_REST_Request( 'OPTIONS', self::ENDPOINT ) )->get_data()['schema']['properties'];
+		$this->assertArrayNotHasKey( 'active_signups', $schema );
+
+		$request = new WP_REST_Request( 'GET', self::ENDPOINT );
+		$request->set_param( 'orderby', 'active_signups' );
+		$this->assertSame( 400, $this->server->dispatch( $request )->get_status(), 'Sorting by active_signups should be rejected.' );
+	}
+
+	/**
+	 * The CSV export calls `get_items()` outside a REST request, so the counts must load there too.
+	 *
+	 * @testdox Should export active sign-up counts only when the feature is enabled.
+	 */
+	public function test_export_includes_active_signups_when_feature_enabled(): void {
+		$controller = new Controller();
+		$this->assertArrayNotHasKey( 'active_signups', $controller->get_export_columns() );
+
+		$this->enable_stock_notification_columns();
+		$ids = $this->create_notification_fixture();
+		$this->assertArrayHasKey( 'active_signups', $controller->get_export_columns() );
+
+		$request = new WP_REST_Request( 'GET', self::ENDPOINT );
+		$request->set_default_params( wp_list_pluck( array_filter( $controller->get_collection_params(), fn( $param ) => isset( $param['default'] ) ), 'default' ) );
+		$request->set_param( 'include', array_values( $ids ) );
+
+		$actual = array();
+		foreach ( $controller->get_items( $request )->get_data() as $item ) {
+			$actual[ $item['id'] ] = $controller->prepare_item_for_export( $item )['active_signups'];
+		}
+
+		$this->assertSame( 2, $actual[ $ids['simple_a'] ] );
+		$this->assertSame( 0, $actual[ $ids['none'] ] );
+		$this->assertSame( 3, $actual[ $ids['variation'] ] );
+	}
+
+	/**
+	 * @testdox Should report active sign-ups per product and variation when the feature is enabled.
+	 */
+	public function test_notification_columns_report_active_signups(): void {
+		$this->enable_stock_notification_columns();
+		$ids = $this->create_notification_fixture();
+
+		$schema = $this->server->dispatch( new WP_REST_Request( 'OPTIONS', self::ENDPOINT ) )->get_data()['schema']['properties'];
+		$this->assertArrayHasKey( 'active_signups', $schema );
+
+		$request = new WP_REST_Request( 'GET', self::ENDPOINT );
+		$request->set_param( 'include', implode( ',', $ids ) );
+		$request->set_param( 'orderby', 'id' );
+		$response = $this->server->dispatch( $request );
+		$this->assertSame( 200, $response->get_status() );
+
+		$actual = array();
+		foreach ( $response->get_data() as $item ) {
+			$actual[ $item['id'] ] = $item['active_signups'];
+		}
+
+		$this->assertSame(
+			array(
+				$ids['simple_a']  => 2,
+				$ids['simple_b']  => 1,
+				$ids['none']      => 0,
+				$ids['parent']    => 0,
+				$ids['variation'] => 3,
+			),
+			array_replace( array_fill_keys( $ids, null ), $actual )
+		);
+	}
+
+	/**
+	 * @testdox Should report the stock notification columns for a page holding a single product.
+	 */
+	public function test_notification_columns_for_single_product_page(): void {
+		$this->enable_stock_notification_columns();
+		$product_id = $this->create_product( ProductStatus::PUBLISH )->get_id();
+		$this->insert_notification( $product_id, NotificationStatus::ACTIVE );
+		$this->insert_notification( $product_id, NotificationStatus::ACTIVE );
+
+		$request = new WP_REST_Request( 'GET', self::ENDPOINT );
+		$request->set_param( 'include', (string) $product_id );
+		$response = $this->server->dispatch( $request );
+
+		$this->assertSame( 200, $response->get_status() );
+		$this->assertCount( 1, $response->get_data() );
+		$this->assertSame( 2, $response->get_data()[0]['active_signups'] );
+	}
+
+	/**
+	 * @testdox Should not sort other product queries by the stock notification columns.
+	 */
+	public function test_orderby_clauses_only_apply_to_the_report(): void {
+		global $wpdb;
+
+		$this->enable_stock_notification_columns();
+
+		$query = new \WP_Query(
+			array(
+				'post_type' => 'product',
+				'orderby'   => 'active_signups',
+				'order'     => 'DESC',
+			)
+		);
+
+		$this->assertStringNotContainsString( $wpdb->prefix . 'wc_stock_notifications', $query->request );
+	}
+
+	/**
+	 * @testdox Should sort by active sign-up count in both orders.
+	 */
+	public function test_orderby_active_signups(): void {
+		$this->enable_stock_notification_columns();
+		$ids = $this->create_notification_fixture();
+
+		$this->assertSame(
+			array( $ids['variation'], $ids['simple_a'], $ids['simple_b'] ),
+			array_slice( $this->get_sorted_ids( $ids, 'active_signups', 'desc' ), 0, 3 )
+		);
+		$this->assertSame(
+			array( $ids['simple_b'], $ids['simple_a'], $ids['variation'] ),
+			array_slice( $this->get_sorted_ids( $ids, 'active_signups', 'asc' ), 2 )
+		);
+	}
+
+	/**
+	 * @testdox Should not serve a cached order when sign-ups change between report requests.
+	 */
+	public function test_orderby_active_signups_is_not_cached(): void {
+		$this->enable_stock_notification_columns();
+		$ids = $this->create_notification_fixture();
+
+		$this->assertSame( $ids['variation'], $this->get_sorted_ids( $ids, 'active_signups', 'desc' )[0] );
+
+		$this->insert_notification( $ids['simple_b'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['simple_b'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['simple_b'], NotificationStatus::ACTIVE );
+
+		$this->assertSame( $ids['simple_b'], $this->get_sorted_ids( $ids, 'active_signups', 'desc' )[0] );
+	}
+
+	/**
+	 * @testdox Should attach the report columns when the feature's services are wired up.
+	 */
+	public function test_feature_wires_up_report_columns(): void {
+		update_option( StockNotifications::ENABLE_OPTION_NAME, 'yes' );
+		$this->init_stock_notifications_services();
+
+		$schema = $this->server->dispatch( new WP_REST_Request( 'OPTIONS', self::ENDPOINT ) )->get_data()['schema']['properties'];
+		$this->assertArrayHasKey( 'active_signups', $schema );
+	}
+
+	/**
+	 * Enable the feature and attach the report columns, which the feature wires up once at `init`.
+	 */
+	private function enable_stock_notification_columns(): void {
+		update_option( StockNotifications::ENABLE_OPTION_NAME, 'yes' );
+		new StockReportColumns();
+	}
+
+	/**
+	 * Create three simple products, one without sign-ups, and a variable product with one variation, plus their notifications.
+	 *
+	 * @return array<string, int> Product IDs keyed by role.
+	 */
+	private function create_notification_fixture(): array {
+		$parent = new WC_Product_Variable();
+		$parent->set_name( 'Test variable product' );
+		$parent->save();
+
+		$variation = new WC_Product_Variation();
+		$variation->set_parent_id( $parent->get_id() );
+		$variation->set_regular_price( 5 );
+		$variation->save();
+
+		$ids = array(
+			'simple_a'  => $this->create_product( ProductStatus::PUBLISH )->get_id(),
+			'simple_b'  => $this->create_product( ProductStatus::PUBLISH )->get_id(),
+			'none'      => $this->create_product( ProductStatus::PUBLISH )->get_id(),
+			'parent'    => $parent->get_id(),
+			'variation' => $variation->get_id(),
+		);
+
+		$this->insert_notification( $ids['simple_a'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['simple_a'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['simple_a'], NotificationStatus::SENT );
+		$this->insert_notification( $ids['simple_b'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['simple_b'], NotificationStatus::PENDING );
+		$this->insert_notification( $ids['none'], NotificationStatus::CANCELLED );
+		$this->insert_notification( $ids['variation'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['variation'], NotificationStatus::ACTIVE );
+		$this->insert_notification( $ids['variation'], NotificationStatus::ACTIVE );
+
+		return $ids;
+	}
+
+	/**
+	 * Insert a stock notification row directly.
+	 *
+	 * @param int    $product_id Product or variation ID.
+	 * @param string $status     Notification status.
+	 */
+	private function insert_notification( int $product_id, string $status ): void {
+		global $wpdb;
+
+		$wpdb->insert(
+			$wpdb->prefix . 'wc_stock_notifications',
+			array(
+				'product_id'       => $product_id,
+				'user_id'          => 0,
+				'user_email'       => wp_generate_password( 8, false ) . '@example.com',
+				'status'           => $status,
+				'date_created_gmt' => gmdate( 'Y-m-d H:i:s' ),
+			)
+		);
+	}
+
+	/**
+	 * Request the stock report for the given products, sorted.
+	 *
+	 * @param int[]  $ids     Product IDs to report on.
+	 * @param string $orderby Sort column.
+	 * @param string $order   Sort direction.
+	 * @return int[] Reported product IDs in order.
+	 */
+	private function get_sorted_ids( array $ids, string $orderby, string $order ): array {
+		$request = new WP_REST_Request( 'GET', self::ENDPOINT );
+		$request->set_param( 'include', implode( ',', $ids ) );
+		$request->set_param( 'orderby', $orderby );
+		$request->set_param( 'order', $order );
+
+		$response = $this->server->dispatch( $request );
+		$this->assertSame( 200, $response->get_status() );
+
+		return wp_list_pluck( $response->get_data(), 'id' );
+	}
+
 	/**
 	 * Create a product with the given status.
 	 *
diff --git a/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsFeatureTrait.php b/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsFeatureTrait.php
index f728e06a4ba..2223824c89c 100644
--- a/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsFeatureTrait.php
+++ b/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsFeatureTrait.php
@@ -49,9 +49,11 @@ trait StockNotificationsFeatureTrait {
 	}

 	/**
-	 * Restore the feature option to its pre-test value.
+	 * Restore the feature option to its pre-test value, and drop the Stock report field the feature's services register.
 	 */
 	private function restore_stock_notifications_feature_option(): void {
+		unset( $GLOBALS['wp_rest_additional_fields']['report_stock'] );
+
 		if ( false === $this->stock_notifications_original_feature_option ) {
 			delete_option( StockNotifications::ENABLE_OPTION_NAME );
 		} else {