Commit b005712fa59 for woocommerce
commit b005712fa59e8e26eaf3dad27e25a8b4faf58dc5
Author: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
Date: Thu Nov 26 14:31:02 2026 +0200
Add a read-only wc/v3/stock-notifications REST controller (#69885)
* feat: add read-only wc/v3/stock-notifications REST controller
Lists and retrieves Back in Stock notifications with status, product, user,
email and date filters, standard pagination headers and _links. Registered
only while the customer_stock_notifications feature is enabled.
* fix: validate the email filter, embed item links and reject id 0 in the stock notifications REST controller
- Drop the custom sanitize_callback on the email arg so the default
rest_parse_request_arg validates its format (and still sanitizes it).
- Embed _links in collection items like prepare_response_for_collection().
- Treat GET /stock-notifications/0 as a 404 instead of an empty 200.
- Fix the deleted-product test: WC_Data::delete() resets the product id.
* fix: add PHPStan types to the stock notifications REST controller and bump @since to 11.4.0
* fix: read offset-less date filters in the site timezone in the stock notifications REST controller
* perf: load all products on a stock notifications page in one query
* feat: add dates_are_gmt to the stock notifications REST date filters
* fix: harden stock notifications REST filters and prepare hook
* fix: flag invalid stock notification prepare filter returns
diff --git a/plugins/woocommerce/changelog/add-stock-notifications-rest-controller b/plugins/woocommerce/changelog/add-stock-notifications-rest-controller
new file mode 100644
index 00000000000..85f409e93b8
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-stock-notifications-rest-controller
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add a read-only REST API endpoint, wc/v3/stock-notifications, to list and retrieve Back in Stock notifications.
diff --git a/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php b/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php
index 65a82b0148e..1a797e17427 100644
--- a/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php
+++ b/plugins/woocommerce/src/Internal/DataStores/StockNotifications/StockNotificationsDataStore.php
@@ -451,18 +451,20 @@ CREATE TABLE $meta_table_name (
$args = wp_parse_args(
$args,
array(
- 'status' => '',
- 'product_id' => array(),
- 'user_id' => 0,
- 'user_email' => '',
- 'customer' => array(),
- 'last_attempt_limit' => 0,
- 'start_date' => 0,
- 'end_date' => 0,
- 'limit' => -1,
- 'offset' => 0,
- 'order_by' => array( 'id' => 'ASC' ),
- 'return' => 'ids', // i.e. 'count', 'ids', 'objects'.
+ 'status' => '',
+ 'product_id' => array(),
+ 'user_id' => 0,
+ 'user_email' => '',
+ 'customer' => array(),
+ 'last_attempt_limit' => 0,
+ 'start_date' => 0,
+ 'end_date' => 0,
+ 'notified_start_date' => 0,
+ 'notified_end_date' => 0,
+ 'limit' => -1,
+ 'offset' => 0,
+ 'order_by' => array( 'id' => 'ASC' ),
+ 'return' => 'ids', // i.e. 'count', 'ids', 'objects'.
)
);
@@ -538,14 +540,17 @@ CREATE TABLE $meta_table_name (
$where_values[] = gmdate( 'Y-m-d H:i:s', $args['last_attempt_limit'] );
}
- if ( $args['start_date'] ) {
- $where[] = 'date_created_gmt >= %s';
- $where_values[] = esc_sql( $args['start_date'] );
- }
-
- if ( $args['end_date'] ) {
- $where[] = 'date_created_gmt < %s';
- $where_values[] = esc_sql( $args['end_date'] );
+ $date_ranges = array(
+ 'start_date' => 'date_created_gmt >= %s',
+ 'end_date' => 'date_created_gmt < %s',
+ 'notified_start_date' => 'date_notified_gmt >= %s',
+ 'notified_end_date' => 'date_notified_gmt < %s',
+ );
+ foreach ( $date_ranges as $arg => $clause ) {
+ if ( ! empty( $args[ $arg ] ) ) {
+ $where[] = $clause;
+ $where_values[] = esc_sql( $args[ $arg ] );
+ }
}
// ORDER BY clauses.
diff --git a/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php b/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
index 4b97e6de69e..9840c2a0422 100644
--- a/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
+++ b/plugins/woocommerce/src/Internal/StockNotifications/StockNotifications.php
@@ -120,6 +120,7 @@ class StockNotifications implements RegisterHooksInterface {
$container->get( PrivacyEraser::class );
$container->get( DataRetentionController::class );
$container->get( Telemetry::class );
+ $container->get( StockNotificationsRestController::class )->register();
$container->get( NotificationManagementService::class );
$container->get( MyAccountEndpoint::class );
diff --git a/plugins/woocommerce/src/Internal/StockNotifications/StockNotificationsRestController.php b/plugins/woocommerce/src/Internal/StockNotifications/StockNotificationsRestController.php
new file mode 100644
index 00000000000..92a1d117281
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/StockNotifications/StockNotificationsRestController.php
@@ -0,0 +1,536 @@
+<?php
+/**
+ * StockNotificationsRestController class file.
+ */
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\StockNotifications;
+
+use Automattic\WooCommerce\Enums\ProductType;
+use Automattic\WooCommerce\Internal\RestApiControllerBase;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationCancellationSource;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+use WP_Error;
+use WP_Http;
+use WP_REST_Request;
+use WP_REST_Response;
+use WP_REST_Server;
+
+/**
+ * Read-only REST API controller for Back in Stock notifications.
+ *
+ * Routes:
+ * - GET /wc/v3/stock-notifications
+ * - GET /wc/v3/stock-notifications/{id}
+ *
+ * Registered by StockNotifications::maybe_init_services(), so the routes only exist
+ * while the customer_stock_notifications feature is enabled.
+ */
+class StockNotificationsRestController extends RestApiControllerBase {
+
+ /**
+ * REST API base.
+ *
+ * @var string
+ */
+ protected string $rest_base = 'stock-notifications';
+
+ /**
+ * Map of `orderby` values to the columns the data store sorts on.
+ *
+ * @var array<string, string>
+ */
+ private const ORDERBY_COLUMNS = array(
+ 'id' => 'id',
+ 'date_created' => 'date_created_gmt',
+ 'date_modified' => 'date_modified_gmt',
+ 'date_notified' => 'date_notified_gmt',
+ );
+
+ /**
+ * Get the WooCommerce REST API namespace for the class.
+ *
+ * @return string
+ */
+ protected function get_rest_api_namespace(): string {
+ return 'stock_notifications';
+ }
+
+ /**
+ * Register the routes.
+ */
+ public function register_routes(): void {
+ register_rest_route(
+ $this->route_namespace,
+ '/' . $this->rest_base,
+ array(
+ array(
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => fn( $request ) => $this->run( $request, 'get_items' ),
+ 'permission_callback' => fn( $request ) => $this->check_permission( $request, 'manage_woocommerce' ),
+ 'args' => $this->get_collection_params(),
+ ),
+ 'schema' => array( $this, 'get_item_schema' ),
+ )
+ );
+
+ register_rest_route(
+ $this->route_namespace,
+ '/' . $this->rest_base . '/(?P<id>[\d]+)',
+ array(
+ array(
+ 'methods' => WP_REST_Server::READABLE,
+ 'callback' => fn( $request ) => $this->run( $request, 'get_item' ),
+ 'permission_callback' => fn( $request ) => $this->check_permission( $request, 'manage_woocommerce' ),
+ 'args' => array(
+ 'id' => array(
+ 'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
+ 'type' => 'integer',
+ ),
+ 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
+ ),
+ ),
+ 'schema' => array( $this, 'get_item_schema' ),
+ )
+ );
+ }
+
+ /**
+ * Get a collection of notifications.
+ *
+ * @param WP_REST_Request $request The request.
+ * @return WP_REST_Response
+ *
+ * @phpstan-param WP_REST_Request<array<string, mixed>> $request
+ */
+ protected function get_items( WP_REST_Request $request ): WP_REST_Response {
+ $per_page = (int) $request['per_page'];
+ $page = (int) $request['page'];
+ $offset = $request['offset'] ? (int) $request['offset'] : ( $page - 1 ) * $per_page;
+ $order = 'asc' === $request['order'] ? 'ASC' : 'DESC';
+ $orderby = self::ORDERBY_COLUMNS[ $request['orderby'] ] ?? 'date_created_gmt';
+ $order_by = array( $orderby => $order );
+ // A second key keeps pages stable when several rows share the same sort value.
+ $order_by['id'] = $order;
+
+ $dates_are_gmt = (bool) $request['dates_are_gmt'];
+
+ $query_args = array(
+ 'status' => (array) $request['status'],
+ 'product_id' => $this->expand_variable_products( (array) $request['product_id'] ),
+ 'user_id' => (int) $request['user_id'],
+ 'user_email' => (string) $request['email'],
+ 'start_date' => $this->to_gmt_mysql_date( $request['after'], $dates_are_gmt ),
+ 'end_date' => $this->to_gmt_mysql_date( $request['before'], $dates_are_gmt ),
+ 'notified_start_date' => $this->to_gmt_mysql_date( $request['notified_after'], $dates_are_gmt ),
+ 'notified_end_date' => $this->to_gmt_mysql_date( $request['notified_before'], $dates_are_gmt ),
+ );
+
+ $total = NotificationQuery::count_notifications( $query_args );
+ $notifications = $total > 0 ? NotificationQuery::get_notifications(
+ array_merge(
+ $query_args,
+ array(
+ 'limit' => $per_page,
+ 'offset' => $offset,
+ 'order_by' => $order_by,
+ 'return' => 'objects',
+ )
+ )
+ ) : array();
+
+ // Load every product on the page in one query instead of one per item, then the parents of any variations.
+ $product_ids = array_unique( array_map( fn( $notification ) => $notification->get_product_id(), $notifications ) );
+ _prime_post_caches( $product_ids );
+ _prime_post_caches( array_unique( array_filter( array_map( 'wp_get_post_parent_id', $product_ids ) ) ) );
+
+ $items = array();
+ foreach ( $notifications as $notification ) {
+ // Embed the item links in the data, as WP_REST_Controller::prepare_response_for_collection() does.
+ $items[] = rest_get_server()->response_to_data( $this->prepare_item_for_response( $notification, $request ), false );
+ }
+
+ $max_pages = (int) ceil( $total / $per_page );
+ $response = new WP_REST_Response( $items );
+ $response->header( 'X-WP-Total', (string) $total );
+ $response->header( 'X-WP-TotalPages', (string) $max_pages );
+
+ $base = add_query_arg( urlencode_deep( $request->get_query_params() ), rest_url( $this->route_namespace . '/' . $this->rest_base ) );
+ if ( $page > 1 ) {
+ $response->link_header( 'prev', add_query_arg( 'page', min( $page - 1, $max_pages ), $base ) );
+ }
+ if ( $page < $max_pages ) {
+ $response->link_header( 'next', add_query_arg( 'page', $page + 1, $base ) );
+ }
+
+ return $response;
+ }
+
+ /**
+ * Get a single notification.
+ *
+ * @param WP_REST_Request $request The request.
+ * @return WP_REST_Response|WP_Error
+ *
+ * @phpstan-param WP_REST_Request<array<string, mixed>> $request
+ */
+ protected function get_item( WP_REST_Request $request ) {
+ $id = (int) $request['id'];
+
+ try {
+ // The data store throws when the row does not exist; an id of 0 is never read at all.
+ $notification = $id > 0 ? new Notification( $id ) : null;
+ } catch ( \Exception $e ) {
+ $notification = null;
+ }
+
+ if ( ! $notification ) {
+ return new WP_Error( 'woocommerce_rest_stock_notification_invalid_id', __( 'Invalid ID.', 'woocommerce' ), array( 'status' => WP_Http::NOT_FOUND ) );
+ }
+
+ return $this->prepare_item_for_response( $notification, $request );
+ }
+
+ /**
+ * Prepare a notification for the response.
+ *
+ * @param Notification $notification The notification.
+ * @param WP_REST_Request $request The request.
+ * @return WP_REST_Response
+ *
+ * @phpstan-param WP_REST_Request<array<string, mixed>> $request
+ */
+ protected function prepare_item_for_response( Notification $notification, WP_REST_Request $request ): WP_REST_Response {
+ $product = $notification->get_product();
+ $posted_attributes = $notification->get_meta( 'posted_attributes' );
+ $posted_attributes = is_array( $posted_attributes ) ? wc_clean( $posted_attributes ) : array();
+ $is_variation = $product && $product->is_type( 'variation' );
+
+ $data = array(
+ 'id' => $notification->get_id(),
+ 'status' => $notification->get_status(),
+ 'product_id' => $notification->get_product_id(),
+ 'parent_id' => $product ? ( $is_variation ? $product->get_parent_id() : 0 ) : null,
+ 'variation_id' => $product ? ( $is_variation ? $product->get_id() : 0 ) : null,
+ 'sku' => $product ? $product->get_sku() : null,
+ 'posted_attributes' => (object) $posted_attributes,
+ 'user_id' => $notification->get_user_id(),
+ 'user_email' => sanitize_email( $notification->get_user_email() ),
+ 'cancellation_source' => $notification->get_cancellation_source(),
+ 'product_permalink' => $product ? $notification->get_product_permalink() : null,
+ );
+
+ foreach ( array( 'date_created', 'date_modified', 'date_confirmed', 'date_notified', 'date_last_attempt', 'date_cancelled' ) as $date_key ) {
+ $date = $notification->{"get_$date_key"}();
+ $data[ $date_key ] = $date ? wc_rest_prepare_date_response( $date, false ) : null;
+ $data[ $date_key . '_gmt' ] = $date ? wc_rest_prepare_date_response( $date ) : null;
+ }
+
+ $response = new WP_REST_Response( $data );
+ $response->add_links( $this->prepare_links( $notification, $product ) );
+
+ /**
+ * Filter the response for a single stock notification.
+ *
+ * @since 11.5.0
+ *
+ * @param WP_REST_Response $response The response.
+ * @param Notification $notification The notification.
+ * @param WP_REST_Request $request The request.
+ */
+ $filtered = apply_filters( 'woocommerce_rest_prepare_stock_notification', $response, $notification, $request );
+ if ( ! $filtered instanceof WP_REST_Response ) {
+ _doing_it_wrong( 'woocommerce_rest_prepare_stock_notification', esc_html( 'The filter must return a WP_REST_Response.' ), '11.5.0' );
+ return $response;
+ }
+
+ return $filtered;
+ }
+
+ /**
+ * Prepare the links for a notification.
+ *
+ * @param Notification $notification The notification.
+ * @param \WC_Product|false $product The notification's product, or false when it no longer exists.
+ * @return array
+ */
+ private function prepare_links( Notification $notification, $product ): array {
+ $links = array(
+ 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->route_namespace, $this->rest_base, $notification->get_id() ) ) ),
+ 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->route_namespace, $this->rest_base ) ) ),
+ );
+
+ if ( $product ) {
+ $product_route = $product->is_type( 'variation' )
+ ? sprintf( 'products/%d/variations/%d', $product->get_parent_id(), $product->get_id() )
+ : sprintf( 'products/%d', $product->get_id() );
+ $links['up'] = array( 'href' => rest_url( $this->route_namespace . '/' . $product_route ) );
+ }
+
+ return $links;
+ }
+
+ /**
+ * Add the variations of any variable product in the list, since sign-ups are stored against variations.
+ *
+ * @param array $product_ids Product or variation IDs.
+ * @return int[]
+ */
+ private function expand_variable_products( array $product_ids ): array {
+ $expanded = array_map( 'intval', $product_ids );
+ foreach ( $product_ids as $product_id ) {
+ $product = wc_get_product( $product_id );
+ if ( $product && $product->is_type( ProductType::VARIABLE ) ) {
+ $expanded = array_merge( $expanded, $product->get_children() );
+ }
+ }
+
+ return array_values( array_unique( $expanded ) );
+ }
+
+ /**
+ * Convert a REST date-time argument to a GMT MySQL datetime for the data store.
+ *
+ * Like the dates in the response, a value without a timezone offset is in the site's timezone, unless `$is_gmt` is true.
+ *
+ * @param mixed $value The argument value.
+ * @param bool $is_gmt Whether a value without a timezone offset is in GMT.
+ * @return string Empty when the argument is absent.
+ */
+ private function to_gmt_mysql_date( $value, bool $is_gmt ): string {
+ if ( empty( $value ) ) {
+ return '';
+ }
+
+ $date = rest_get_date_with_gmt( (string) $value, $is_gmt );
+
+ return $date ? $date[1] : '';
+ }
+
+ /**
+ * Get the `context` argument definition.
+ *
+ * @param array $args Overrides.
+ * @return array
+ */
+ private function get_context_param( array $args = array() ): array {
+ return array_merge(
+ array(
+ 'description' => __( 'Scope under which the request is made; determines fields present in response.', 'woocommerce' ),
+ 'type' => 'string',
+ 'enum' => array( 'view', 'edit' ),
+ 'default' => 'view',
+ ),
+ $args
+ );
+ }
+
+ /**
+ * Get the query parameters for the collection.
+ *
+ * @return array
+ */
+ public function get_collection_params(): array {
+ return array(
+ 'context' => $this->get_context_param(),
+ 'page' => array(
+ 'description' => __( 'Current page of the collection.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'default' => 1,
+ 'minimum' => 1,
+ ),
+ 'per_page' => array(
+ 'description' => __( 'Maximum number of items to be returned in result set.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'default' => 10,
+ 'minimum' => 1,
+ 'maximum' => 100,
+ ),
+ 'offset' => array(
+ 'description' => __( 'Offset the result set by a specific number of items.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'minimum' => 0,
+ ),
+ 'order' => array(
+ 'description' => __( 'Order sort attribute ascending or descending.', 'woocommerce' ),
+ 'type' => 'string',
+ 'default' => 'desc',
+ 'enum' => array( 'asc', 'desc' ),
+ ),
+ 'orderby' => array(
+ 'description' => __( 'Sort collection by attribute.', 'woocommerce' ),
+ 'type' => 'string',
+ 'default' => 'date_created',
+ 'enum' => array_keys( self::ORDERBY_COLUMNS ),
+ ),
+ 'status' => array(
+ 'description' => __( 'Limit result set to notifications with one or more statuses.', 'woocommerce' ),
+ 'type' => 'array',
+ 'items' => array(
+ 'type' => 'string',
+ 'enum' => NotificationStatus::get_valid_statuses(),
+ ),
+ 'default' => array(),
+ ),
+ 'product_id' => array(
+ 'description' => __( 'Limit result set to notifications for one or more product or variation IDs. A variable product ID also matches its variations.', 'woocommerce' ),
+ 'type' => 'array',
+ 'items' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'default' => array(),
+ ),
+ 'user_id' => array(
+ 'description' => __( 'Limit result set to notifications of a registered user.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'email' => array(
+ 'description' => __( 'Limit result set to notifications for an email address (exact match).', 'woocommerce' ),
+ 'type' => 'string',
+ 'format' => 'email',
+ ),
+ 'after' => array(
+ 'description' => __( 'Limit response to notifications created on or after a given ISO8601 compliant date. Without a timezone offset, the date is in the site\'s timezone, unless dates_are_gmt is true.', 'woocommerce' ),
+ 'type' => 'string',
+ 'format' => 'date-time',
+ ),
+ 'before' => array(
+ 'description' => __( 'Limit response to notifications created before a given ISO8601 compliant date. Without a timezone offset, the date is in the site\'s timezone, unless dates_are_gmt is true.', 'woocommerce' ),
+ 'type' => 'string',
+ 'format' => 'date-time',
+ ),
+ 'notified_after' => array(
+ 'description' => __( 'Limit response to notifications sent on or after a given ISO8601 compliant date. Without a timezone offset, the date is in the site\'s timezone, unless dates_are_gmt is true.', 'woocommerce' ),
+ 'type' => 'string',
+ 'format' => 'date-time',
+ ),
+ 'notified_before' => array(
+ 'description' => __( 'Limit response to notifications sent before a given ISO8601 compliant date. Without a timezone offset, the date is in the site\'s timezone, unless dates_are_gmt is true.', 'woocommerce' ),
+ 'type' => 'string',
+ 'format' => 'date-time',
+ ),
+ 'dates_are_gmt' => array(
+ 'description' => __( 'Whether date filters without a timezone offset are in GMT instead of the site\'s timezone.', 'woocommerce' ),
+ 'type' => 'boolean',
+ 'default' => false,
+ ),
+ );
+ }
+
+ /**
+ * Get the item schema.
+ *
+ * @return array
+ */
+ public function get_item_schema(): array {
+ $date_props = array();
+ foreach ( array(
+ 'date_created' => __( 'The date the notification was created', 'woocommerce' ),
+ 'date_modified' => __( 'The date the notification was last modified', 'woocommerce' ),
+ 'date_confirmed' => __( 'The date the notification was confirmed by the customer', 'woocommerce' ),
+ 'date_notified' => __( 'The date the back in stock email was sent', 'woocommerce' ),
+ 'date_last_attempt' => __( 'The date the back in stock email was last attempted', 'woocommerce' ),
+ 'date_cancelled' => __( 'The date the notification was cancelled', 'woocommerce' ),
+ ) as $key => $description ) {
+ $date_props[ $key ] = array(
+ /* translators: %s: what the date records. */
+ 'description' => sprintf( __( "%s, in the site's timezone.", 'woocommerce' ), $description ),
+ 'type' => array( 'string', 'null' ),
+ 'format' => 'date-time',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ );
+ $date_props[ $key . '_gmt' ] = array(
+ /* translators: %s: what the date records. */
+ 'description' => sprintf( __( '%s, as GMT.', 'woocommerce' ), $description ),
+ 'type' => array( 'string', 'null' ),
+ 'format' => 'date-time',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ );
+ }
+
+ $schema = $this->get_base_schema();
+ $schema['title'] = 'stock_notification';
+ $schema['properties'] = array_merge(
+ array(
+ 'id' => array(
+ 'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'status' => array(
+ 'description' => __( 'Notification status.', 'woocommerce' ),
+ 'type' => 'string',
+ 'enum' => NotificationStatus::get_valid_statuses(),
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'product_id' => array(
+ 'description' => __( 'ID of the product or variation the customer signed up for.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'parent_id' => array(
+ 'description' => __( 'Parent product ID when the product is a variation, otherwise 0. Null if the product no longer exists.', 'woocommerce' ),
+ 'type' => array( 'integer', 'null' ),
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'variation_id' => array(
+ 'description' => __( 'Variation ID when the product is a variation, otherwise 0. Null if the product no longer exists.', 'woocommerce' ),
+ 'type' => array( 'integer', 'null' ),
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'sku' => array(
+ 'description' => __( 'Product SKU. Null if the product no longer exists.', 'woocommerce' ),
+ 'type' => array( 'string', 'null' ),
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'posted_attributes' => array(
+ 'description' => __( 'Variation attributes the customer selected when signing up, keyed by attribute name (e.g. attribute_pa_color).', 'woocommerce' ),
+ 'type' => 'object',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'user_id' => array(
+ 'description' => __( 'User ID, or 0 for a guest.', 'woocommerce' ),
+ 'type' => 'integer',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'user_email' => array(
+ 'description' => __( 'Email address the notification is sent to.', 'woocommerce' ),
+ 'type' => 'string',
+ 'format' => 'email',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'cancellation_source' => array(
+ 'description' => __( 'Who or what cancelled the notification. Null unless cancelled.', 'woocommerce' ),
+ 'type' => array( 'string', 'null' ),
+ 'enum' => array_merge( NotificationCancellationSource::get_valid_cancellation_sources(), array( null ) ),
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ 'product_permalink' => array(
+ 'description' => __( 'Product URL, with the posted attributes preselected for variations. Null if the product no longer exists.', 'woocommerce' ),
+ 'type' => array( 'string', 'null' ),
+ 'format' => 'uri',
+ 'context' => array( 'view', 'edit' ),
+ 'readonly' => true,
+ ),
+ ),
+ $date_props
+ );
+
+ return $schema;
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsRestControllerTests.php b/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsRestControllerTests.php
new file mode 100644
index 00000000000..e834c2b3715
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/StockNotifications/StockNotificationsRestControllerTests.php
@@ -0,0 +1,475 @@
+<?php
+
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\StockNotifications;
+
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationCancellationSource;
+use Automattic\WooCommerce\Internal\StockNotifications\Enums\NotificationStatus;
+use Automattic\WooCommerce\Internal\StockNotifications\Notification;
+use Automattic\WooCommerce\Internal\StockNotifications\StockNotificationsRestController;
+use WC_REST_Unit_Test_Case;
+use WP_REST_Request;
+
+/**
+ * Tests for the wc/v3/stock-notifications REST controller.
+ */
+class StockNotificationsRestControllerTests extends WC_REST_Unit_Test_Case {
+
+ use StockNotificationsFeatureTrait;
+
+ private const ROUTE = '/wc/v3/stock-notifications';
+
+ /**
+ * The test registers its own routes, so it needs a fresh server each time.
+ *
+ * @var bool
+ */
+ protected static $reuse_rest_server = false;
+
+ /**
+ * Set up the test.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ $this->enable_stock_notifications_feature();
+ ( new StockNotificationsRestController() )->register_routes();
+ wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) );
+ }
+
+ /**
+ * Tear down the test.
+ */
+ public function tearDown(): void {
+ global $wpdb;
+ $wpdb->query( "DELETE FROM {$wpdb->prefix}wc_stock_notificationmeta" );
+ $wpdb->query( "DELETE FROM {$wpdb->prefix}wc_stock_notifications" );
+ $this->restore_stock_notifications_feature_option();
+ parent::tearDown();
+ }
+
+ /**
+ * Create and save a notification.
+ *
+ * @param array $props Props to set, plus optional `posted_attributes` meta.
+ * @return Notification
+ */
+ private function create_notification( array $props = array() ): Notification {
+ $posted_attributes = $props['posted_attributes'] ?? null;
+ unset( $props['posted_attributes'] );
+
+ $props['product_id'] ??= \WC_Helper_Product::create_simple_product()->get_id();
+
+ $notification = new Notification();
+ $notification->set_props(
+ array_merge(
+ array(
+ 'user_email' => 'shopper@example.com',
+ 'status' => NotificationStatus::ACTIVE,
+ ),
+ $props
+ )
+ );
+ if ( null !== $posted_attributes ) {
+ $notification->add_meta_data( 'posted_attributes', $posted_attributes );
+ }
+ $notification->save();
+
+ return $notification;
+ }
+
+ /**
+ * Dispatch a GET request to the collection route.
+ *
+ * @param array $params Query params.
+ * @return \WP_REST_Response
+ */
+ private function get_collection( array $params = array() ) {
+ $request = new WP_REST_Request( 'GET', self::ROUTE );
+ $request->set_query_params( $params );
+ return $this->server->dispatch( $request );
+ }
+
+ /**
+ * @testdox The single item route returns every documented field with the expected values.
+ */
+ public function test_get_item(): void {
+ $product = \WC_Helper_Product::create_simple_product( true, array( 'sku' => 'BIS-SKU' ) );
+ $notification = $this->create_notification(
+ array(
+ 'product_id' => $product->get_id(),
+ 'user_id' => get_current_user_id(),
+ 'status' => NotificationStatus::CANCELLED,
+ 'cancellation_source' => NotificationCancellationSource::ADMIN,
+ 'date_cancelled' => '2026-02-03T04:05:06Z',
+ )
+ );
+
+ $response = $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/' . $notification->get_id() ) );
+ $data = $response->get_data();
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertSame( $notification->get_id(), $data['id'] );
+ $this->assertSame( 'cancelled', $data['status'] );
+ $this->assertSame( $product->get_id(), $data['product_id'] );
+ $this->assertSame( 0, $data['parent_id'] );
+ $this->assertSame( 0, $data['variation_id'] );
+ $this->assertSame( 'BIS-SKU', $data['sku'] );
+ $this->assertSame( get_current_user_id(), $data['user_id'] );
+ $this->assertSame( 'shopper@example.com', $data['user_email'] );
+ $this->assertSame( 'admin', $data['cancellation_source'] );
+ $this->assertSame( $product->get_permalink(), $data['product_permalink'] );
+ $this->assertEquals( new \stdClass(), $data['posted_attributes'] );
+ $this->assertSame( '2026-02-03T04:05:06', $data['date_cancelled_gmt'] );
+ $this->assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/', $data['date_created'] );
+ $this->assertNotNull( $data['date_created_gmt'] );
+ foreach ( array( 'date_confirmed', 'date_notified', 'date_last_attempt' ) as $unset_date ) {
+ $this->assertNull( $data[ $unset_date ] );
+ $this->assertNull( $data[ $unset_date . '_gmt' ] );
+ }
+
+ $links = $response->get_links();
+ $this->assertStringEndsWith( self::ROUTE . '/' . $notification->get_id(), $links['self'][0]['href'] );
+ $this->assertStringEndsWith( self::ROUTE, $links['collection'][0]['href'] );
+ $this->assertStringEndsWith( '/wc/v3/products/' . $product->get_id(), $links['up'][0]['href'] );
+ }
+
+ /**
+ * @testdox A variation sign-up resolves the parent product, the variation and the posted attributes.
+ */
+ public function test_get_item_for_variation(): void {
+ $variable = \WC_Helper_Product::create_variation_product();
+ $variation = wc_get_product( $variable->get_children()[0] );
+ $attributes = array( 'attribute_pa_size' => 'small' );
+ $notification = $this->create_notification(
+ array(
+ 'product_id' => $variation->get_id(),
+ 'posted_attributes' => $attributes,
+ )
+ );
+
+ $response = $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/' . $notification->get_id() ) );
+ $data = $response->get_data();
+
+ $this->assertSame( $variation->get_id(), $data['product_id'] );
+ $this->assertSame( $variable->get_id(), $data['parent_id'] );
+ $this->assertSame( $variation->get_id(), $data['variation_id'] );
+ $this->assertSame( $attributes, (array) $data['posted_attributes'] );
+ $this->assertStringEndsWith( sprintf( '/wc/v3/products/%d/variations/%d', $variable->get_id(), $variation->get_id() ), $response->get_links()['up'][0]['href'] );
+ }
+
+ /**
+ * @testdox A notification whose product was deleted returns null product fields instead of failing.
+ */
+ public function test_get_item_with_deleted_product(): void {
+ $product = \WC_Helper_Product::create_simple_product();
+ $product_id = $product->get_id();
+ $notification = $this->create_notification( array( 'product_id' => $product_id ) );
+ $product->delete( true );
+
+ $response = $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/' . $notification->get_id() ) );
+ $data = $response->get_data();
+
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertSame( $product_id, $data['product_id'] );
+ $this->assertNull( $data['parent_id'] );
+ $this->assertNull( $data['variation_id'] );
+ $this->assertNull( $data['sku'] );
+ $this->assertNull( $data['product_permalink'] );
+ $this->assertArrayNotHasKey( 'up', $response->get_links() );
+ }
+
+ /**
+ * @testdox An unknown id yields a 404 with the invalid id error code.
+ */
+ public function test_get_item_unknown_id(): void {
+ $response = $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/999999' ) );
+
+ $this->assertSame( 404, $response->get_status() );
+ $this->assertSame( 'woocommerce_rest_stock_notification_invalid_id', $response->get_data()['code'] );
+ $this->assertSame( 404, $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/0' ) )->get_status() );
+ }
+
+ /**
+ * @testdox The prepare filter can extend the payload.
+ */
+ public function test_prepare_filter(): void {
+ $notification = $this->create_notification();
+ $filter = function ( $response, $filtered_notification, $request ) use ( $notification ) {
+ $this->assertSame( $notification->get_id(), $filtered_notification->get_id() );
+ $this->assertInstanceOf( WP_REST_Request::class, $request );
+ $data = $response->get_data();
+ $data['extra'] = 'yes';
+ $response->set_data( $data );
+ return $response;
+ };
+ add_filter( 'woocommerce_rest_prepare_stock_notification', $filter, 10, 3 );
+
+ $data = $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/' . $notification->get_id() ) )->get_data();
+ remove_filter( 'woocommerce_rest_prepare_stock_notification', $filter );
+
+ $this->assertSame( 'yes', $data['extra'] );
+ }
+
+ /**
+ * @testdox A prepare filter that returns something other than a response is ignored and flagged as incorrect usage.
+ */
+ public function test_prepare_filter_invalid_return(): void {
+ $this->setExpectedIncorrectUsage( 'woocommerce_rest_prepare_stock_notification' );
+ $notification = $this->create_notification();
+ $filter = fn() => new \WP_Error( 'broken', 'Broken.' );
+ add_filter( 'woocommerce_rest_prepare_stock_notification', $filter );
+
+ $item = $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/' . $notification->get_id() ) );
+ $collection = $this->get_collection();
+ remove_filter( 'woocommerce_rest_prepare_stock_notification', $filter );
+
+ $this->assertSame( 200, $item->get_status() );
+ $this->assertSame( $notification->get_id(), $item->get_data()['id'] );
+ $this->assertSame( array( $notification->get_id() ), array_column( $collection->get_data(), 'id' ) );
+ }
+
+ /**
+ * @testdox Collection requests paginate with the standard total headers, newest first.
+ */
+ public function test_get_items_pagination(): void {
+ $ids = array();
+ for ( $i = 0; $i < 3; $i++ ) {
+ $ids[] = $this->create_notification( array( 'date_created' => 1000 + $i ) )->get_id();
+ }
+
+ $response = $this->get_collection( array( 'per_page' => 2 ) );
+ $this->assertSame( 200, $response->get_status() );
+ $this->assertArrayHasKey( '_links', $response->get_data()[0] );
+ $this->assertSame( '3', $response->get_headers()['X-WP-Total'] );
+ $this->assertSame( '2', $response->get_headers()['X-WP-TotalPages'] );
+ $this->assertSame( array( $ids[2], $ids[1] ), array_column( $response->get_data(), 'id' ) );
+ $this->assertStringContainsString( 'rel="next"', $response->get_headers()['Link'] );
+
+ $response = $this->get_collection(
+ array(
+ 'per_page' => 2,
+ 'page' => 2,
+ )
+ );
+ $this->assertSame( array( $ids[0] ), array_column( $response->get_data(), 'id' ) );
+ $this->assertStringContainsString( 'rel="prev"', $response->get_headers()['Link'] );
+
+ $response = $this->get_collection(
+ array(
+ 'offset' => 1,
+ 'order' => 'asc',
+ 'orderby' => 'id',
+ )
+ );
+ $this->assertSame( array( $ids[1], $ids[2] ), array_column( $response->get_data(), 'id' ) );
+ $this->assertSame( '3', $response->get_headers()['X-WP-Total'] );
+ }
+
+ /**
+ * @testdox Collection requests cap per_page at 100 and reject unknown statuses.
+ */
+ public function test_get_items_invalid_params(): void {
+ $this->assertSame( 'rest_invalid_param', $this->get_collection( array( 'per_page' => 101 ) )->get_data()['code'] );
+ $this->assertSame( 'rest_invalid_param', $this->get_collection( array( 'status' => 'bogus' ) )->get_data()['code'] );
+ $this->assertSame( 'rest_invalid_param', $this->get_collection( array( 'after' => 'not-a-date' ) )->get_data()['code'] );
+ $this->assertSame( 'rest_invalid_param', $this->get_collection( array( 'email' => 'not-an-email' ) )->get_data()['code'] );
+ }
+
+ /**
+ * @testdox Each collection filter narrows the result set.
+ */
+ public function test_get_items_filters(): void {
+ $product_a = \WC_Helper_Product::create_simple_product();
+ $product_b = \WC_Helper_Product::create_simple_product();
+ $user_id = $this->factory->user->create();
+
+ $active = $this->create_notification(
+ array(
+ 'product_id' => $product_a->get_id(),
+ 'user_id' => $user_id,
+ 'date_created' => '2026-01-10T00:00:00Z',
+ )
+ );
+ $sent = $this->create_notification(
+ array(
+ 'product_id' => $product_b->get_id(),
+ 'status' => NotificationStatus::SENT,
+ 'user_email' => 'Other@Example.com',
+ 'date_created' => '2026-01-20T00:00:00Z',
+ 'date_notified' => '2026-01-25T00:00:00Z',
+ )
+ );
+ $cancelled = $this->create_notification(
+ array(
+ 'product_id' => $product_b->get_id(),
+ 'status' => NotificationStatus::CANCELLED,
+ 'date_created' => '2026-01-30T00:00:00Z',
+ )
+ );
+
+ $ids = fn( array $params ) => array_column( $this->get_collection( $params )->get_data(), 'id' );
+
+ $this->assertSame( array( $cancelled->get_id(), $sent->get_id(), $active->get_id() ), $ids( array() ) );
+ $this->assertSame( array( $sent->get_id() ), $ids( array( 'status' => 'sent' ) ) );
+ $this->assertSame( array( $cancelled->get_id(), $sent->get_id() ), $ids( array( 'status' => 'sent,cancelled' ) ) );
+ $this->assertSame( array( $active->get_id() ), $ids( array( 'product_id' => $product_a->get_id() ) ) );
+ $this->assertSame( array( $cancelled->get_id(), $sent->get_id() ), $ids( array( 'product_id' => $product_b->get_id() ) ) );
+ $this->assertSame( array( $active->get_id() ), $ids( array( 'user_id' => $user_id ) ) );
+ $this->assertSame( array( $sent->get_id() ), $ids( array( 'email' => 'other@example.com' ) ) );
+ $this->assertSame( array( $cancelled->get_id(), $sent->get_id() ), $ids( array( 'after' => '2026-01-15T00:00:00' ) ) );
+ $this->assertSame( array( $active->get_id() ), $ids( array( 'before' => '2026-01-15T00:00:00' ) ) );
+ $this->assertSame( array( $sent->get_id() ), $ids( array( 'notified_after' => '2026-01-24T00:00:00' ) ) );
+ $this->assertSame( array(), $ids( array( 'notified_before' => '2026-01-24T00:00:00' ) ) );
+ }
+
+ /**
+ * @testdox Filtering by a variable product ID also matches sign-ups for its variations.
+ */
+ public function test_get_items_variable_product_filter(): void {
+ $variable = \WC_Helper_Product::create_variation_product();
+ $variation = $this->create_notification( array( 'product_id' => $variable->get_children()[0] ) );
+ $this->create_notification();
+
+ $ids = array_column( $this->get_collection( array( 'product_id' => $variable->get_id() ) )->get_data(), 'id' );
+
+ $this->assertSame( array( $variation->get_id() ), $ids );
+ }
+
+ /**
+ * @testdox The orderby parameter sorts by the requested column.
+ * @dataProvider provide_orderby_columns
+ *
+ * @param string $orderby The orderby value, which is also the date prop it sorts on.
+ */
+ public function test_get_items_orderby( string $orderby ): void {
+ $later = $this->create_notification( array( $orderby => '2026-01-20T00:00:00Z' ) );
+ $earlier = $this->create_notification( array( $orderby => '2026-01-10T00:00:00Z' ) );
+
+ $ids = array_column(
+ $this->get_collection(
+ array(
+ 'orderby' => $orderby,
+ 'order' => 'asc',
+ )
+ )->get_data(),
+ 'id'
+ );
+
+ $this->assertSame( array( $earlier->get_id(), $later->get_id() ), $ids );
+ }
+
+ /**
+ * Data provider for test_get_items_orderby.
+ *
+ * @return array
+ */
+ public function provide_orderby_columns(): array {
+ return array(
+ 'date_created' => array( 'date_created' ),
+ 'date_modified' => array( 'date_modified' ),
+ 'date_notified' => array( 'date_notified' ),
+ );
+ }
+
+ /**
+ * @testdox Dates without an offset are in the site's timezone, in both the response and the date filters, unless dates_are_gmt is set.
+ */
+ public function test_dates_use_site_timezone(): void {
+ update_option( 'timezone_string', 'Europe/Athens' );
+ $notification = $this->create_notification( array( 'date_created' => '2026-01-10T10:00:00Z' ) );
+
+ $item = $this->get_collection()->get_data()[0];
+ $this->assertSame( '2026-01-10T12:00:00', $item['date_created'] );
+ $this->assertSame( '2026-01-10T10:00:00', $item['date_created_gmt'] );
+
+ $ids = fn( array $params ) => array_column( $this->get_collection( $params )->get_data(), 'id' );
+ $this->assertSame( array( $notification->get_id() ), $ids( array( 'after' => '2026-01-10T12:00:00' ) ) );
+ $this->assertSame( array(), $ids( array( 'after' => '2026-01-10T12:00:01' ) ) );
+ $this->assertSame( array( $notification->get_id() ), $ids( array( 'after' => '2026-01-10T10:00:00Z' ) ) );
+ $this->assertSame( array(), $ids( array( 'after' => '2026-01-10T12:00:01+02:00' ) ) );
+ $gmt = fn( string $after ) => array(
+ 'after' => $after,
+ 'dates_are_gmt' => true,
+ );
+ $this->assertSame( array( $notification->get_id() ), $ids( $gmt( '2026-01-10T10:00:00' ) ) );
+ $this->assertSame( array(), $ids( $gmt( '2026-01-10T10:00:01' ) ) );
+
+ delete_option( 'timezone_string' );
+ }
+
+ /**
+ * @testdox The _fields parameter limits the returned fields.
+ */
+ public function test_get_items_fields(): void {
+ $this->create_notification();
+
+ $data = $this->get_collection( array( '_fields' => 'id,status' ) )->get_data();
+
+ $this->assertSame( array( 'id', 'status' ), array_keys( $data[0] ) );
+ }
+
+ /**
+ * @testdox Users without manage_woocommerce are rejected on both routes.
+ */
+ public function test_permissions(): void {
+ $notification = $this->create_notification();
+
+ wp_set_current_user( 0 );
+ $response = $this->get_collection();
+ $this->assertSame( 401, $response->get_status() );
+ $this->assertSame( 'woocommerce_rest_cannot_view', $response->get_data()['code'] );
+
+ wp_set_current_user( $this->factory->user->create( array( 'role' => 'customer' ) ) );
+ $this->assertSame( 403, $this->get_collection()->get_status() );
+ $this->assertSame( 403, $this->server->dispatch( new WP_REST_Request( 'GET', self::ROUTE . '/' . $notification->get_id() ) )->get_status() );
+
+ wp_set_current_user( $this->factory->user->create( array( 'role' => 'shop_manager' ) ) );
+ $this->assertSame( 200, $this->get_collection()->get_status() );
+ }
+
+ /**
+ * @testdox OPTIONS exposes a read-only schema with every documented field.
+ */
+ public function test_schema(): void {
+ $response = $this->server->dispatch( new WP_REST_Request( 'OPTIONS', self::ROUTE ) );
+ $schema = $response->get_data()['schema'];
+
+ $this->assertSame( 'stock_notification', $schema['title'] );
+ $expected = array(
+ 'id',
+ 'status',
+ 'product_id',
+ 'parent_id',
+ 'variation_id',
+ 'sku',
+ 'posted_attributes',
+ 'user_id',
+ 'user_email',
+ 'cancellation_source',
+ 'product_permalink',
+ 'date_created',
+ 'date_created_gmt',
+ 'date_modified',
+ 'date_modified_gmt',
+ 'date_confirmed',
+ 'date_confirmed_gmt',
+ 'date_notified',
+ 'date_notified_gmt',
+ 'date_last_attempt',
+ 'date_last_attempt_gmt',
+ 'date_cancelled',
+ 'date_cancelled_gmt',
+ );
+ $this->assertSame( $expected, array_keys( $schema['properties'] ) );
+ foreach ( $schema['properties'] as $property ) {
+ $this->assertTrue( $property['readonly'] );
+ $this->assertSame( array( 'view', 'edit' ), $property['context'] );
+ }
+ $this->assertSame( NotificationStatus::get_valid_statuses(), $schema['properties']['status']['enum'] );
+
+ $args = $response->get_data()['endpoints'][0]['args'];
+ $this->assertSame( 100, $args['per_page']['maximum'] );
+ $this->assertSame( NotificationStatus::get_valid_statuses(), $args['status']['items']['enum'] );
+ }
+}