Commit 60a75a4583a for woocommerce
commit 60a75a4583a44e6c2c80ea1c5df93d5620915771
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date: Tue Nov 17 14:48:06 2026 +0100
Agent readiness: let the rules file set Required store checks, and rank Fix first on sales it can trust (#70996)
* Agent readiness: rank checks by sales, let the rules file set Required store checks
ProductSales reads each product's and variation's net sales over the
last 90 days from the Analytics lookup tables. The scan adds up the
sales of each check's failing products, or only the failing variations
of a variable product, and stores the share. Shares are left out with
fewer than 20 orders, or while Analytics holds under 90% of the store's
orders.
The rules file's store_checks marks a store check required or off
without a release. The UCP catalog search check asks once more before it
fails, and keeps the status and content type of a failed answer.
* Agent readiness: keep each POST answer per body, not per URL
post_json() cached its answer by URL alone, so a second POST of a different
body to the same URL in one scan got the first body's answer. Both callers
send an empty body today, so no result changes. post_json_again() now
clears only the answer for its own body.
Fixes WOOAIRR-787.
* Agent readiness: keep fix links on the Agentic commerce tab
This branch has no AI shopping section yet. Point UCP and policy fixes
at the current tab so they work if this PR merges to trunk before #70590.
* Agent readiness: address CodeRabbit findings on sales shares and settings
Clear sales_share when example membership changes, count Analytics orders
before revenue, exclude WCPay test orders from the import denominator, group
settings by shows_required(), and read nested AggregateOffer policies.
* Keep guest checkout Optional in agent readiness.
With guest checkout off, UCP still serves the catalog and carts, so it no longer blocks the AI shopping switch. Also turn on a payment method in the ready-store settings tests, since that step is Required.
* Count WCPay test orders apart, so the sales import check works without HPOS.
The posts order store doesn't support meta_query: it ignored the exclusion and raised a doing-it-wrong notice on every scan. Count all orders and the test-mode ones, and subtract.
---------
diff --git a/plugins/woocommerce/changelog/add-agent-readiness-fix-first-rules b/plugins/woocommerce/changelog/add-agent-readiness-fix-first-rules
new file mode 100644
index 00000000000..7e059753453
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-agent-readiness-fix-first-rules
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Agent readiness (unreleased): Fix first ranks by sales, the rules file sets Required store checks, and the UCP catalog search check asks twice before it fails.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
index 4a4ab6627f8..7d6305439e0 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
@@ -58,6 +58,13 @@ class AgentReadiness {
*/
private RemoteRules $remote_rules;
+ /**
+ * Product sales from Analytics.
+ *
+ * @var ProductSales
+ */
+ private ProductSales $product_sales;
+
/**
* Scan reused for single-product checks, with the shared GTINs the last stored scan found.
*
@@ -81,8 +88,10 @@ class AgentReadiness {
* @param StoreOutputChecks $store_output_checks Store checks that read what the store returns.
* @param RemoteRules $remote_rules Rules from the published rules file.
* @param DeclaredToAgents|null $declared_to_agents What the store declares to agents, resolved from the container when omitted.
+ * @param ProductSales|null $product_sales Product sales from Analytics, resolved from the container when omitted.
*/
- final public function init( StoreConditions $store_conditions, StoreOutputChecks $store_output_checks, RemoteRules $remote_rules, ?DeclaredToAgents $declared_to_agents = null ): void {
+ final public function init( StoreConditions $store_conditions, StoreOutputChecks $store_output_checks, RemoteRules $remote_rules, ?DeclaredToAgents $declared_to_agents = null, ?ProductSales $product_sales = null ): void {
+ $this->product_sales = $product_sales ?? wc_get_container()->get( ProductSales::class );
$this->store_conditions = $store_conditions;
$this->store_output_checks = $store_output_checks;
$this->declared_to_agents = $declared_to_agents ?? wc_get_container()->get( DeclaredToAgents::class );
@@ -205,7 +214,7 @@ class AgentReadiness {
/**
* Run every check over the catalog.
*
- * @return array{generated_at:string,products:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool}
+ * @return array{generated_at:string,products:int,available:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool,sales:array{days:int,orders:int,imported:bool}|null}
*/
public function get_report(): array {
return $this->build_report();
@@ -215,7 +224,7 @@ class AgentReadiness {
* Run every check over the catalog.
*
* @param callable|null $on_tested Called with each product id and its failures.
- * @return array{generated_at:string,products:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool,shared_gtins?:array<int,string>}
+ * @return array{generated_at:string,products:int,available:int,hidden_from_catalog:int,unsupported_types:int,store_checks:array<int,array<string,mixed>>,declared:array<int,array{id:string,name:string,found:bool|null}>,channels:array<string,array<string,mixed>>,checks:array<int,array<string,mixed>>,truncated:bool,sales:array{days:int,orders:int,imported:bool}|null,shared_gtins?:array<int,string>}
*/
private function build_report( ?callable $on_tested = null ): array {
// Rebuild the rules and the scan for each report: a long-running process may have fetched a new rules file or changed GTINs since.
@@ -225,7 +234,12 @@ class AgentReadiness {
$rules = $active['rules'];
$channel_rules = $active['channel_rules'];
- $scan = new ProductScan();
+ $sales = $this->product_sales->last_days();
+ $scan = new ProductScan();
+ $ranked = null !== $sales && $sales['imported'] && $sales['orders'] >= ProductSales::MIN_ORDERS && $sales['total'] > 0;
+ if ( $ranked ) {
+ $scan->use_sales( $sales['by_product'], $sales['by_variation'] );
+ }
if ( null === $on_tested ) {
$scan->evaluate( $rules, $channel_rules, self::PRODUCT_IDS_LIMIT );
} else {
@@ -243,6 +257,8 @@ class AgentReadiness {
'channels' => $channel_rules[ $id ],
'count' => $result['count'],
'product_ids' => $result['product_ids'],
+ // Share of the store's sales on the products that fail; null without enough sales to compare.
+ 'sales_share' => $ranked ? self::share( $result['sales'] / $sales['total'] ) : null,
'fix_url' => admin_url( 'edit.php?post_type=product' ),
);
}
@@ -252,6 +268,7 @@ class AgentReadiness {
$report = array(
'generated_at' => gmdate( 'c' ),
'products' => $scan->products(),
+ 'available' => $scan->available(),
'hidden_from_catalog' => $scan->hidden_from_catalog(),
'unsupported_types' => $scan->unsupported_types(),
'store_checks' => array_merge( $this->store_conditions->all(), $this->store_output_checks->all_for( $responses ) ),
@@ -259,6 +276,12 @@ class AgentReadiness {
'channels' => $scan->channel_totals(),
'checks' => $checks,
'truncated' => $scan->truncated(),
+ // How sales shares were measured: null while Analytics is off.
+ 'sales' => null === $sales ? null : array(
+ 'days' => $sales['days'],
+ 'orders' => $sales['orders'],
+ 'imported' => $sales['imported'],
+ ),
);
if ( null !== $on_tested && null !== $scan->shared_gtins() ) {
// Stored for checks of one product, so a save doesn't read every published product.
@@ -267,6 +290,16 @@ class AgentReadiness {
return $report;
}
+ /**
+ * A share of sales from 0 to 1, rounded to 4 places. Any sales at all keep at least 0.0001, so they never read as none.
+ *
+ * @param float $share Unrounded share; refunds can push it below 0 or, with other products' refunds, above 1.
+ */
+ private static function share( float $share ): float {
+ $share = min( 1.0, max( 0.0, $share ) );
+ return $share > 0.0 ? max( 0.0001, round( $share, 4 ) ) : 0.0;
+ }
+
/**
* The last stored report, or null when there is none.
*
@@ -312,14 +345,23 @@ class AgentReadiness {
if ( ! is_array( $check ) || ! isset( $check['id'] ) ) {
continue;
}
- $id = (string) $check['id'];
- $report['checks'][ $index ]['count'] = $counts[ $id ] ?? 0;
- $report['checks'][ $index ]['product_ids'] = array_values(
+ $id = (string) $check['id'];
+ $count = $counts[ $id ] ?? 0;
+ $examples = array_map( 'intval', (array) ( $check['product_ids'] ?? array() ) );
+ $still = array_values(
array_filter(
- (array) ( $check['product_ids'] ?? array() ),
- static fn( $product_id ): bool => in_array( $id, ProductFailures::for_product( (int) $product_id ), true )
+ $examples,
+ static fn( int $product_id ): bool => in_array( $id, ProductFailures::for_product( $product_id ), true )
)
);
+ // Drop the displayed share when the failing set changed, even if the count stayed the same
+ // (e.g. one example fixed and another product now fails). Fix first still ranks by the scan-time share.
+ if ( (int) ( $check['count'] ?? 0 ) !== $count || $still !== $examples ) {
+ $report['checks'][ $index ]['ranked_share'] = $check['sales_share'] ?? null;
+ $report['checks'][ $index ]['sales_share'] = null;
+ }
+ $report['checks'][ $index ]['count'] = $count;
+ $report['checks'][ $index ]['product_ids'] = $still;
}
// Every product the checks cover has a checked row, so products added, fixed or removed since the scan count now.
$products = $counts[ ProductFailures::CHECKED ] ?? 0;
@@ -346,7 +388,8 @@ class AgentReadiness {
/**
* Store checks as they stand now: the store conditions read live, then the
* store output checks from the stored report, since those run only in the scan.
- * Output checks are always recommended, whatever the stored report says.
+ * Output checks are always recommended, whatever the stored report says, and
+ * one the rules file has turned off since the scan is left out.
*
* @param array<string, mixed>|null $report Stored report.
* @param array<int, array{id:string,ok:bool|null,blocks:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string}>|null $live Store conditions already read, or null to read them.
@@ -359,6 +402,9 @@ class AgentReadiness {
if ( ! is_array( $check ) || ! isset( $check['id'], $check['name'] ) || in_array( $check['id'], $live_ids, true ) ) {
continue;
}
+ if ( StoreConditions::is_off( (string) $check['id'] ) ) {
+ continue;
+ }
$checks[] = array(
'id' => (string) $check['id'],
'ok' => isset( $check['ok'] ) ? (bool) $check['ok'] : null,
@@ -417,7 +463,7 @@ class AgentReadiness {
/**
* Ids of the checks one product fails. A variation is judged by its parent,
* as the scan counts it; other products the scan leaves out (other types,
- * hidden from the shop catalog, unpublished) have no issues.
+ * set to Hidden, unpublished) have no issues.
*
* @param \WC_Product $product Product or variation.
* @return array<int, string>
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php
index 71aa8127d0e..e73351c5ea6 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettings.php
@@ -20,6 +20,11 @@ class AgenticCommerceSettings implements RegisterHooksInterface {
public const TAB = 'agentic-commerce';
+ /**
+ * The AI shopping section of the tab, which the landing page's Manage button opens.
+ */
+ public const SHOPPING_SECTION = 'shopping';
+
public const PRIVACY_PAGE_OPTION = 'wp_page_for_privacy_policy';
public const TERMS_PAGE_OPTION = 'woocommerce_terms_page_id';
@@ -70,6 +75,15 @@ class AgenticCommerceSettings implements RegisterHooksInterface {
*/
private ScheduledScan $scheduled_scan;
+ /**
+ * Link to the AI tools tab: its landing page, or a section of it.
+ *
+ * @param string $section Section id, or '' for the landing page.
+ */
+ public static function url( string $section = '' ): string {
+ return admin_url( 'admin.php?page=wc-settings&tab=' . self::TAB . ( '' === $section ? '' : '§ion=' . $section ) );
+ }
+
/**
* Initialize dependencies.
*
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php
index 26e051a9ef7..f3a17b11b69 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php
@@ -172,7 +172,7 @@ class AgenticCommerceSettingsPage extends \WC_Settings_Page {
echo '<p class="wc-agentic-commerce-intro">' . esc_html__( 'Let AI shopping assistants find your products, build a cart, and send shoppers to your checkout to pay. Uses the Universal Commerce Protocol (UCP).', 'woocommerce' ) . '</p>';
$this->render_switch( $checks, count( $failing ) );
$this->render_visibility( $report );
- $this->render_status( $checks, $this->ucp_switch->status( $failing ), count( $failing ) );
+ $this->render_status( $checks, $this->ucp_switch->status( $failing ) );
$this->render_readiness( array_slice( $this->agent_readiness->get_store_checks( $report, $checks ), count( $checks ) ), (bool) ( array_column( $checks, 'ok', 'id' )['launched'] ?? true ), $report );
echo '<div class="wc-agentic-commerce-card wc-agentic-commerce-policies">';
@@ -496,11 +496,10 @@ class AgenticCommerceSettingsPage extends \WC_Settings_Page {
* The Status card: a badge, then the setup checks grouped into Required, Recommended and Done.
* Each open check says what to do and links to where to do it. UCP itself is the switch, so it is not listed.
*
- * @param array<int, array{id:string,level:string,ok:bool,name:string,label:string,fix_url:string}> $checks Store conditions.
- * @param string $status UcpSwitch status.
- * @param int $failing_required Number of failing required setup checks.
+ * @param array<int, array{id:string,level:string,ok:bool,name:string,label:string,fix_url:string}> $checks Store conditions.
+ * @param string $status UcpSwitch status.
*/
- private function render_status( array $checks, string $status, int $failing_required ): void {
+ private function render_status( array $checks, string $status ): void {
$statuses = self::status_labels();
$classes = array(
UcpSwitch::STATUS_ACTIVE => 'pass',
@@ -516,12 +515,14 @@ class AgenticCommerceSettingsPage extends \WC_Settings_Page {
if ( 'ucp_on' === $check['id'] ) {
continue;
}
- $group = $check['ok'] ? 'done' : ( StoreConditions::LEVEL_REQUIRED === $check['level'] ? 'required' : 'recommended' );
+ $group = $check['ok'] ? 'done' : ( StoreConditions::shows_required( $check ) ? 'required' : 'recommended' );
$groups[ $group ][1][] = $check;
}
- $summary = $failing_required > 0
- /* translators: %d: number of failing required setup checks. */
- ? sprintf( _n( '%d required step to finish so agents can shop your store.', '%d required steps to finish so agents can shop your store.', $failing_required, 'woocommerce' ), $failing_required )
+ // The summary follows the Required rows on this card. $failing_required is the smaller set that blocks the switch.
+ $shown_failing = count( $groups['required'][1] );
+ $summary = $shown_failing > 0
+ /* translators: %d: number of failing checks shown as Required. */
+ ? sprintf( _n( '%d required step to finish so agents can shop your store.', '%d required steps to finish so agents can shop your store.', $shown_failing, 'woocommerce' ), $shown_failing )
: __( 'Everything agents need is set up.', 'woocommerce' );
?>
<div class="wc-agentic-commerce-card wc-agentic-commerce-status-card">
@@ -604,16 +605,16 @@ class AgenticCommerceSettingsPage extends \WC_Settings_Page {
/**
* One line on where a question stands.
*
- * @param string $group Question id.
- * @param array<int, array{ok:bool|null,level:string,pending?:bool}> $checks The question's checks. Pending ones don't count as unchecked.
- * @param bool $scanned Whether a scan has run.
- * @param int $product_problems Failing product checks under the question.
- * @param bool $ucp_scanned Whether the last scan checked UCP.
- * @param bool $ucp_enabled Whether UCP is on.
+ * @param string $group Question id.
+ * @param array<int, array{id:string,ok:bool|null,level:string,pending?:bool}> $checks The question's checks. Pending ones don't count as unchecked.
+ * @param bool $scanned Whether a scan has run.
+ * @param int $product_problems Failing product checks under the question.
+ * @param bool $ucp_scanned Whether the last scan checked UCP.
+ * @param bool $ucp_enabled Whether UCP is on.
*/
private static function group_summary( string $group, array $checks, bool $scanned, int $product_problems, bool $ucp_scanned, bool $ucp_enabled ): string {
- $fix = count( array_filter( $checks, static fn( array $check ): bool => false === $check['ok'] && StoreConditions::LEVEL_REQUIRED === $check['level'] ) );
- $check = $product_problems + count( array_filter( $checks, static fn( array $check ): bool => false === $check['ok'] && StoreConditions::LEVEL_REQUIRED !== $check['level'] ) );
+ $fix = count( array_filter( $checks, static fn( array $check ): bool => false === $check['ok'] && StoreConditions::shows_required( $check ) ) );
+ $check = $product_problems + count( array_filter( $checks, static fn( array $check ): bool => false === $check['ok'] && ! StoreConditions::shows_required( $check ) ) );
$unknown = count( array_filter( $checks, static fn( array $check ): bool => null === $check['ok'] && empty( $check['pending'] ) ) );
$parts = array();
if ( $fix > 0 ) {
@@ -667,7 +668,7 @@ class AgenticCommerceSettingsPage extends \WC_Settings_Page {
$badge = array( 'pass', __( 'Pass', 'woocommerce' ) );
} elseif ( $conflict ) {
$badge = array( 'check', __( 'Likely conflict', 'woocommerce' ) );
- } elseif ( StoreConditions::LEVEL_REQUIRED === $check['level'] ) {
+ } elseif ( StoreConditions::shows_required( $check ) ) {
$badge = array( 'fix', __( 'Fix', 'woocommerce' ) );
} else {
$badge = array( 'check', __( 'Check', 'woocommerce' ) );
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/AbstractReadinessCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/AbstractReadinessCheck.php
index 670f937c40a..5b72f28eed8 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/AbstractReadinessCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/AbstractReadinessCheck.php
@@ -4,6 +4,8 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\AgentReadiness\Checks;
use Automattic\WooCommerce\Internal\AgentReadiness\FeedChannels;
+use Automattic\WooCommerce\Internal\AgentReadiness\ProductFields;
+use Automattic\WooCommerce\Internal\AgentReadiness\ProductScan;
use Automattic\WooCommerce\Internal\AgentReadiness\ReadinessRule;
defined( 'ABSPATH' ) || exit;
@@ -32,6 +34,36 @@ abstract class AbstractReadinessCheck implements ReadinessRule {
);
}
+ /**
+ * The published variations of a failing variable product that have the problem, so only their
+ * sales count against it. Null when the problem is the whole product's.
+ *
+ * @param \WC_Product $product Product that fails the rule.
+ * @param ProductScan $scan Catalog-wide lookups.
+ * @return array<int, int>|null Variation ids.
+ */
+ public function failing_variations( \WC_Product $product, ProductScan $scan ): ?array {
+ unset( $product, $scan );
+ return null;
+ }
+
+ /**
+ * Only the ids of the variations a test fails, or null when none does, as when the parent fails.
+ *
+ * @param \WC_Product $product Product.
+ * @param callable $test Whether a variation has the problem: fn( \WC_Product ): bool.
+ * @return array<int, int>|null
+ */
+ protected static function variation_ids_where( \WC_Product $product, callable $test ): ?array {
+ $ids = array();
+ foreach ( ProductFields::variations( $product ) as $variation ) {
+ if ( $test( $variation ) ) {
+ $ids[] = $variation->get_id();
+ }
+ }
+ return array() === $ids ? null : $ids;
+ }
+
/**
* Field and effect by channel for one failing product: the given map.
*
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php
index 822427060a5..3c40c0ef3cb 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php
@@ -75,6 +75,27 @@ class MissingGtinCheck extends AbstractReadinessCheck {
return $channels;
}
+ /**
+ * The variations that need a GTIN and have none.
+ *
+ * @param \WC_Product $product Product that fails the rule.
+ * @param ProductScan $scan Catalog-wide lookups.
+ * @return array<int, int>|null
+ */
+ public function failing_variations( \WC_Product $product, ProductScan $scan ): ?array {
+ unset( $scan );
+ return self::variation_ids_where( $product, static fn( \WC_Product $variation ): bool => self::lacks_gtin( $variation ) );
+ }
+
+ /**
+ * Whether a product or variation needs a GTIN and has none.
+ *
+ * @param \WC_Product $item Product or variation.
+ */
+ private static function lacks_gtin( \WC_Product $item ): bool {
+ return ProductFields::needs_identifiers( $item ) && '' === ProductFields::normalise_gtin( (string) $item->get_global_unique_id() );
+ }
+
/**
* Whether the product has this problem.
*
@@ -88,7 +109,7 @@ class MissingGtinCheck extends AbstractReadinessCheck {
// A variable product with no published variation lists nothing, so it needs no GTIN.
$items = $product instanceof \WC_Product_Variable ? ProductFields::variations( $product ) : array( $product );
foreach ( $items as $item ) {
- if ( ProductFields::needs_identifiers( $item ) && '' === ProductFields::normalise_gtin( (string) $item->get_global_unique_id() ) ) {
+ if ( self::lacks_gtin( $item ) ) {
return true;
}
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingRegularPriceCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingRegularPriceCheck.php
index b59261c999d..47829564a13 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingRegularPriceCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingRegularPriceCheck.php
@@ -75,6 +75,18 @@ class MissingRegularPriceCheck extends AbstractReadinessCheck {
return false;
}
+ /**
+ * The variations without a price.
+ *
+ * @param \WC_Product $product Product that fails the rule.
+ * @param ProductScan $scan Catalog-wide lookups.
+ * @return array<int, int>|null
+ */
+ public function failing_variations( \WC_Product $product, ProductScan $scan ): ?array {
+ unset( $scan );
+ return self::variation_ids_where( $product, static fn( \WC_Product $variation ): bool => ! self::has_positive_price( $variation ) );
+ }
+
/**
* A gap, not a missing listing, for a variable product with a priced variation.
*
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/SimpleCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/SimpleCheck.php
index 94705af9b8c..7a872a84a71 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/SimpleCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/SimpleCheck.php
@@ -47,6 +47,13 @@ final class SimpleCheck extends AbstractReadinessCheck {
*/
private \Closure $test;
+ /**
+ * Whether one variation has the problem, for checks a variable product fails through its variations.
+ *
+ * @var \Closure(\WC_Product):bool|null
+ */
+ private ?\Closure $variation_test;
+
/**
* Build a check.
*
@@ -54,12 +61,14 @@ final class SimpleCheck extends AbstractReadinessCheck {
* @param array{label:string,why:string,fix:string} $texts Merchant-facing texts.
* @param array<string, array{field:string,effect:string}> $channels Field and effect by channel.
* @param \Closure $test Whether a product has the problem: fn( \WC_Product ): bool.
+ * @param \Closure|null $variation_test Whether one variation has it, for checks a variable product fails through its variations.
*/
- public function __construct( string $id, array $texts, array $channels, \Closure $test ) {
- $this->id = $id;
- $this->texts = $texts;
- $this->channels = $channels;
- $this->test = $test;
+ public function __construct( string $id, array $texts, array $channels, \Closure $test, ?\Closure $variation_test = null ) {
+ $this->id = $id;
+ $this->texts = $texts;
+ $this->channels = $channels;
+ $this->test = $test;
+ $this->variation_test = $variation_test;
}
/**
@@ -119,7 +128,8 @@ final class SimpleCheck extends AbstractReadinessCheck {
'fix' => __( 'Set the options on each variation.', 'woocommerce' ),
),
self::fields( array( 'variant_dict', 'color, size', 'color, sizes' ), self::EFFECT_GAPS ),
- \Closure::fromCallable( array( self::class, 'has_unset_variation_option' ) )
+ \Closure::fromCallable( array( self::class, 'has_unset_variation_option' ) ),
+ \Closure::fromCallable( array( self::class, 'has_unset_option' ) )
),
new self(
'missing_variation_images',
@@ -131,12 +141,13 @@ final class SimpleCheck extends AbstractReadinessCheck {
self::fields( array( 'image_url', 'image_link', 'imageLink' ), self::EFFECT_GAPS ),
static function ( \WC_Product $product ): bool {
foreach ( ProductFields::variations( $product ) as $variation ) {
- if ( (int) $variation->get_image_id( 'edit' ) <= 0 ) {
+ if ( self::has_no_own_image( $variation ) ) {
return true;
}
}
return false;
- }
+ },
+ \Closure::fromCallable( array( self::class, 'has_no_own_image' ) )
),
new self(
'title_too_long',
@@ -206,13 +217,43 @@ final class SimpleCheck extends AbstractReadinessCheck {
return true;
}
foreach ( ProductFields::variations( $product ) as $variation ) {
- if ( in_array( '', array_map( 'strval', $variation->get_attributes() ), true ) ) {
+ if ( self::has_unset_option( $variation ) ) {
return true;
}
}
return false;
}
+ /**
+ * Whether a variation has an option set to "any".
+ *
+ * @param \WC_Product $variation Variation.
+ */
+ private static function has_unset_option( \WC_Product $variation ): bool {
+ return in_array( '', array_map( 'strval', $variation->get_attributes() ), true );
+ }
+
+ /**
+ * Whether a variation has no image of its own.
+ *
+ * @param \WC_Product $variation Variation.
+ */
+ private static function has_no_own_image( \WC_Product $variation ): bool {
+ return (int) $variation->get_image_id( 'edit' ) <= 0;
+ }
+
+ /**
+ * The variations that have the problem, for checks a variable product fails through its variations.
+ *
+ * @param \WC_Product $product Product that fails the rule.
+ * @param ProductScan $scan Catalog-wide lookups.
+ * @return array<int, int>|null
+ */
+ public function failing_variations( \WC_Product $product, ProductScan $scan ): ?array {
+ unset( $scan );
+ return null === $this->variation_test ? null : self::variation_ids_where( $product, $this->variation_test );
+ }
+
/**
* Check id.
*/
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/DeclaredToAgents.php b/plugins/woocommerce/src/Internal/AgentReadiness/DeclaredToAgents.php
index 68a05344445..96289703f62 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/DeclaredToAgents.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/DeclaredToAgents.php
@@ -52,9 +52,6 @@ class DeclaredToAgents {
'editorial-metadata' => array( __( 'Author and publish date', 'woocommerce' ), self::has_editorial_metadata( array( $home, $page ) ) ),
'site-search-autocomplete' => array( __( 'On-site search with autocomplete', 'woocommerce' ), self::page_has_tag( array( $home ), array( 'INPUT' ), array( self::class, 'is_autocomplete_search' ) ) ),
'mcp-server-card' => array( __( 'MCP server card', 'woocommerce' ), self::either( self::document_served( $responses, '/.well-known/mcp/server-card.json', array( self::class, 'is_mcp_server_card' ) ), self::document_served( $responses, '/.well-known/mcp.json', array( self::class, 'is_mcp_server_card' ) ) ) ),
- // Not read yet: DNS-AID needs a DNS lookup, and a feed product sync is set up outside the store's pages.
- 'dns-aid' => array( __( 'DNS for AI Discovery (DNS-AID)', 'woocommerce' ), null ),
- 'product-feed-automation' => array( __( 'Automated product feed', 'woocommerce' ), null ),
);
foreach ( $lines as $id => $line ) {
$items[] = array(
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php
new file mode 100644
index 00000000000..cbc1c120299
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductSales.php
@@ -0,0 +1,176 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Internal\AgentReadiness;
+
+use Automattic\WooCommerce\Internal\Admin\Analytics;
+use Automattic\WooCommerce\Internal\Admin\Settings;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Each product's net sales over the last DAYS days, read from the Analytics order
+ * lookup tables, so Sales readiness can rank product problems by the sales they put
+ * at stake. Variations count toward their parent product, and are also kept on their own.
+ * Orders are counted as Analytics counts them, leaving out the statuses its settings exclude.
+ *
+ * @since 11.4.0
+ */
+class ProductSales {
+
+ public const DAYS = 90;
+
+ /**
+ * Below this many orders over DAYS, shares of sales are too noisy to rank by, so checks rank by product count.
+ */
+ public const MIN_ORDERS = 20;
+
+ /**
+ * Share of the store's orders that must be in Analytics for its sales to count as imported.
+ * New orders reach Analytics shortly after they are placed, so the last few may be missing.
+ * A store with fewer than MIN_ORDERS orders ranks by product count anyway, so it counts as imported.
+ */
+ private const IMPORTED_SHARE = 0.9;
+
+ /**
+ * Net sales by product id and by variation id, their total, the number of orders, and whether
+ * Analytics holds the store's orders for the period, or null while Analytics is off.
+ *
+ * @return array{days:int,orders:int,imported:bool,total:float,by_product:array<int,float>,by_variation:array<int,float>}|null
+ */
+ public function last_days(): ?array {
+ global $wpdb;
+
+ if ( 'yes' !== get_option( Analytics::TOGGLE_OPTION_NAME, 'yes' ) ) {
+ return null;
+ }
+
+ // The lookup tables store dates in the site's time zone.
+ $start = new \DateTimeImmutable( '-' . self::DAYS . ' days', wp_timezone() );
+ $since = $start->format( 'Y-m-d H:i:s' );
+ $excluded = self::excluded_statuses();
+ // A filter may leave nothing to exclude, and `NOT IN ()` is not valid SQL.
+ $not_in = array() === $excluded ? '' : 'AND stats.status NOT IN ( ' . implode( ', ', array_fill( 0, count( $excluded ), '%s' ) ) . ' )';
+ $lookup = $wpdb->prefix . 'wc_order_product_lookup';
+ $stats = $wpdb->prefix . 'wc_order_stats';
+
+ // Count first so an Analytics import that commits between the two reads cannot make
+ // the order total cover revenue that this request never saw.
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Table names from $wpdb, placeholders built for the excluded statuses; the scan runs this once, in the background.
+ $orders = (int) $wpdb->get_var(
+ $wpdb->prepare(
+ "SELECT COUNT( DISTINCT stats.order_id )
+ FROM {$stats} AS stats
+ WHERE stats.parent_id = 0 AND stats.date_created >= %s {$not_in}",
+ array_merge( array( $since ), $excluded )
+ )
+ );
+ $rows = $wpdb->get_results(
+ $wpdb->prepare(
+ "SELECT lookup.product_id, lookup.variation_id, SUM( lookup.product_net_revenue ) AS revenue
+ FROM {$lookup} AS lookup
+ INNER JOIN {$stats} AS stats ON stats.order_id = lookup.order_id
+ WHERE lookup.date_created >= %s {$not_in}
+ GROUP BY lookup.product_id, lookup.variation_id",
+ array_merge( array( $since ), $excluded )
+ ),
+ ARRAY_A
+ );
+ // phpcs:enable
+
+ $by_product = array();
+ $by_variation = array();
+ foreach ( is_array( $rows ) ? $rows : array() as $row ) {
+ $product_id = (int) $row['product_id'];
+ $by_product[ $product_id ] = ( $by_product[ $product_id ] ?? 0.0 ) + (float) $row['revenue'];
+ if ( (int) $row['variation_id'] > 0 ) {
+ $by_variation[ (int) $row['variation_id'] ] = (float) $row['revenue'];
+ }
+ }
+ return array(
+ 'days' => self::DAYS,
+ 'orders' => $orders,
+ 'imported' => self::is_imported( $orders, self::store_orders( $start, $excluded ) ),
+ 'total' => max( 0.0, array_sum( $by_product ) ),
+ 'by_product' => $by_product,
+ 'by_variation' => $by_variation,
+ );
+ }
+
+ /**
+ * Whether Analytics holds enough of the store's orders. A store with too few orders to rank by
+ * keeps the "too few orders" reason instead.
+ *
+ * @param int $in_analytics Orders in Analytics for the period.
+ * @param int $in_store Orders the store holds for the period.
+ */
+ private static function is_imported( int $in_analytics, int $in_store ): bool {
+ return $in_store < self::MIN_ORDERS || $in_analytics >= self::IMPORTED_SHARE * $in_store;
+ }
+
+ /**
+ * How many orders the store holds since a date, with the statuses Analytics counts. Analytics
+ * holds fewer while its import of past orders hasn't run or finished. WCPay test-mode orders
+ * are left out the same way OrdersScheduler skips them (meta `_wcpay_mode=test`). They are
+ * counted in a second query and subtracted, because the posts order store doesn't support
+ * `meta_query`. A custom `woocommerce_analytics_is_test_order` callback is not applied.
+ *
+ * @param \DateTimeImmutable $since Start of the period.
+ * @param array<int, string> $excluded Statuses Analytics leaves out.
+ */
+ private static function store_orders( \DateTimeImmutable $since, array $excluded ): int {
+ $statuses = array_diff( array_keys( wc_get_order_statuses() ), $excluded, array( 'wc-checkout-draft' ) );
+ if ( array() === $statuses ) {
+ return 0;
+ }
+ $count = static function ( array $extra ) use ( $since, $statuses ): int {
+ $orders = wc_get_orders(
+ array(
+ 'type' => 'shop_order',
+ 'status' => array_values( $statuses ),
+ 'date_created' => '>=' . $since->getTimestamp(),
+ 'limit' => 1,
+ 'return' => 'ids',
+ 'paginate' => true,
+ ) + $extra
+ );
+ return is_object( $orders ) && isset( $orders->total ) ? (int) $orders->total : 0;
+ };
+ $all = $count( array() );
+ // Below MIN_ORDERS the import check passes anyway, so test orders can't change it.
+ if ( $all < self::MIN_ORDERS ) {
+ return $all;
+ }
+ return max(
+ 0,
+ $all - $count(
+ array(
+ 'meta_key' => '_wcpay_mode', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- One count for the import check.
+ 'meta_value' => 'test', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- One count for the import check.
+ )
+ )
+ );
+ }
+
+ /**
+ * The order statuses Analytics leaves out, as the stats table stores them: with and without the `wc-` prefix.
+ *
+ * @return array<int, string>
+ */
+ private static function excluded_statuses(): array {
+ $default = Settings::get_default_excluded_order_statuses();
+ $excluded = Settings::get_valid_order_statuses_or_default( get_option( 'woocommerce_excluded_report_order_statuses', $default ), $default );
+ // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Core's Analytics hook, documented in Admin\API\Reports\DataStore.
+ $filtered = apply_filters( 'woocommerce_analytics_excluded_order_statuses', array_merge( array( 'auto-draft', 'trash' ), $excluded ) );
+ $statuses = array();
+ foreach ( is_array( $filtered ) ? $filtered : $excluded as $status ) {
+ if ( is_string( $status ) && '' !== $status ) {
+ // The status column holds 20 characters, so longer custom statuses are stored cut short.
+ $status = str_starts_with( $status, 'wc-' ) ? substr( $status, 3 ) : $status;
+ $statuses[] = substr( $status, 0, 20 );
+ $statuses[] = substr( 'wc-' . $status, 0, 20 );
+ }
+ }
+ return array_values( array_unique( $statuses ) );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
index c5189ec5ccb..54d991e7c41 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
@@ -3,6 +3,8 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\AgentReadiness;
+use Automattic\WooCommerce\Internal\AgentReadiness\Checks\AbstractReadinessCheck;
+
defined( 'ABSPATH' ) || exit;
/**
@@ -11,9 +13,10 @@ defined( 'ABSPATH' ) || exit;
* Walks published simple and variable products in batches, most recently
* modified first, tests each against every rule once and tallies product
* statuses per channel. Stops after PRODUCT_LIMIT products so the scan stays
- * inside one request. Products hidden from the shop catalog are the merchant's
- * choice and other product types are not supported by agents yet, so both are
- * counted, not checked.
+ * inside one request. Products set to Hidden are the merchant's choice and
+ * agents can't buy other product types through UCP yet, so both are counted,
+ * not checked. "Search results only" products are checked: agents find them
+ * by search.
*
* @since 11.4.0
*/
@@ -25,17 +28,46 @@ class ProductScan {
public const SUPPORTED_TYPES = array( 'simple', 'variable' );
+ /**
+ * Published products of a supported type that shoppers can find in the catalog: the ones agents see.
+ */
+ public const COUNT_AVAILABLE = 'available';
+
+ /**
+ * Published products of a supported type with Catalog visibility set to Hidden.
+ */
+ public const COUNT_HIDDEN = 'hidden';
+
+ /**
+ * Published products of a type agents can't sell yet.
+ */
+ public const COUNT_UNSUPPORTED = 'unsupported';
+
public const NOT_LISTABLE = 'not_listable';
public const WITH_GAPS = 'with_gaps';
public const COMPLETE = 'complete';
/**
- * Count and product ids per rule id.
+ * Count, product ids and the failing products' sales per rule id.
*
- * @var array<string, array{count:int,product_ids:array<int,int>}>
+ * @var array<string, array{count:int,product_ids:array<int,int>,sales:float}>
*/
private array $results = array();
+ /**
+ * Net sales by product id, from ProductSales, or empty when none were given.
+ *
+ * @var array<int, float>
+ */
+ private array $sales = array();
+
+ /**
+ * Net sales by variation id, from ProductSales.
+ *
+ * @var array<int, float>
+ */
+ private array $variation_sales = array();
+
/**
* Products tested.
*
@@ -44,12 +76,19 @@ class ProductScan {
private int $products = 0;
/**
- * Published products of a supported type hidden from the shop catalog.
+ * Published products of a supported type set to Hidden.
*
* @var int
*/
private int $hidden_from_catalog = 0;
+ /**
+ * Published products agents can see, the scan's catalog. More than it checks when it stops at PRODUCT_LIMIT.
+ *
+ * @var int
+ */
+ private int $available = 0;
+
/**
* Published products of a type agents don't support yet.
*
@@ -99,7 +138,7 @@ class ProductScan {
return 'publish' === $product->get_status()
&& ! $product instanceof \WC_Product_Variation
&& in_array( self::stored_type( $product ), self::SUPPORTED_TYPES, true )
- && ! in_array( $product->get_catalog_visibility(), array( 'search', 'hidden' ), true );
+ && 'hidden' !== $product->get_catalog_visibility();
}
/**
@@ -145,26 +184,15 @@ class ProductScan {
array(
'count' => 0,
'product_ids' => array(),
+ 'sales' => 0.0,
)
);
$this->products = 0;
$this->statuses = array();
$this->truncated = false;
- $this->hidden_from_catalog = self::count_published( array( self::supported_type_query(), self::catalog_query( 'IN' ) ) );
- $this->unsupported_types = self::count_published(
- array(
- array(
- 'taxonomy' => 'product_type',
- 'field' => 'slug',
- 'terms' => self::SUPPORTED_TYPES,
- 'operator' => 'NOT IN',
- ),
- array(
- 'taxonomy' => 'product_type',
- 'operator' => 'EXISTS',
- ),
- )
- );
+ $this->hidden_from_catalog = self::count_published( self::count_query( self::COUNT_HIDDEN ) );
+ $this->available = self::count_published( self::count_query( self::COUNT_AVAILABLE ) );
+ $this->unsupported_types = self::count_published( self::count_query( self::COUNT_UNSUPPORTED ) );
$flush_runtime_cache = wp_cache_supports( 'flush_runtime' );
$page = 1;
@@ -181,10 +209,7 @@ class ProductScan {
'ID' => 'DESC',
),
'no_found_rows' => true,
- 'tax_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
- self::supported_type_query(),
- self::catalog_query( 'NOT IN' ),
- ),
+ 'tax_query' => self::count_query( self::COUNT_AVAILABLE ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
)
);
@@ -227,6 +252,30 @@ class ProductScan {
$this->tested_callback = null;
}
+ /**
+ * The tax query behind a product count, so the Products list a count links to shows the same products.
+ *
+ * @param string $count COUNT_AVAILABLE, COUNT_HIDDEN or COUNT_UNSUPPORTED.
+ * @return array<int, array<string|int, mixed>>
+ */
+ public static function count_query( string $count ): array {
+ if ( self::COUNT_UNSUPPORTED === $count ) {
+ return array(
+ array(
+ 'taxonomy' => 'product_type',
+ 'field' => 'slug',
+ 'terms' => self::SUPPORTED_TYPES,
+ 'operator' => 'NOT IN',
+ ),
+ array(
+ 'taxonomy' => 'product_type',
+ 'operator' => 'EXISTS',
+ ),
+ );
+ }
+ return array( self::supported_type_query(), self::catalog_query( self::COUNT_HIDDEN === $count ) );
+ }
+
/**
* Tax query for a supported type. A product with no type term loads as simple.
*
@@ -248,18 +297,23 @@ class ProductScan {
}
/**
- * Tax query on the shop catalog: "Search results only" and "Hidden" both
- * carry the exclude-from-catalog term.
+ * Tax query on catalog visibility. Only "Hidden" carries both the
+ * exclude-from-catalog and exclude-from-search terms.
*
- * @param string $operator IN for hidden products, NOT IN for the rest.
- * @return array<string, mixed>
+ * @param bool $hidden True for Hidden products, false for the rest.
+ * @return array<string|int, mixed>
*/
- private static function catalog_query( string $operator ): array {
- return array(
+ private static function catalog_query( bool $hidden ): array {
+ $term = static fn( string $name ): array => array(
'taxonomy' => 'product_visibility',
'field' => 'name',
- 'terms' => array( 'exclude-from-catalog' ),
- 'operator' => $operator,
+ 'terms' => array( $name ),
+ 'operator' => $hidden ? 'IN' : 'NOT IN',
+ );
+ return array(
+ 'relation' => $hidden ? 'AND' : 'OR',
+ $term( 'exclude-from-catalog' ),
+ $term( 'exclude-from-search' ),
);
}
@@ -334,18 +388,31 @@ class ProductScan {
}
/**
- * Count and product ids for one rule.
+ * Count, product ids and the failing products' sales for one rule.
*
* @param string $rule_id Rule id.
- * @return array{count:int,product_ids:array<int,int>}
+ * @return array{count:int,product_ids:array<int,int>,sales:float}
*/
public function result( string $rule_id ): array {
return $this->results[ $rule_id ] ?? array(
'count' => 0,
'product_ids' => array(),
+ 'sales' => 0.0,
);
}
+ /**
+ * Sales to add up per rule over the next evaluate(): each failing product adds its own, or
+ * only its failing variations' when the check names them.
+ *
+ * @param array<int, float> $by_product Net sales by product id.
+ * @param array<int, float> $by_variation Net sales by variation id.
+ */
+ public function use_sales( array $by_product, array $by_variation = array() ): void {
+ $this->sales = $by_product;
+ $this->variation_sales = $by_variation;
+ }
+
/**
* Products tested.
*/
@@ -354,7 +421,14 @@ class ProductScan {
}
/**
- * Published products of a supported type hidden from the shop catalog, not checked.
+ * Published products agents can see, including any past PRODUCT_LIMIT.
+ */
+ public function available(): int {
+ return $this->available;
+ }
+
+ /**
+ * Published products of a supported type set to Hidden, not checked.
*/
public function hidden_from_catalog(): int {
return $this->hidden_from_catalog;
@@ -529,6 +603,21 @@ class ProductScan {
return $failed;
}
+ /**
+ * The sales a rule puts at stake on one failing product: its failing variations' when the rule
+ * names them, else the whole product's.
+ *
+ * @param \WC_Product $product Product that fails the rule.
+ * @param ReadinessRule $rule Rule.
+ */
+ private function sales_failing( \WC_Product $product, ReadinessRule $rule ): float {
+ $variations = array() !== $this->sales && $rule instanceof AbstractReadinessCheck ? $rule->failing_variations( $product, $this ) : null;
+ if ( null === $variations ) {
+ return $this->sales[ $product->get_id() ] ?? 0.0;
+ }
+ return array_sum( array_intersect_key( $this->variation_sales, array_flip( $variations ) ) );
+ }
+
/**
* Test one product and add it to the results and totals.
*
@@ -545,6 +634,7 @@ class ProductScan {
foreach ( array_keys( $failures ) as $id ) {
$result = $this->result( $id );
++$result['count'];
+ $result['sales'] += $this->sales_failing( $product, $rules[ $id ] );
if ( count( $result['product_ids'] ) < $ids_limit ) {
$result['product_ids'][] = $product->get_id();
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
index 65d32ff602d..778882c0320 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
@@ -285,7 +285,7 @@ class ProductsList {
}
/**
- * Limit the Products list to the chosen problem.
+ * Limit the Products list to the chosen problem, or to the products behind one of the settings page's counts.
*
* @internal
*
@@ -297,14 +297,25 @@ class ProductsList {
if ( ! $query instanceof \WP_Query || ! is_admin() || 'edit.php' !== $pagenow || ! $query->is_main_query() || 'product' !== $query->get( 'post_type' ) || ! $this->enabled() || empty( $_GET[ self::FILTER_PARAM ] ) ) {
return;
}
+ // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A list filter that changes nothing.
+ $value = sanitize_text_field( wp_unslash( $_GET[ self::FILTER_PARAM ] ) );
+ if ( in_array( $value, array( ProductScan::COUNT_AVAILABLE, ProductScan::COUNT_HIDDEN, ProductScan::COUNT_UNSUPPORTED ), true ) ) {
+ // The list's own tax query stays a group of its own, as the meta query does below.
+ $existing = array_filter( (array) $query->get( 'tax_query' ) );
+ $tax_query = array_merge( array( 'relation' => 'AND' ), ProductScan::count_query( $value ) );
+ if ( array() !== $existing ) {
+ $tax_query[] = $existing;
+ }
+ $query->set( 'tax_query', $tax_query ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
+ return;
+ }
// The list's own meta query stays a group of its own, so an OR in it can't widen this filter.
$existing = array_filter( (array) $query->get( 'meta_query' ) );
$meta_query = array(
'relation' => 'AND',
array(
'key' => ProductFailures::META_KEY,
- // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A list filter that changes nothing.
- 'value' => sanitize_text_field( wp_unslash( $_GET[ self::FILTER_PARAM ] ) ),
+ 'value' => $value,
),
);
if ( array() !== $existing ) {
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index 0ea2e7e975a..8edd27f6347 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -52,7 +52,7 @@ Only published simple and variable products are checked, the types agents suppor
- Products hidden from the shop catalog (catalog visibility "Search results only" or "Hidden"). Agents see the products shoppers see in the shop, so hiding one is the merchant's choice, not a problem.
- Products of any other type: grouped, external, subscription, booking, bundle and so on. A product keeps its stored type when its plugin is inactive, so it stays in this group.
-Store-wide conditions (`StoreConditions`) are reported first because they affect every product: coming soon mode and "Discourage search engines" hide the products, UCP off, no HTTPS and a `/.well-known/ucp` the store can't serve (Plain permalinks without a static file, a file WooCommerce didn't write in the way, or WooCommerce's file with an outdated profile; see `UcpDiscovery::serve_status()`, which picks the fix shown) hide the catalog from UCP agents, and guest checkout off or no payment method turned on stops agents placing orders. Missing policy pages and order emails off weaken agent orders. Each condition's `blocks` says which, so a reader can tell a hidden store from one agents can't buy from.
+Store-wide conditions (`StoreConditions`) are reported first because they affect every product: coming soon mode and "Discourage search engines" hide the products, UCP off, no HTTPS and a `/.well-known/ucp` the store can't serve (Plain permalinks without a static file, a file WooCommerce didn't write in the way, or WooCommerce's file with an outdated profile; see `UcpDiscovery::serve_status()`, which picks the fix shown) hide the catalog from UCP agents, no payment method turned on stops agents placing orders, and guest checkout off stops UCP checkout while agents can still build carts. Missing policy pages and order emails off weaken agent orders. Each condition's `blocks` says which, so a reader can tell a hidden store from one agents can't buy from.
## Store output checks
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/RemoteRules.php b/plugins/woocommerce/src/Internal/AgentReadiness/RemoteRules.php
index 2accf8f9ee4..8a39d03b6fb 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/RemoteRules.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/RemoteRules.php
@@ -16,6 +16,13 @@ defined( 'ABSPATH' ) || exit;
* text, is named with an empty channel map ("channels": {}). A file is only
* stored when at least one check in it has a valid channel.
*
+ * The optional `store_checks` map changes store checks by id: `required`
+ * (true or false) sets whether a setup step or output check is shown as
+ * Required, and `"off": true` stops one running. An id the map leaves out
+ * keeps its bundled behaviour. A check that keeps AI shopping from being
+ * turned on (StoreConditions::LEVEL_REQUIRED) is always Required and can't be
+ * turned off. `version` is the date of the file's last change (Y-m-d).
+ *
* The file is fetched before each background scan: the daily run and any
* scan that is asked for. Only a GET is made; the request's user agent
* includes the site URL, as other WooCommerce.com polls do. A failed fetch
@@ -90,17 +97,48 @@ class RemoteRules {
if ( array() === $usable ) {
return false;
}
- update_option(
- self::OPTION,
- array(
- 'version' => (string) ( $rules['version'] ?? '' ),
- 'checks' => $checks,
- ),
- false
+ $stored = array(
+ 'version' => (string) ( $rules['version'] ?? '' ),
+ 'checks' => $checks,
);
+ $store_checks = self::valid_store_checks( $rules['store_checks'] ?? null );
+ if ( array() !== $store_checks ) {
+ $stored['store_checks'] = $store_checks;
+ }
+ update_option( self::OPTION, $stored, false );
return true;
}
+ /**
+ * What the stored file sets for one store check: `required` and `off`, each only when the file
+ * sets it. Empty when no file is stored or the file doesn't name the check.
+ *
+ * @param string $id Store check id.
+ * @return array{required?:bool,off?:bool}
+ */
+ public static function store_check( string $id ): array {
+ $stored = get_option( self::OPTION );
+ $check = is_array( $stored ) && is_array( $stored['store_checks'] ?? null ) ? ( $stored['store_checks'][ $id ] ?? null ) : null;
+ return is_array( $check ) ? $check : array();
+ }
+
+ /**
+ * The `store_checks` entries with a boolean `required` or `off`, keeping only those two keys.
+ *
+ * @param mixed $store_checks `store_checks` map from the file.
+ * @return array<string, array{required?:bool,off?:bool}>
+ */
+ private static function valid_store_checks( $store_checks ): array {
+ $valid = array();
+ foreach ( is_array( $store_checks ) ? $store_checks : array() as $id => $check ) {
+ $set = is_string( $id ) && is_array( $check ) ? array_filter( array_intersect_key( $check, array_flip( array( 'required', 'off' ) ) ), 'is_bool' ) : array();
+ if ( array() !== $set ) {
+ $valid[ $id ] = $set;
+ }
+ }
+ return $valid;
+ }
+
/**
* Whether a check's channel map names at least one known channel, and every
* known channel has a string field, a valid effect and, when effect_from is
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ReportAbility.php b/plugins/woocommerce/src/Internal/AgentReadiness/ReportAbility.php
index a56929a1c13..9e2ba8f0af3 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ReportAbility.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ReportAbility.php
@@ -102,13 +102,17 @@ class ReportAbility implements AbilityDefinition {
'type' => 'integer',
'description' => __( 'Published simple and variable products checked.', 'woocommerce' ),
),
+ 'available' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Published products agents can see, including any past the check\'s limit.', 'woocommerce' ),
+ ),
'hidden_from_catalog' => array(
'type' => 'integer',
- 'description' => __( 'Products not checked because the merchant hid them from the shop catalog.', 'woocommerce' ),
+ 'description' => __( 'Products not checked because the merchant set them to Hidden.', 'woocommerce' ),
),
'unsupported_types' => array(
'type' => 'integer',
- 'description' => __( 'Products not checked because agents don\'t support their type yet.', 'woocommerce' ),
+ 'description' => __( 'Products not checked because agents can\'t buy their type through UCP yet.', 'woocommerce' ),
),
'store_checks' => array(
'type' => 'array',
@@ -150,6 +154,10 @@ class ReportAbility implements AbilityDefinition {
'type' => 'string',
'description' => __( 'On a likely conflict: the address where it was seen.', 'woocommerce' ),
),
+ 'source' => array(
+ 'type' => 'string',
+ 'description' => __( 'On a failed UCP version check: the version the store serves. On a failed UCP endpoint check: the status and content type catalog search answered with, such as 403 text/html. Otherwise empty.', 'woocommerce' ),
+ ),
),
),
),
@@ -182,6 +190,10 @@ class ReportAbility implements AbilityDefinition {
'description' => __( 'Up to 10 failing products, most recently modified first.', 'woocommerce' ),
'items' => array( 'type' => 'integer' ),
),
+ 'sales_share' => array(
+ 'type' => array( 'number', 'null' ),
+ 'description' => __( 'Share of the store\'s net sales, from 0 to 1, on the products that fail this check, over the period in sales. Null when Analytics is off or the period has fewer than 20 orders, too few to rank by.', 'woocommerce' ),
+ ),
'fix_url' => array( 'type' => 'string' ),
),
),
@@ -199,6 +211,15 @@ class ReportAbility implements AbilityDefinition {
),
),
'truncated' => array( 'type' => 'boolean' ),
+ 'sales' => array(
+ 'type' => array( 'object', 'null' ),
+ 'description' => __( 'The sales the shares compare: the last days, from Analytics, how many orders, and whether Analytics has imported the store\'s orders for that period. Null while Analytics is off.', 'woocommerce' ),
+ 'properties' => array(
+ 'days' => array( 'type' => 'integer' ),
+ 'orders' => array( 'type' => 'integer' ),
+ 'imported' => array( 'type' => 'boolean' ),
+ ),
+ ),
),
),
'scan_pending' => array(
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php b/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php
index bde66aa8ade..50f8f95b73f 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php
@@ -96,7 +96,7 @@ class RunCheckAbility implements AbilityDefinition {
}
$result = $readiness->check_product( $product );
if ( null === $result ) {
- return new \WP_Error( 'woocommerce_agent_readiness_product_not_checked', __( 'Only published simple and variable products shown in the shop catalog are checked.', 'woocommerce' ), array( 'status' => 400 ) );
+ return new \WP_Error( 'woocommerce_agent_readiness_product_not_checked', __( 'Only published simple and variable products not set to Hidden are checked.', 'woocommerce' ), array( 'status' => 400 ) );
}
$rules = $readiness->get_default_rules();
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php b/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
index f6519088a09..9aaf16956f7 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ScheduledScan.php
@@ -41,7 +41,7 @@ class ScheduledScan implements RegisterHooksInterface {
/**
* How long a daily scan marked running still counts as pending. A process killed mid-scan
* leaves it running until Action Scheduler's cleanup marks it failed (after 5 minutes, on a
- * queue run), so this frees Run check even when that cleanup does not run.
+ * queue run), so this frees Run checks even when that cleanup does not run.
*/
public const RUNNING_FOR = 10 * MINUTE_IN_SECONDS;
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php
index a3c5fb08a2a..d556c937259 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php
@@ -16,7 +16,8 @@ defined( 'ABSPATH' ) || exit;
*
* `ok` says whether the store is clear of the problem the label names, or is
* null when it couldn't be checked (StoreOutputChecks); `name` is the check
- * worded as its passing state.
+ * worded as its passing state. `group` is the merchant question the check
+ * answers on Sales readiness, as for the store output checks.
* `blocks` says what a failing condition stops: `listing` hides every product
* on every channel, `ucp` hides the catalog from agents that use UCP,
* `checkout` stops or weakens agent orders. A failing `required` condition
@@ -28,6 +29,13 @@ class StoreConditions {
public const LEVEL_REQUIRED = 'required';
+ /**
+ * Recommended conditions shown as Required, which don't keep AI shopping from being turned on:
+ * AI assistants read the catalog through the API whatever search engines are told, and with no
+ * payment method no sale goes through. The rules file's `store_checks` can change any of them (RemoteRules).
+ */
+ public const SHOWN_REQUIRED = array( 'search_visible', 'payment_method' );
+
public const LEVEL_RECOMMENDED = 'recommended';
/**
@@ -51,7 +59,7 @@ class StoreConditions {
/**
* Every condition with its current state.
*
- * @return array<int, array{id:string,ok:bool,blocks:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string}>
+ * @return array<int, array{id:string,ok:bool,blocks:string,group:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string}>
*/
public function all(): array {
$settings_url = static fn( string $tab ): string => admin_url( 'admin.php?page=wc-settings&tab=' . $tab );
@@ -59,19 +67,22 @@ class StoreConditions {
'id' => $id,
'ok' => self::is_policy_page( (int) get_option( $option ) ),
'blocks' => 'checkout',
+ 'group' => 'buy',
'level' => self::LEVEL_RECOMMENDED,
'name' => $name,
'label' => $label,
'why' => $why,
+ // The AI shopping section lands with #70590; until then the tab has one page.
'fix' => __( 'Choose a published page under WooCommerce > Settings > Agentic commerce.', 'woocommerce' ),
- 'fix_url' => $settings_url( AgenticCommerceSettings::TAB ) . '#' . $option,
+ 'fix_url' => AgenticCommerceSettings::url() . '#' . $option,
);
- return array(
+ $conditions = array(
array(
'id' => 'launched',
'ok' => $this->coming_soon_helper->is_site_live(),
'blocks' => 'listing',
+ 'group' => 'access',
'level' => self::LEVEL_REQUIRED,
'name' => __( 'Store is launched', 'woocommerce' ),
'label' => __( 'Store is in coming soon mode', 'woocommerce' ),
@@ -83,6 +94,7 @@ class StoreConditions {
'id' => 'search_visible',
'ok' => '0' !== (string) get_option( 'blog_public', '1' ),
'blocks' => 'listing',
+ 'group' => 'find',
'level' => self::LEVEL_RECOMMENDED,
'name' => __( 'Search engines can index the store', 'woocommerce' ),
'label' => __( 'Store is hidden from search engines', 'woocommerce' ),
@@ -94,17 +106,19 @@ class StoreConditions {
'id' => 'ucp_on',
'ok' => Utils::is_enabled(),
'blocks' => 'ucp',
+ 'group' => 'access',
'level' => self::LEVEL_RECOMMENDED,
'name' => __( 'Universal Commerce Protocol (UCP) is on', 'woocommerce' ),
'label' => __( 'Universal Commerce Protocol (UCP) is off', 'woocommerce' ),
'why' => __( 'Shopping agents that use UCP cannot read your catalog.', 'woocommerce' ),
- 'fix' => __( 'Turn on "Let AI agents shop your store" under WooCommerce > Settings > Agentic commerce.', 'woocommerce' ),
- 'fix_url' => $settings_url( AgenticCommerceSettings::TAB ),
+ 'fix' => __( 'Turn on "Allow AI assistants to shop your store" under WooCommerce > Settings > Agentic commerce.', 'woocommerce' ),
+ 'fix_url' => AgenticCommerceSettings::url(),
),
array(
'id' => 'https',
'ok' => wc_site_is_https(),
'blocks' => 'ucp',
+ 'group' => 'access',
'level' => self::LEVEL_REQUIRED,
'name' => __( 'Site uses HTTPS', 'woocommerce' ),
'label' => __( 'Site does not use HTTPS', 'woocommerce' ),
@@ -145,6 +159,7 @@ class StoreConditions {
'id' => 'payment_method',
'ok' => $this->payment_method_enabled(),
'blocks' => 'checkout',
+ 'group' => 'buy',
'level' => self::LEVEL_RECOMMENDED,
'name' => __( 'A payment method is turned on', 'woocommerce' ),
'label' => __( 'No payment method is turned on', 'woocommerce' ),
@@ -156,10 +171,11 @@ class StoreConditions {
'id' => 'guest_checkout',
'ok' => ! $this->registration_required(),
'blocks' => 'checkout',
+ 'group' => 'buy',
'level' => self::LEVEL_RECOMMENDED,
'name' => __( 'Guest checkout is allowed', 'woocommerce' ),
'label' => __( 'Guest checkout is off', 'woocommerce' ),
- 'why' => __( 'Shopping agents check out for shoppers without an account on your store, so they cannot place orders.', 'woocommerce' ),
+ 'why' => __( 'With guest checkout off, an AI assistant can check out only when the shopper creates an account at checkout. If account creation at checkout is off too, it can\'t. It can still find your products and build carts.', 'woocommerce' ),
'fix' => __( 'Tick "Enable guest checkout" under WooCommerce > Settings > Accounts & Privacy.', 'woocommerce' ),
'fix_url' => $settings_url( 'account' ),
),
@@ -167,6 +183,7 @@ class StoreConditions {
'id' => 'order_emails',
'ok' => $this->order_confirmation_email_enabled(),
'blocks' => 'checkout',
+ 'group' => 'buy',
'level' => self::LEVEL_RECOMMENDED,
'name' => __( 'Order confirmation emails are on', 'woocommerce' ),
'label' => __( 'Order confirmation emails are off', 'woocommerce' ),
@@ -175,19 +192,51 @@ class StoreConditions {
'fix_url' => $settings_url( 'email§ion=wc_email_customer_processing_order' ),
),
);
+ return array_values( array_filter( $conditions, static fn( array $condition ): bool => ! self::is_off( $condition['id'], $condition['level'] ) ) );
+ }
+
+ /**
+ * Whether a store check is shown as Required: a required one, or one the rules file marks
+ * `required`, else one in SHOWN_REQUIRED.
+ *
+ * @param array{id:string,level:string} $check Store condition or output check.
+ */
+ public static function shows_required( array $check ): bool {
+ if ( self::LEVEL_REQUIRED === $check['level'] ) {
+ return true;
+ }
+ return RemoteRules::store_check( $check['id'] )['required'] ?? in_array( $check['id'], self::SHOWN_REQUIRED, true );
+ }
+
+ /**
+ * Whether the rules file turns a store check off. A required one always runs.
+ *
+ * @param string $id Store condition or output check id.
+ * @param string $level Its level; output checks are recommended.
+ */
+ public static function is_off( string $id, string $level = self::LEVEL_RECOMMENDED ): bool {
+ return self::LEVEL_REQUIRED !== $level && true === ( RemoteRules::store_check( $id )['off'] ?? false );
+ }
+
+ /**
+ * Whether this WooCommerce has the UCP checkout routes.
+ */
+ public static function serves_ucp_checkout(): bool {
+ return defined( Utils::class . '::CAPABILITY_CHECKOUT' );
}
/**
* The UCP address condition, with the fix for why the address doesn't serve the profile.
*
* @param string $status A status from UcpDiscovery::serve_status().
- * @return array{id:string,ok:bool,blocks:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string}
+ * @return array{id:string,ok:bool,blocks:string,group:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string}
*/
private static function ucp_discovery( string $status ): array {
return array(
'id' => 'ucp_discovery',
'ok' => 'ok' === $status,
'blocks' => 'ucp',
+ 'group' => 'access',
'level' => self::LEVEL_REQUIRED,
'name' => __( 'Use a readable permalink structure', 'woocommerce' ),
// Without a file in the way, Plain permalinks are why the connection URL doesn't load.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
index bd420bb2ed6..f04207dfd80 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
@@ -55,7 +55,7 @@ class StoreOutputChecks {
* A likely conflict also names the address where it was seen. It doesn't name a plugin: any list of
* plugins goes stale, and several can change the same output.
*
- * @return array<int, array{id:string,ok:bool|null,blocks:string,group:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string,conflict:bool,pending:bool,seen_at:string}>
+ * @return array<int, array{id:string,ok:bool|null,blocks:string,group:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string,conflict:bool,pending:bool,seen_at:string,source:string}>
*/
public function all(): array {
return $this->all_for( $this->responses() );
@@ -67,14 +67,17 @@ class StoreOutputChecks {
* @since 11.4.0
*
* @param StoreResponses $responses Responses of the scan.
- * @return array<int, array{id:string,ok:bool|null,blocks:string,group:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string,conflict:bool,pending:bool,seen_at:string}>
+ * @return array<int, array{id:string,ok:bool|null,blocks:string,group:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string,conflict:bool,pending:bool,seen_at:string,source:string}>
*/
public function all_for( StoreResponses $responses ): array {
// The home page first: when it can't be reached, no other request is made.
$responses->home_page();
$results = array();
foreach ( $this->checks() as $check ) {
- $pending = in_array( $check['id'], self::PENDING, true );
+ if ( StoreConditions::is_off( $check['id'] ) ) {
+ continue;
+ }
+ $pending = in_array( $check['id'], self::PENDING, true ) || ( 'ucp_checkout' === $check['id'] && ! StoreConditions::serves_ucp_checkout() );
try {
$ok = $pending ? null : ( $check['test'] )( $responses );
} catch ( \Throwable $e ) {
@@ -85,7 +88,14 @@ class StoreOutputChecks {
array( 'source' => 'agent-readiness' )
);
}
- $conflict = false === $ok && ! empty( $check['conflict'] );
+ $conflict = false === $ok && ! empty( $check['conflict'] );
+ $source = '';
+ if ( 'ucp_profile_version' === $check['id'] && false === $ok ) {
+ $source = self::served_version( $responses );
+ }
+ if ( 'ucp_endpoints_live' === $check['id'] && false === $ok ) {
+ $source = self::search_seen( $responses );
+ }
$results[] = array(
'id' => $check['id'],
'ok' => $ok,
@@ -100,6 +110,7 @@ class StoreOutputChecks {
'conflict' => $conflict,
'pending' => $pending,
'seen_at' => $conflict ? self::seen_at( (string) ( $check['seen_at'] ?? '' ), $responses ) : '',
+ 'source' => $source,
);
}
return $results;
@@ -108,14 +119,12 @@ class StoreOutputChecks {
/**
* Checks for output WooCommerce doesn't build yet. They don't run and are reported as
* pending, not failed; remove the entry when the output ships. The output is built by
- * WOOPRD-3912 (returns policy), WOOPRD-3908 (shipping), WOOPRD-3918 (buy action) and
- * WOOAI-1435 (UCP checkout).
+ * WOOPRD-3908 (shipping) and WOOPRD-3918 (buy action). The UCP checkout check is pending
+ * until this WooCommerce serves UCP checkout (StoreConditions::serves_ucp_checkout()).
*/
private const PENDING = array(
- 'product_return_policy_schema',
'product_shipping_schema',
'product_buy_action_schema',
- 'ucp_checkout',
);
private const MAX_LISTED_SITEMAPS = 5;
@@ -314,7 +323,7 @@ class StoreOutputChecks {
'group' => 'access',
'test' => fn( StoreResponses $responses ): ?bool => $this->pages_public( $responses ),
'blocks' => 'listing',
- 'name' => __( 'Store pages open without signing in', 'woocommerce' ),
+ 'name' => __( 'Store pages open without logging in', 'woocommerce' ),
'label' => __( 'Store pages ask visitors to sign in', 'woocommerce' ),
'why' => __( 'Agents don\'t sign in, so they can\'t read your home, shop or product pages.', 'woocommerce' ),
'fix' => __( 'Check the membership, private store or maintenance plugin that asks visitors to sign in.', 'woocommerce' ),
@@ -403,7 +412,7 @@ class StoreOutputChecks {
'id' => 'product_gtin_jsonld',
'group' => 'understand',
'test' => fn( StoreResponses $responses ): ?bool => $this->with_products( $responses, static fn( array $products ): ?bool => array() === $products ? null : self::served_gtin_ok( $products, $responses->product() ) ),
- 'blocks' => 'listing',
+ 'blocks' => 'discovery',
'name' => __( 'Product structured data has a valid GTIN', 'woocommerce' ),
'label' => __( 'Product structured data has no valid GTIN', 'woocommerce' ),
'why' => __( 'Agents match products by GTIN, and the product page gives none or an invalid one.', 'woocommerce' ),
@@ -416,10 +425,10 @@ class StoreOutputChecks {
'id' => 'product_brand_jsonld',
'group' => 'understand',
'test' => fn( StoreResponses $responses ): ?bool => $this->with_products( $responses, static fn( array $products ): ?bool => array() === $products ? null : self::served_brand_ok( $products, $responses->product() ) ),
- 'blocks' => 'listing',
+ 'blocks' => 'discovery',
'name' => __( 'Product structured data has a brand', 'woocommerce' ),
'label' => __( 'Product structured data has no brand', 'woocommerce' ),
- 'why' => __( 'ChatGPT needs a brand to list a product. Your product has one, but the page gives agents none.', 'woocommerce' ),
+ 'why' => __( 'Agents use the brand to match and compare products. Your product has one, but the page gives agents none.', 'woocommerce' ),
'fix' => __( 'WooCommerce adds the product\'s brand. Usually an SEO plugin or your theme replaces it: check its schema settings.', 'woocommerce' ),
'fix_url' => '',
'conflict' => true,
@@ -450,8 +459,8 @@ class StoreOutputChecks {
array(
'id' => 'product_return_policy_schema',
'group' => 'buy',
- 'test' => fn( StoreResponses $responses ): ?bool => $this->with_products( $responses, static fn( array $products ): bool => self::offer_has( $products, 'hasMerchantReturnPolicy' ) ),
- 'blocks' => 'listing',
+ 'test' => fn( StoreResponses $responses ): ?bool => $this->with_products( $responses, static fn( array $products ): ?bool => array() === $products ? null : self::offer_has( $products, 'hasMerchantReturnPolicy' ) || self::store_has_return_policy( $responses ) ),
+ 'blocks' => 'checkout',
'name' => __( 'Product structured data links your returns policy', 'woocommerce' ),
'label' => __( 'Product structured data has no returns policy', 'woocommerce' ),
'why' => __( 'Agents tell shoppers whether they can return an item before they buy, and read it from the product\'s structured data.', 'woocommerce' ),
@@ -462,10 +471,10 @@ class StoreOutputChecks {
'id' => 'product_shipping_schema',
'group' => 'buy',
'test' => fn( StoreResponses $responses ): ?bool => $this->with_products( $responses, static fn( array $products ): ?bool => self::ships( $responses ) ? self::offer_has( $products, 'shippingDetails' ) : null ),
- 'blocks' => 'listing',
+ 'blocks' => 'checkout',
'name' => __( 'Product structured data gives shipping details', 'woocommerce' ),
'label' => __( 'Product structured data has no shipping details', 'woocommerce' ),
- 'why' => __( 'Agents compare delivery options, and leave out products whose shipping they can\'t tell.', 'woocommerce' ),
+ 'why' => __( 'Agents tell shoppers the delivery options and cost before they buy.', 'woocommerce' ),
'fix' => __( 'Set up shipping zones so WooCommerce can add shipping details to your products.', 'woocommerce' ),
'fix_url' => admin_url( 'admin.php?page=wc-settings&tab=shipping' ),
),
@@ -473,7 +482,7 @@ class StoreOutputChecks {
'id' => 'product_buy_action_schema',
'group' => 'buy',
'test' => fn( StoreResponses $responses ): ?bool => $this->with_products( $responses, static fn( array $products ): ?bool => self::has_buy_action( $products, $responses->product() ) ),
- 'blocks' => 'listing',
+ 'blocks' => 'checkout',
'name' => __( 'Product structured data says how to buy', 'woocommerce' ),
'label' => __( 'Product structured data has no buy action', 'woocommerce' ),
'why' => __( 'A BuyAction tells agents where to send a shopper to buy the product.', 'woocommerce' ),
@@ -1008,6 +1017,17 @@ class StoreOutputChecks {
return is_array( $profile ) && is_array( $profile['ucp'] ?? null ) ? $profile : null;
}
+ /**
+ * The UCP version the served profile declares when it is older than WooCommerce's, or '' when it
+ * isn't a date like 2026-04-08 or isn't older, so the message never calls a newer version older.
+ *
+ * @param StoreResponses $responses Store responses.
+ */
+ private static function served_version( StoreResponses $responses ): string {
+ $version = self::served_profile( $responses )['ucp']['version'] ?? '';
+ return is_string( $version ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $version ) && strcmp( $version, UcpUtils::VERSION ) < 0 ? $version : '';
+ }
+
/**
* Whether the served profile declares the UCP version WooCommerce implements. Null when no
* profile is served, which the ucp_profile check reports.
@@ -1037,11 +1057,29 @@ class StoreOutputChecks {
* @param string $property Offer property.
*/
private static function offer_has( array $products, string $property ): bool {
- foreach ( self::with_variants( $products ) as $product ) {
- foreach ( self::as_list( $product['offers'] ?? null ) as $offer ) {
- if ( ! empty( $offer[ $property ] ) ) {
- return true;
- }
+ foreach ( self::offers( $products ) as $offer ) {
+ if ( ! empty( $offer[ $property ] ) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Whether the product page names a returns policy for the whole store: WooCommerce adds it to an
+ * OnlineStore item there once a refund and returns page is chosen, and SEO plugins may add it to
+ * their Organization item.
+ *
+ * @param StoreResponses $responses Store responses.
+ */
+ private static function store_has_return_policy( StoreResponses $responses ): bool {
+ $page = $responses->product_page();
+ if ( null === $page ) {
+ return false;
+ }
+ foreach ( JsonLd::items( $page['body'], ...self::ORGANIZATION_TYPES ) as $store ) {
+ if ( ! empty( $store['hasMerchantReturnPolicy'] ) ) {
+ return true;
}
}
return false;
@@ -1197,8 +1235,42 @@ class StoreOutputChecks {
* @param StoreResponses $responses Store responses.
*/
private static function ucp_endpoint_answers( StoreResponses $responses ): ?bool {
- $endpoint = untrailingslashit( self::ucp_endpoint( $responses ) ?? rest_url( 'wc/ucp/v1' ) );
- $response = $responses->post_json( $endpoint . '/catalog/search', array() );
+ $url = self::catalog_search_url( $responses );
+ $answer = self::endpoint_answer( $responses->post_json( $url, array() ) );
+ // Asked once more before it fails, so one slow or briefly refused request doesn't mark AI shopping as broken.
+ return true === $answer ? true : self::endpoint_answer( $responses->post_json_again( $url, array() ) );
+ }
+
+ /**
+ * Catalog search on the endpoint the served profile names, or WooCommerce's when it isn't served.
+ *
+ * @param StoreResponses $responses Store responses.
+ */
+ private static function catalog_search_url( StoreResponses $responses ): string {
+ return untrailingslashit( self::ucp_endpoint( $responses ) ?? rest_url( 'wc/ucp/v1' ) ) . '/catalog/search';
+ }
+
+ /**
+ * The status and content type of the last answer from catalog search, such as `403 text/html`,
+ * so a failed check says what was in the way. Empty when the store didn't answer.
+ *
+ * @param StoreResponses $responses Store responses.
+ */
+ private static function search_seen( StoreResponses $responses ): string {
+ $response = $responses->post_json( self::catalog_search_url( $responses ), array() );
+ if ( null === $response ) {
+ return '';
+ }
+ $type = strtolower( trim( explode( ';', $response['headers']['content-type'] ?? '' )[0] ) );
+ return trim( $response['status'] . ' ' . sanitize_text_field( $type ) );
+ }
+
+ /**
+ * Whether one answer from catalog search is its JSON, or null when the store didn't answer.
+ *
+ * @param array{status:int,body:string,headers:array<string,string>,truncated:bool}|null $response Response.
+ */
+ private static function endpoint_answer( ?array $response ): ?bool {
if ( null === $response || $response['status'] >= 500 ) {
return null;
}
@@ -1869,7 +1941,8 @@ class StoreOutputChecks {
$product = null;
foreach ( $ids as $id ) {
$candidate = wc_get_product( (int) $id );
- if ( $candidate instanceof \WC_Product && $candidate->is_visible() ) {
+ // A product the scan checks, "Search results only" included.
+ if ( $candidate instanceof \WC_Product && ProductScan::covers( $candidate ) ) {
$product = $candidate;
break;
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php
index 59e2e3f478b..79a03c6fb20 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreResponses.php
@@ -3,7 +3,6 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\AgentReadiness;
-use Automattic\WooCommerce\Enums\CatalogVisibility;
use Automattic\WooCommerce\Enums\ProductStatus;
defined( 'ABSPATH' ) || exit;
@@ -146,7 +145,7 @@ class StoreResponses {
*/
public function post_json( string $url, array $body ): ?array {
$url = self::absolute( $url );
- $key = 'POST ' . $url;
+ $key = self::post_key( $url, $body );
if ( ! array_key_exists( $key, $this->responses ) ) {
$this->responses[ $key ] = $this->site_live && $this->is_store_url( $url ) ? $this->request(
$url,
@@ -160,6 +159,28 @@ class StoreResponses {
return $this->responses[ $key ];
}
+ /**
+ * The response to a POST of a JSON object, sent again instead of read from this scan's earlier answer.
+ *
+ * @param string $url URL or path.
+ * @param array<string, mixed> $body JSON object.
+ * @return array{status:int,body:string,headers:array<string,string>,truncated:bool}|null Null when the store could not be reached.
+ */
+ public function post_json_again( string $url, array $body ): ?array {
+ unset( $this->responses[ self::post_key( self::absolute( $url ), $body ) ] );
+ return $this->post_json( $url, $body );
+ }
+
+ /**
+ * The key this scan keeps a POST's answer under: one per URL and body.
+ *
+ * @param string $url Absolute URL.
+ * @param array<string, mixed> $body JSON object.
+ */
+ private static function post_key( string $url, array $body ): string {
+ return 'POST ' . $url . ' ' . wp_json_encode( (object) $body );
+ }
+
/**
* The shop page, or null when there is none or it didn't answer 200.
*
@@ -201,7 +222,7 @@ class StoreResponses {
}
/**
- * The newest published product of a type the report checks that is in the shop catalog, or null when there is none.
+ * The newest product the scan checks (ProductScan::count_query()), or null when there is none.
* Password protected products are left out, since their page shows a form instead of the product. A product with
* a price comes first, so one unfinished product doesn't decide a check for the whole store; only the five newest
* of the others are looked at.
@@ -209,18 +230,19 @@ class StoreResponses {
public function product(): ?\WC_Product {
if ( null === $this->product ) {
$this->product = false;
- $products = wc_get_products(
+ $ids = get_posts(
array(
- 'status' => ProductStatus::PUBLISH,
- 'visibility' => CatalogVisibility::CATALOG,
- 'type' => ProductScan::SUPPORTED_TYPES,
- 'has_password' => false,
- 'limit' => 5,
- 'orderby' => 'date',
- 'order' => 'DESC',
+ 'post_type' => 'product',
+ 'post_status' => ProductStatus::PUBLISH,
+ 'has_password' => false,
+ 'tax_query' => ProductScan::count_query( ProductScan::COUNT_AVAILABLE ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Five rows, once per background scan.
+ 'posts_per_page' => 5,
+ 'fields' => 'ids',
+ 'orderby' => 'date',
+ 'order' => 'DESC',
)
);
- foreach ( is_array( $products ) ? $products : array() as $product ) {
+ foreach ( array_map( 'wc_get_product', $ids ) as $product ) {
if ( ! $product instanceof \WC_Product ) {
continue;
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/rules.json b/plugins/woocommerce/src/Internal/AgentReadiness/rules.json
index 3b255c0c6e2..0390b54a803 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/rules.json
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/rules.json
@@ -1,5 +1,9 @@
{
- "version": "1",
+ "version": "2026-11-17",
+ "store_checks": {
+ "search_visible": { "required": true },
+ "payment_method": { "required": true }
+ },
"checks": {
"missing_regular_price": {
"channels": {
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php
index 522f96af5dc..d2c8730c388 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php
@@ -33,12 +33,14 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
parent::setUp();
// Report tests stay offline: store output checks would load the test site's pages.
StoreOutputChecksTest::block_requests();
+ // Orders other tests left in the Analytics tables would count toward the sales share.
+ \WC_Helper_Reports::reset_stats_dbs();
$store_conditions = new StoreConditions();
$store_conditions->init( new ComingSoonHelper() );
$output_checks = new StoreOutputChecks();
$output_checks->init( new ComingSoonHelper() );
$this->sut = new AgentReadiness();
- $this->sut->init( $store_conditions, $output_checks, new RemoteRules(), wc_get_container()->get( \Automattic\WooCommerce\Internal\AgentReadiness\DeclaredToAgents::class ) );
+ $this->sut->init( $store_conditions, $output_checks, new RemoteRules(), wc_get_container()->get( \Automattic\WooCommerce\Internal\AgentReadiness\DeclaredToAgents::class ), new \Automattic\WooCommerce\Internal\AgentReadiness\ProductSales() );
}
/**
@@ -75,7 +77,7 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
$output_checks->init( new ComingSoonHelper() );
$store_conditions = new StoreConditions();
$store_conditions->init( new ComingSoonHelper() );
- $this->sut->init( $store_conditions, $output_checks, new RemoteRules(), wc_get_container()->get( \Automattic\WooCommerce\Internal\AgentReadiness\DeclaredToAgents::class ) );
+ $this->sut->init( $store_conditions, $output_checks, new RemoteRules(), wc_get_container()->get( \Automattic\WooCommerce\Internal\AgentReadiness\DeclaredToAgents::class ), new \Automattic\WooCommerce\Internal\AgentReadiness\ProductSales() );
add_filter( 'pre_http_request', static fn() => new \WP_Error( 'http_request_failed', 'Timed out' ) );
$checks = array_column( $this->sut->get_report()['store_checks'], null, 'id' );
@@ -97,9 +99,9 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
$report = $this->sut->get_report();
- $this->assertSame( array( 'generated_at', 'products', 'hidden_from_catalog', 'unsupported_types', 'store_checks', 'declared', 'channels', 'checks', 'truncated' ), array_keys( $report ) );
+ $this->assertSame( array( 'generated_at', 'products', 'available', 'hidden_from_catalog', 'unsupported_types', 'store_checks', 'declared', 'channels', 'checks', 'truncated', 'sales' ), array_keys( $report ) );
$this->assertFalse( $report['truncated'] );
- $this->assertSame( array( 'id', 'ok', 'blocks', 'level', 'name', 'label', 'why', 'fix', 'fix_url' ), array_keys( $report['store_checks'][0] ) );
+ $this->assertSame( array( 'id', 'ok', 'blocks', 'group', 'level', 'name', 'label', 'why', 'fix', 'fix_url' ), array_keys( $report['store_checks'][0] ) );
$this->assertSame( array( 'chatgpt', 'google', 'copilot' ), array_keys( $report['channels'] ) );
$this->assertSame(
array( 'name', 'spec', 'url', 'listable', 'not_listable', 'with_gaps', 'complete' ),
@@ -108,7 +110,7 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
$checks = array_column( $report['checks'], null, 'id' );
$this->assertSame(
- array( 'id', 'label', 'why', 'fix', 'channels', 'count', 'product_ids', 'fix_url' ),
+ array( 'id', 'label', 'why', 'fix', 'channels', 'count', 'product_ids', 'sales_share', 'fix_url' ),
array_keys( $checks['missing_brand'] )
);
$this->assertSame( 1, $checks['missing_brand']['count'] );
@@ -242,6 +244,92 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
$this->assertNotContains( 'missing_brand', $this->sut->get_failing_check_ids( $product ) );
}
+ /**
+ * @testdox A share is kept between 0 and 1 and rounded to 4 places, and any sales at all keep at least 0.01%.
+ */
+ public function test_share_rounding(): void {
+ $share = new \ReflectionMethod( AgentReadiness::class, 'share' );
+ $share->setAccessible( true );
+
+ $this->assertSame( 0.0001, $share->invoke( null, 90 / 2000000 ), 'Small sales are not "No sales"' );
+ $this->assertSame( 0.0, $share->invoke( null, 0.0 ) );
+ $this->assertSame( 0.0, $share->invoke( null, -0.2 ), 'Refunds in the period can make a product\'s sales negative' );
+ $this->assertSame( 1.0, $share->invoke( null, 1.3 ), 'Other products\' refunds can make one product\'s share exceed 1' );
+ $this->assertSame( 0.1235, $share->invoke( null, 0.123456 ) );
+ }
+
+ /**
+ * @testdox Each check carries the share of the last 90 days' sales on its failing products, from Analytics, once there are enough orders to rank by.
+ */
+ public function test_report_sales_share(): void {
+ update_option( 'woocommerce_analytics_enabled', 'yes' );
+ if ( ! taxonomy_exists( 'product_brand' ) ) {
+ register_taxonomy( 'product_brand', 'product' );
+ }
+ $branded = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ $unbranded = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 30 ) );
+ wp_set_object_terms( $branded->get_id(), 'Acme', 'product_brand' );
+ $place_order = function () use ( $branded, $unbranded ): void {
+ $order = wc_create_order();
+ $order->add_product( $branded, 1 );
+ $order->add_product( $unbranded, 1 );
+ $order->set_status( 'completed' );
+ $order->calculate_totals();
+ $order->save();
+ \Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore::sync_order( $order->get_id() );
+ \Automattic\WooCommerce\Admin\API\Reports\Products\DataStore::sync_order_products( $order->get_id() );
+ };
+ for ( $i = 1; $i < \Automattic\WooCommerce\Internal\AgentReadiness\ProductSales::MIN_ORDERS; $i++ ) {
+ $place_order();
+ }
+
+ $report = $this->sut->get_report();
+ $this->assertNull( array_column( $report['checks'], null, 'id' )['missing_brand']['sales_share'], 'Too few orders to rank by' );
+ $this->assertSame( 19, $report['sales']['orders'] );
+
+ $place_order();
+ $report = $this->sut->get_report();
+ $checks = array_column( $report['checks'], null, 'id' );
+
+ $this->assertSame( 1, $checks['missing_brand']['count'] );
+ $this->assertEqualsWithDelta( 0.75, $checks['missing_brand']['sales_share'], 0.0001, '30 of 40 in sales has no brand' );
+ $this->assertSame( 90, $report['sales']['days'] );
+ $this->assertSame( 20, $report['sales']['orders'] );
+ }
+
+ /**
+ * @testdox A check a variable product fails through some variations counts only their sales; a check on the whole product counts all of it.
+ */
+ public function test_report_sales_share_of_failing_variations(): void {
+ update_option( 'woocommerce_analytics_enabled', 'yes' );
+ $variable = WC_Helper_Product::create_variation_product();
+ $children = array_map( 'wc_get_product', $variable->get_children() );
+ $image_id = self::factory()->attachment->create_object( 'mug.jpg', 0, array( 'post_mime_type' => 'image/jpeg' ) );
+ foreach ( array_slice( $children, 1 ) as $child ) {
+ $child->set_image_id( $image_id );
+ $child->save();
+ }
+ for ( $i = 0; $i < \Automattic\WooCommerce\Internal\AgentReadiness\ProductSales::MIN_ORDERS; $i++ ) {
+ $order = wc_create_order();
+ $order->add_product( $children[0], 1 );
+ $order->add_product( $children[1], 1 );
+ $order->set_status( 'completed' );
+ $order->calculate_totals();
+ $order->save();
+ \Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore::sync_order( $order->get_id() );
+ \Automattic\WooCommerce\Admin\API\Reports\Products\DataStore::sync_order_products( $order->get_id() );
+ }
+ $first = (float) $children[0]->get_price();
+ $second = (float) $children[1]->get_price();
+ $this->assertGreaterThan( 0.0, $first * $second, 'Both variations have a price' );
+
+ $checks = array_column( $this->sut->get_report()['checks'], null, 'id' );
+
+ $this->assertSame( 1, $checks['missing_variation_images']['count'] );
+ $this->assertEqualsWithDelta( round( $first / ( $first + $second ), 4 ), $checks['missing_variation_images']['sales_share'], 0.0001, 'Only the variation without an image' );
+ $this->assertSame( 1.0, $checks['missing_brand']['sales_share'], 'A brand is the whole product\'s' );
+ }
+
/**
* @testdox check_product judges a variation by its parent and returns null for products the scan leaves out.
*/
@@ -318,7 +406,7 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
}
/**
- * @testdox Products hidden from the shop catalog and unsupported types are counted, not checked.
+ * @testdox Hidden products and unsupported types are counted, not checked; search-only and shop-only products are checked.
*/
public function test_scan_counts_hidden_and_unsupported_products(): void {
WC_Helper_Product::create_simple_product();
@@ -341,10 +429,13 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
$report = $this->sut->get_report();
- $this->assertSame( 2, $report['products'], 'Only the shown simple product and the shop-only one are checked' );
- $this->assertSame( 2, $report['hidden_from_catalog'], 'Hidden and search-only products are counted apart' );
+ $this->assertSame( 3, $report['products'], 'The shown simple product, the search-only one and the shop-only one are checked: agents can open all three' );
+ $this->assertSame( 1, $report['hidden_from_catalog'], 'Only the Hidden product is counted apart' );
+ $this->assertSame( 3, $report['available'], 'The catalog agents can see: the same products as checked when under the limit' );
$this->assertSame( 2, $report['unsupported_types'], 'External and the subscription are counted apart' );
- $this->assertSame( 2, $report['channels']['chatgpt']['listable'] + $report['channels']['chatgpt']['not_listable'] );
+ $this->assertSame( 3, $report['channels']['chatgpt']['listable'] + $report['channels']['chatgpt']['not_listable'] );
+ $this->assertTrue( ProductScan::covers( $search_only ) );
+ $this->assertFalse( ProductScan::covers( $hidden_variable ) );
$this->assertNotContains( 'hidden_from_catalog', array_column( $report['checks'], 'id' ) );
$this->assertSame( array(), $this->sut->get_failing_check_ids( $hidden_variable ), 'A hidden product has no issues' );
$this->assertSame( array(), $this->sut->get_failing_check_ids( wc_get_product( $hidden_variable->get_children()[0] ) ), 'Nor do its variations' );
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
index 8391190ae57..fc81c6d81b0 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
@@ -138,13 +138,75 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
$this->assertSame( 'AI agents can now find and shop your store.', $on_message->invoke( null, 0 ) );
}
+ /**
+ * @testdox Status groups by shows_required(), so a recommended-level check the rules mark Required lands in Required.
+ */
+ public function test_status_groups_by_shows_required(): void {
+ $render = new \ReflectionMethod( AgenticCommerceSettingsPage::class, 'render_status' );
+ $render->setAccessible( true );
+ ob_start();
+ $render->invoke(
+ $this->page(),
+ array(
+ array(
+ 'id' => 'search_visible',
+ 'level' => 'recommended',
+ 'ok' => false,
+ 'name' => 'Products can be found in search',
+ 'label' => 'Search',
+ 'fix_url' => '#search',
+ 'fix' => 'Fix search',
+ ),
+ array(
+ 'id' => 'canonical_url',
+ 'level' => 'recommended',
+ 'ok' => false,
+ 'name' => 'Pages name their canonical URL',
+ 'label' => 'Canonical',
+ 'fix_url' => '#canonical',
+ 'fix' => 'Fix canonical',
+ ),
+ ),
+ \Automattic\WooCommerce\Internal\AgentReadiness\UcpSwitch::STATUS_OFF
+ );
+ $html = (string) ob_get_clean();
+
+ $this->assertStringContainsString( 'wc-agentic-commerce-group--required', $html );
+ $this->assertStringContainsString( '1 required step to finish so agents can shop your store.', $html, 'The summary counts a Required row even when it does not block the switch' );
+ $this->assertStringNotContainsString( 'Everything agents need is set up.', $html );
+ $this->assertStringContainsString( 'Let search engines index your store', $html, 'search_visible shows as Required via shows_required()' );
+ $this->assertMatchesRegularExpression(
+ '/wc-agentic-commerce-group--required[\s\S]*Let search engines index your store[\s\S]*wc-agentic-commerce-group--recommended[\s\S]*Canonical/s',
+ $html
+ );
+ }
+
+ /**
+ * Render the page with one payment gateway turned on, since a payment method is Required.
+ *
+ * @return string
+ */
+ private function render_with_a_payment_method(): string {
+ $gateways = WC()->payment_gateways()->payment_gateways();
+ $this->assertNotEmpty( $gateways, 'Core registers its gateways' );
+ $gateway = reset( $gateways );
+ $enabled = $gateway->enabled;
+
+ $gateway->enabled = 'yes';
+ try {
+ return $this->render_page();
+ } finally {
+ $gateway->enabled = $enabled;
+ }
+ }
+
/**
* @testdox With every required check passing, open checks are only Recommended and passing ones are Done.
*/
public function test_output_on_a_ready_store(): void {
StoreConditionsTest::make_store_ready();
- $html = $this->render_page();
+ $html = $this->render_with_a_payment_method();
$this->assertStringContainsString( 'Everything agents need is set up.', $html );
$this->assertStringNotContainsString( 'wc-agentic-commerce-check--required', $html );
@@ -160,7 +222,7 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
StoreConditionsTest::make_store_ready();
delete_option( AgenticCommerceSettings::PRIVACY_PAGE_OPTION );
- $html = $this->render_page();
+ $html = $this->render_with_a_payment_method();
$this->assertStringNotContainsString( 'wc-agentic-commerce-check--required', $html );
$this->assertMatchesRegularExpression( '/wc-agentic-commerce-group--recommended.*Choose a privacy policy page/s', $html );
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/DeclaredToAgentsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/DeclaredToAgentsTest.php
index 7edbf82aeda..675b0f5c96b 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/DeclaredToAgentsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/DeclaredToAgentsTest.php
@@ -430,14 +430,13 @@ class DeclaredToAgentsTest extends WC_Unit_Test_Case {
}
/**
- * @testdox DNS-AID and an automated product feed are listed as not checked yet.
+ * @testdox Only items the scan reads are listed: DNS-AID and an automated product feed would always be not checked.
*/
- public function test_not_read_yet(): void {
+ public function test_lists_only_what_the_scan_reads(): void {
$results = $this->results( array() );
- $this->assertArrayHasKey( 'dns-aid', $results );
- $this->assertNull( $results['dns-aid'] );
- $this->assertNull( $results['product-feed-automation'] );
+ $this->assertArrayNotHasKey( 'dns-aid', $results );
+ $this->assertArrayNotHasKey( 'product-feed-automation', $results );
}
/**
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
index 05f66fdcc80..8af09cdeff5 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductFailuresTest.php
@@ -27,6 +27,8 @@ class ProductFailuresTest extends WC_Unit_Test_Case {
public function setUp(): void {
parent::setUp();
StoreOutputChecksTest::block_requests();
+ // Orders other tests left in the Analytics tables would count toward the sales share.
+ \WC_Helper_Reports::reset_stats_dbs();
$this->readiness = wc_get_container()->get( AgentReadiness::class );
}
@@ -153,6 +155,73 @@ class ProductFailuresTest extends WC_Unit_Test_Case {
$this->assertSame( 1, ProductFailures::counts()[ ProductFailures::CHECKED ] ?? 0, 'Back on the first site' );
}
+ /**
+ * @testdox A check's share of sales is dropped once its count changes after the scan, since it was measured on the products failing then.
+ */
+ public function test_sales_share_dropped_when_count_changes(): void {
+ update_option( 'woocommerce_analytics_enabled', 'yes' );
+ $product = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ for ( $i = 0; $i < \Automattic\WooCommerce\Internal\AgentReadiness\ProductSales::MIN_ORDERS; $i++ ) {
+ $order = wc_create_order();
+ $order->add_product( $product, 1 );
+ $order->set_status( 'completed' );
+ $order->calculate_totals();
+ $order->save();
+ \Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore::sync_order( $order->get_id() );
+ \Automattic\WooCommerce\Admin\API\Reports\Products\DataStore::sync_order_products( $order->get_id() );
+ }
+ $share = fn(): ?float => array_column( (array) $this->readiness->get_cached_report()['checks'], 'sales_share', 'id' )['missing_images'];
+
+ $this->readiness->refresh_report();
+ $this->assertSame( 1.0, $share() );
+
+ ProductFailures::store( $product->get_id(), array() );
+ $this->assertNull( $share() );
+ $this->assertSame( 1.0, array_column( (array) $this->readiness->get_cached_report()['checks'], 'ranked_share', 'id' )['missing_images'], 'Fix first still ranks by the share from the check' );
+ }
+
+ /**
+ * @testdox A check's share of sales is also dropped when the example products change while the count stays the same.
+ */
+ public function test_sales_share_dropped_when_example_membership_changes(): void {
+ $kept = WC_Helper_Product::create_simple_product();
+ $fixed = WC_Helper_Product::create_simple_product();
+ $added = WC_Helper_Product::create_simple_product();
+ $fail = array(
+ 'missing_images' => array(
+ 'chatgpt' => array(
+ 'field' => 'image',
+ 'effect' => 'gaps',
+ ),
+ ),
+ );
+ ProductFailures::store( $kept->get_id(), $fail );
+ ProductFailures::store( $fixed->get_id(), array() );
+ ProductFailures::store( $added->get_id(), $fail );
+ update_option(
+ AgentReadiness::REPORT_OPTION,
+ array(
+ 'failures_stored' => true,
+ 'products' => 3,
+ 'channels' => array(),
+ 'checks' => array(
+ array(
+ 'id' => 'missing_images',
+ 'count' => 2,
+ 'product_ids' => array( $kept->get_id(), $fixed->get_id() ),
+ 'sales_share' => 0.5,
+ ),
+ ),
+ )
+ );
+
+ $check = array_column( (array) $this->readiness->get_cached_report()['checks'], null, 'id' )['missing_images'];
+ $this->assertSame( 2, $check['count'], 'Count still two failing products' );
+ $this->assertNull( $check['sales_share'], 'Share cleared: examples no longer match the scan' );
+ $this->assertSame( 0.5, $check['ranked_share'] );
+ $this->assertSame( array( $kept->get_id() ), $check['product_ids'], 'Only examples that still fail remain' );
+ }
+
/**
* @testdox Every checked product has a checked row, passing or not, which for_product leaves out and the product total counts.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductSalesTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductSalesTest.php
new file mode 100644
index 00000000000..3f6c07b3421
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductSalesTest.php
@@ -0,0 +1,220 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;
+
+use Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore as OrdersStatsDataStore;
+use Automattic\WooCommerce\Admin\API\Reports\Products\DataStore as ProductsDataStore;
+use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\Internal\AgentReadiness\ProductSales;
+use WC_Helper_Product;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for the ProductSales class.
+ */
+class ProductSalesTest extends WC_Unit_Test_Case {
+
+ /**
+ * The System Under Test.
+ *
+ * @var ProductSales
+ */
+ private $sut;
+
+ /**
+ * Set up test fixtures.
+ */
+ public function setUp(): void {
+ parent::setUp();
+ // Orders other tests left in the Analytics tables would count too.
+ \WC_Helper_Reports::reset_stats_dbs();
+ update_option( 'woocommerce_analytics_enabled', 'yes' );
+ $this->sut = new ProductSales();
+ }
+
+ /**
+ * @testdox Sales add up per product over the last 90 days, a variation counting toward its parent, leaving out statuses Analytics excludes and older orders.
+ */
+ public function test_last_days_sums_sales_per_product(): void {
+ $mug = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ $vase = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 30 ) );
+ $variable = WC_Helper_Product::create_variation_product();
+ $children = $variable->get_children();
+ $variant = wc_get_product( $children[0] );
+
+ $this->order( array( array( $mug, 2 ), array( $variant, 1 ) ), OrderStatus::COMPLETED );
+ $this->order( array( array( $vase, 1 ) ), OrderStatus::CANCELLED );
+ $this->order( array( array( $vase, 1 ) ), OrderStatus::PROCESSING, time() - 120 * DAY_IN_SECONDS );
+
+ $sales = $this->sut->last_days();
+
+ $this->assertIsArray( $sales );
+ $this->assertSame( 90, $sales['days'] );
+ $this->assertSame( 1, $sales['orders'], 'Only the completed order in the period counts' );
+ $this->assertEqualsWithDelta( 20.0, $sales['by_product'][ $mug->get_id() ] ?? 0.0, 0.01 );
+ $this->assertGreaterThan( 0.0, (float) $variant->get_price(), 'The variation has a price, so its sales show' );
+ $this->assertArrayHasKey( $variable->get_id(), $sales['by_product'], 'A variation counts toward its parent' );
+ $this->assertEqualsWithDelta( (float) $variant->get_price(), $sales['by_product'][ $variable->get_id() ], 0.01 );
+ $this->assertArrayNotHasKey( $variant->get_id(), $sales['by_product'] );
+ $this->assertEqualsWithDelta( (float) $variant->get_price(), $sales['by_variation'][ $variant->get_id() ] ?? 0.0, 0.01, 'The variation\'s own sales are kept too' );
+ $this->assertArrayNotHasKey( $mug->get_id(), $sales['by_variation'] );
+ $this->assertArrayNotHasKey( $vase->get_id(), $sales['by_product'], 'Cancelled and older orders are left out' );
+ $this->assertEqualsWithDelta( 20.0 + (float) $variant->get_price(), $sales['total'], 0.01 );
+ }
+
+ /**
+ * @testdox A refund takes its amount off the product's sales, as Analytics nets it, and doesn't count as another order.
+ */
+ public function test_last_days_nets_refunds(): void {
+ $mug = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ $order = $this->order( array( array( $mug, 2 ) ), OrderStatus::COMPLETED );
+ $items = $order->get_items();
+ $item = reset( $items );
+ $refund = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 10,
+ 'line_items' => array(
+ $item->get_id() => array(
+ 'qty' => 1,
+ 'refund_total' => 10,
+ ),
+ ),
+ )
+ );
+ $this->assertInstanceOf( \WC_Order_Refund::class, $refund );
+ OrdersStatsDataStore::sync_order( $refund->get_id() );
+ ProductsDataStore::sync_order_products( $refund->get_id() );
+
+ $sales = $this->sut->last_days();
+
+ $this->assertEqualsWithDelta( 10.0, $sales['by_product'][ $mug->get_id() ] ?? 0.0, 0.01, 'Two sold, one refunded' );
+ $this->assertSame( 1, $sales['orders'] );
+ }
+
+ /**
+ * @testdox Sales count as imported only while Analytics holds the store's orders for the period, not while past orders are still to import.
+ */
+ public function test_last_days_imported(): void {
+ $mug = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ $missing = array();
+ for ( $i = 0; $i < 3; $i++ ) {
+ $order = wc_create_order();
+ $order->add_product( $mug, 1 );
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->save();
+ $missing[] = $order->get_id();
+ }
+ $this->assertTrue( $this->sut->last_days()['imported'], 'With too few orders to rank by, the reason stays "too few orders"' );
+
+ for ( $i = 0; $i < ProductSales::MIN_ORDERS; $i++ ) {
+ $this->order( array( array( $mug, 1 ) ), OrderStatus::COMPLETED );
+ }
+ $this->order( array( array( $mug, 1 ) ), OrderStatus::CANCELLED );
+ $this->assertFalse( $this->sut->last_days()['imported'], '20 of 23 orders is under 90%; the cancelled one isn\'t asked for' );
+
+ array_map( array( OrdersStatsDataStore::class, 'sync_order' ), $missing );
+ $this->assertTrue( $this->sut->last_days()['imported'] );
+ }
+
+ /**
+ * @testdox WCPay test-mode orders are left out of the import denominator, matching Analytics.
+ */
+ public function test_last_days_imported_ignores_test_orders(): void {
+ $mug = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ for ( $i = 0; $i < ProductSales::MIN_ORDERS; $i++ ) {
+ $this->order( array( array( $mug, 1 ) ), OrderStatus::COMPLETED );
+ }
+ // Three unsynced test orders: 20/23 would fail the 90% gate if they counted.
+ for ( $i = 0; $i < 3; $i++ ) {
+ $test = wc_create_order();
+ $test->add_product( $mug, 1 );
+ $test->set_status( OrderStatus::COMPLETED );
+ $test->update_meta_data( '_wcpay_mode', 'test' );
+ $test->calculate_totals();
+ $test->save();
+ }
+
+ $this->assertTrue( $this->sut->last_days()['imported'], '20 real orders imported; three WCPay test-mode orders must not block the gate' );
+ }
+
+ /**
+ * @testdox With no orders the total is zero; with Analytics off there are no sales to read.
+ */
+ public function test_last_days_without_sales_or_analytics(): void {
+ $sales = $this->sut->last_days();
+ $this->assertIsArray( $sales );
+ $this->assertSame( 0, $sales['orders'] );
+ $this->assertSame( 0.0, $sales['total'] );
+
+ update_option( 'woocommerce_analytics_enabled', 'no' );
+ $this->assertNull( $this->sut->last_days() );
+ }
+
+ /**
+ * @testdox A filter that excludes no statuses counts every order, and statuses past the column width are cut to match it.
+ */
+ public function test_last_days_with_no_or_long_excluded_statuses(): void {
+ $mug = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ $this->order( array( array( $mug, 1 ) ), OrderStatus::COMPLETED );
+ $this->order( array( array( $mug, 1 ) ), OrderStatus::CANCELLED );
+ add_filter( 'woocommerce_analytics_excluded_order_statuses', '__return_empty_array' );
+
+ $this->assertSame( 2, $this->sut->last_days()['orders'], 'Nothing excluded' );
+
+ remove_filter( 'woocommerce_analytics_excluded_order_statuses', '__return_empty_array' );
+ global $wpdb;
+ $wpdb->update( $wpdb->prefix . 'wc_order_stats', array( 'status' => 'wc-awaiting-collecti' ), array( 'status' => 'wc-cancelled' ) );
+ $long = static fn(): array => array( 'awaiting-collection-at-store' );
+ add_filter( 'woocommerce_analytics_excluded_order_statuses', $long );
+ try {
+ $this->assertSame( 1, $this->sut->last_days()['orders'], 'The long status, stored cut short, is still left out' );
+ } finally {
+ remove_filter( 'woocommerce_analytics_excluded_order_statuses', $long );
+ }
+ }
+
+ /**
+ * @testdox The 90-day window follows the site's time zone, as the lookup tables store local dates.
+ */
+ public function test_last_days_window_in_site_time_zone(): void {
+ $mug = WC_Helper_Product::create_simple_product( true, array( 'regular_price' => 10 ) );
+ try {
+ update_option( 'timezone_string', 'Pacific/Auckland' );
+ $this->order( array( array( $mug, 1 ) ), OrderStatus::COMPLETED, time() - 90 * DAY_IN_SECONDS - 6 * HOUR_IN_SECONDS );
+ $this->order( array( array( $mug, 2 ) ), OrderStatus::COMPLETED, time() - 90 * DAY_IN_SECONDS + 6 * HOUR_IN_SECONDS );
+
+ $sales = $this->sut->last_days();
+
+ $this->assertSame( 1, $sales['orders'], 'The older order is out, though its local date reads later than the UTC boundary' );
+ $this->assertEqualsWithDelta( 20.0, $sales['by_product'][ $mug->get_id() ] ?? 0.0, 0.01 );
+ } finally {
+ delete_option( 'timezone_string' );
+ }
+ }
+
+ /**
+ * Create an order and sync it into the Analytics lookup tables.
+ *
+ * @param array<int, array{0:\WC_Product,1:int}> $lines Products and quantities.
+ * @param string $status Order status.
+ * @param int|null $created When the order was created, or now.
+ * @return \WC_Order
+ */
+ private function order( array $lines, string $status, ?int $created = null ): \WC_Order {
+ $order = wc_create_order();
+ foreach ( $lines as $line ) {
+ $order->add_product( $line[0], $line[1] );
+ }
+ $order->set_status( $status );
+ if ( null !== $created ) {
+ $order->set_date_created( $created );
+ }
+ $order->calculate_totals();
+ $order->save();
+ OrdersStatsDataStore::sync_order( $order->get_id() );
+ ProductsDataStore::sync_order_products( $order->get_id() );
+ return $order;
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
index fb28c331831..10eae3696a5 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
@@ -7,6 +7,7 @@ use Automattic\WooCommerce\Internal\AgentReadiness\AgenticCommerceSettings;
use Automattic\WooCommerce\Internal\AgentReadiness\AgentReadiness;
use Automattic\WooCommerce\Internal\AgentReadiness\ProductFailures;
use Automattic\WooCommerce\Internal\AgentReadiness\ProductsList;
+use Automattic\WooCommerce\Internal\AgentReadiness\ProductScan;
use WC_Helper_Product;
use WC_Unit_Test_Case;
@@ -367,4 +368,55 @@ class ProductsListTest extends WC_Unit_Test_Case {
unset( $GLOBALS['current_screen'], $_GET[ ProductsList::FILTER_PARAM ] );
}
}
+
+ /**
+ * @testdox The Available and Hidden filters list the products their counts count: only Hidden is hidden.
+ */
+ public function test_visibility_filters(): void {
+ global $pagenow, $wp_the_query;
+ $previous = array( $pagenow, $wp_the_query );
+ $ids = array();
+ foreach ( array( 'visible', 'catalog', 'search', 'hidden' ) as $visibility ) {
+ $product = WC_Helper_Product::create_simple_product();
+ $product->set_catalog_visibility( $visibility );
+ $product->save();
+ $ids[ $visibility ] = $product->get_id();
+ }
+ // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Only is_admin() reads it here.
+ $GLOBALS['current_screen'] = new class() {
+ /**
+ * Whether this is an admin screen.
+ */
+ public function in_admin(): bool {
+ return true;
+ }
+ };
+ $pagenow = 'edit.php'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ $listed = function ( string $filter ) use ( &$wp_the_query ): array {
+ $_GET[ ProductsList::FILTER_PARAM ] = $filter;
+ $query = new \WP_Query();
+ $query->set( 'post_type', 'product' );
+ $query->set( 'post_status', 'publish' );
+ $query->set( 'fields', 'ids' );
+ $query->set( 'posts_per_page', -1 );
+ $wp_the_query = $query; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ $this->sut->apply_filter( $query );
+ $found = array_map( 'intval', $query->get_posts() );
+ sort( $found );
+ return $found;
+ };
+
+ // wp-admin never runs the storefront query hooks, but an earlier test can leave one on; the test case restores hooks afterwards.
+ remove_all_actions( 'pre_get_posts' );
+
+ try {
+ $available = array( $ids['visible'], $ids['catalog'], $ids['search'] );
+ sort( $available );
+ $this->assertSame( $available, $listed( ProductScan::COUNT_AVAILABLE ) );
+ $this->assertSame( array( $ids['hidden'] ), $listed( ProductScan::COUNT_HIDDEN ) );
+ } finally {
+ list( $pagenow, $wp_the_query ) = $previous; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ unset( $GLOBALS['current_screen'], $_GET[ ProductsList::FILTER_PARAM ] );
+ }
+ }
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/RemoteRulesTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/RemoteRulesTest.php
index ccdba2d4a42..d587485e605 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/RemoteRulesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/RemoteRulesTest.php
@@ -84,9 +84,10 @@ class RemoteRulesTest extends WC_Unit_Test_Case {
/**
* Point the rules URL at the test URL and answer with this rules file.
*
- * @param array $checks Channel maps by check id.
+ * @param array $checks Channel maps by check id.
+ * @param array|null $store_checks The file's store_checks map, or null to leave it out.
*/
- private function serve( array $checks ): void {
+ private function serve( array $checks, ?array $store_checks = null ): void {
add_filter(
'woocommerce_agent_readiness_rules_url',
static function () {
@@ -97,6 +98,9 @@ class RemoteRulesTest extends WC_Unit_Test_Case {
'version' => '2026-11-01',
'checks' => array(),
);
+ if ( null !== $store_checks ) {
+ $file['store_checks'] = $store_checks;
+ }
foreach ( $checks as $id => $channels ) {
$file['checks'][ $id ] = array(
'label' => 'Ignored by core',
@@ -118,7 +122,7 @@ class RemoteRulesTest extends WC_Unit_Test_Case {
$output_checks = new StoreOutputChecks();
$output_checks->init( new ComingSoonHelper() );
$agent_readiness = new AgentReadiness();
- $agent_readiness->init( $store_conditions, $output_checks, $this->sut, wc_get_container()->get( \Automattic\WooCommerce\Internal\AgentReadiness\DeclaredToAgents::class ) );
+ $agent_readiness->init( $store_conditions, $output_checks, $this->sut, wc_get_container()->get( \Automattic\WooCommerce\Internal\AgentReadiness\DeclaredToAgents::class ), new \Automattic\WooCommerce\Internal\AgentReadiness\ProductSales() );
return $agent_readiness;
}
@@ -639,6 +643,83 @@ class RemoteRulesTest extends WC_Unit_Test_Case {
$this->assertSame( array( 'title_too_long' ), array_keys( $this->sut->channel_rules() ) );
}
+ /**
+ * @testdox The file's store_checks set which store checks show as Required and which are off; a check that blocks AI shopping stays Required and on, and without the map the bundled list applies.
+ */
+ public function test_file_sets_store_checks_required_or_off(): void {
+ $step = static fn( string $id, string $level = StoreConditions::LEVEL_RECOMMENDED ): array => array(
+ 'id' => $id,
+ 'level' => $level,
+ );
+ $channels = array(
+ 'title_too_long' => array(
+ 'chatgpt' => array(
+ 'field' => 'title',
+ 'effect' => 'gaps',
+ ),
+ ),
+ );
+
+ $this->serve(
+ $channels,
+ array(
+ 'refund_returns_page' => array( 'required' => true ),
+ 'search_visible' => array( 'required' => false ),
+ 'launched' => array(
+ 'required' => false,
+ 'off' => true,
+ ),
+ 'order_emails' => array(
+ 'off' => true,
+ 'label' => 'Ignored',
+ ),
+ 'llms_txt_present' => array( 'off' => true ),
+ 'terms_page' => array( 'required' => 'yes' ),
+ 'privacy_page' => 'required',
+ )
+ );
+ $this->assertTrue( $this->sut->refresh() );
+
+ $this->assertSame( array( 'off' => true ), RemoteRules::store_check( 'order_emails' ), 'Only required and off are kept' );
+ $this->assertSame( array(), RemoteRules::store_check( 'terms_page' ), 'A value that is not true or false is dropped' );
+ $this->assertSame( array(), RemoteRules::store_check( 'privacy_page' ) );
+ $this->assertTrue( StoreConditions::shows_required( $step( 'refund_returns_page' ) ) );
+ $this->assertFalse( StoreConditions::shows_required( $step( 'search_visible' ) ), 'The file can drop a bundled Required step' );
+ $this->assertTrue( StoreConditions::shows_required( $step( 'payment_method' ) ), 'A step the map leaves out keeps its bundled level' );
+ $this->assertTrue( StoreConditions::shows_required( $step( 'launched', StoreConditions::LEVEL_REQUIRED ) ), 'A required condition stays Required' );
+ $this->assertFalse( StoreConditions::is_off( 'launched', StoreConditions::LEVEL_REQUIRED ), 'A required condition always runs' );
+ $this->assertTrue( StoreConditions::is_off( 'llms_txt_present' ) );
+
+ $conditions = array_column( wc_get_container()->get( StoreConditions::class )->all(), 'id' );
+ $this->assertNotContains( 'order_emails', $conditions, 'A setup step turned off is not listed' );
+ $this->assertContains( 'launched', $conditions );
+
+ $report = array(
+ 'store_checks' => array(
+ array(
+ 'id' => 'llms_txt_present',
+ 'ok' => false,
+ 'name' => 'llms.txt is served',
+ ),
+ array(
+ 'id' => 'canonical_url',
+ 'ok' => false,
+ 'name' => 'Pages name their canonical URL',
+ ),
+ ),
+ );
+ $listed = array_column( wc_get_container()->get( AgentReadiness::class )->get_store_checks( $report ), 'id' );
+ $this->assertNotContains( 'llms_txt_present', $listed, 'An output check turned off after the scan is left out of the stored report' );
+ $this->assertContains( 'canonical_url', $listed );
+
+ $this->serve( $channels );
+ $this->assertTrue( $this->sut->refresh() );
+ $this->assertSame( array(), RemoteRules::store_check( 'refund_returns_page' ) );
+ $this->assertTrue( StoreConditions::shows_required( $step( 'search_visible' ) ), 'Without the map, the bundled list applies' );
+ $this->assertFalse( StoreConditions::shows_required( $step( 'refund_returns_page' ) ) );
+ $this->assertContains( 'order_emails', array_column( wc_get_container()->get( StoreConditions::class )->all(), 'id' ) );
+ }
+
/**
* @testdox The shipped rules file names the same checks the code can run, and those are the ones that run.
*/
@@ -647,6 +728,12 @@ class RemoteRulesTest extends WC_Unit_Test_Case {
$file = json_decode( (string) file_get_contents( $path ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local file.
$this->assertIsArray( $file );
$this->assertIsArray( $file['checks'] );
+ $this->assertMatchesRegularExpression( '/^\d{4}-\d{2}-\d{2}$/', $file['version'], 'The version is the date of the last change' );
+ $this->assertSame(
+ array_fill_keys( StoreConditions::SHOWN_REQUIRED, array( 'required' => true ) ),
+ $file['store_checks'],
+ 'The shipped file marks the bundled Required steps and turns nothing off, so the first publish changes nothing'
+ );
$rules = ( new AgentReadiness() )->get_default_rules();
$known = array_keys( $rules );
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php
index f77773cd393..76f210fd84d 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ServedOutputChecksTest.php
@@ -3,6 +3,7 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;
+use Automattic\WooCommerce\Internal\AgentReadiness\StoreConditions;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreOutputChecks;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreResponses;
use Automattic\WooCommerce\StoreApi\Utilities\Ucp\Utils as UcpUtils;
@@ -298,7 +299,7 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
}
/**
- * @testdox With UCP on, the profile check reads the served profile, and the endpoint check POSTs to catalog search.
+ * @testdox With UCP on, the profile check reads the served profile, and the endpoint check POSTs to catalog search, once more when it fails, and keeps what a failed one answered.
*/
public function test_ucp_checks(): void {
update_option( 'woocommerce_feature_ucp_enabled', 'yes' );
@@ -327,6 +328,7 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
$this->assertTrue( $results['ucp_profile'] );
$this->assertTrue( $results['ucp_profile_version'] );
$this->assertTrue( $results['ucp_endpoints_live'], 'Catalog search answers even when a GET of the endpoint base does not' );
+ $this->assertSame( '', array_column( $this->sut->all(), 'source', 'id' )['ucp_endpoints_live'], 'A passing check names nothing' );
$this->assertContains( 'POST ' . $search, $this->requested );
$responses[ 'POST ' . $search ] = array( 400, '{"ucp":{"status":"error"},"messages":[{"code":"VALIDATION_ERROR","content":"A query or at least one supported filter is required."}]}' );
@@ -336,10 +338,22 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
$responses[ 'POST ' . $search ] = array( 400, '<html>Bad request</html>' );
$this->serve( $responses );
$this->assertFalse( $this->results()['ucp_endpoints_live'], 'A 400 page is not the endpoint' );
+ $this->assertSame( '', array_column( $this->sut->all(), 'source', 'id' )['ucp_profile_version'], 'A matching version names none' );
$responses['/.well-known/ucp'] = array( 200, (string) str_replace( UcpUtils::VERSION, '2025-01-01', (string) $profile ) );
$this->serve( $responses );
$this->assertFalse( $this->results()['ucp_profile_version'], 'A profile for another UCP version is likely another plugin\'s' );
+ $this->assertSame( '2025-01-01', array_column( $this->sut->all(), 'source', 'id' )['ucp_profile_version'], 'The served version is kept for the message' );
+
+ $responses['/.well-known/ucp'] = array( 200, (string) str_replace( '"' . UcpUtils::VERSION . '"', '"<b>x</b>"', (string) $profile ) );
+ $this->serve( $responses );
+ $this->assertFalse( $this->results()['ucp_profile_version'] );
+ $this->assertSame( '', array_column( $this->sut->all(), 'source', 'id' )['ucp_profile_version'], 'A version that isn\'t a date is not shown' );
+
+ $responses['/.well-known/ucp'] = array( 200, (string) str_replace( UcpUtils::VERSION, '2099-01-01', (string) $profile ) );
+ $this->serve( $responses );
+ $this->assertFalse( $this->results()['ucp_profile_version'] );
+ $this->assertSame( '', array_column( $this->sut->all(), 'source', 'id' )['ucp_profile_version'], 'A newer version is not called older' );
$responses['/.well-known/ucp'] = array( 404, '' );
$responses[ 'POST ' . $search ] = array( 403, '<html>Blocked</html>' );
@@ -350,6 +364,13 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
$this->assertFalse( $results['ucp_endpoints_live'], 'Without a profile, WooCommerce\'s catalog search is tried' );
$this->assertContains( 'POST ' . $search, $this->requested );
+ $responses[ 'POST ' . $search ] = array( 403, '<html>Blocked</html>', array( 'content-type' => 'text/HTML; charset=UTF-8' ) );
+ $this->serve( $responses );
+ $this->assertSame( '403 text/html', array_column( $this->sut->all(), 'source', 'id' )['ucp_endpoints_live'], 'A failed check keeps what came back' );
+ $responses[ 'POST ' . $search ] = null;
+ $this->serve( $responses );
+ $this->assertSame( '', array_column( $this->sut->all(), 'source', 'id' )['ucp_endpoints_live'], 'No answer leaves nothing to show' );
+
$responses[ $path ] = array( 200, '{"namespace":"wc/ucp/v1","routes":{}}' );
$responses[ 'POST ' . $search ] = array( 404, '' );
$this->serve( $responses );
@@ -358,6 +379,31 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
$responses[ 'POST ' . $search ] = array( 200, '<html>Checking your browser</html>' );
$this->serve( $responses );
$this->assertFalse( $this->results()['ucp_endpoints_live'], 'A challenge page is not the endpoint' );
+ $this->assertSame( 2, count( array_keys( $this->requested, 'POST ' . $search, true ) ), 'A failed search is asked once more' );
+
+ $this->serve( $responses );
+ $answers = array( array( 403, '<html>Blocked</html>' ), array( 200, '{"ucp":{"status":"success"},"products":[]}' ) );
+ add_filter(
+ 'pre_http_request',
+ function ( $pre, $args, $url ) use ( $search, &$answers ) {
+ if ( 'POST' !== $args['method'] || substr( $url, strlen( untrailingslashit( home_url() ) ) ) !== $search ) {
+ return $pre;
+ }
+ $answer = array_shift( $answers );
+ return array(
+ 'headers' => new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( array() ),
+ 'body' => $answer[1],
+ 'response' => array(
+ 'code' => $answer[0],
+ 'message' => '',
+ ),
+ 'cookies' => array(),
+ );
+ },
+ 20,
+ 3
+ );
+ $this->assertTrue( $this->results()['ucp_endpoints_live'], 'A refusal followed by the endpoint passes' );
}
/**
@@ -369,11 +415,33 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
$checks = array_column( $this->sut->all(), null, 'id' );
- foreach ( array( 'product_return_policy_schema', 'product_shipping_schema', 'product_buy_action_schema', 'ucp_checkout' ) as $id ) {
+ foreach ( ( new \ReflectionClassConstant( StoreOutputChecks::class, 'PENDING' ) )->getValue() as $id ) {
$this->assertNull( $checks[ $id ]['ok'], $id );
$this->assertTrue( $checks[ $id ]['pending'], $id );
}
$this->assertFalse( $checks['open_graph_tags']['pending'] );
+ $this->assertFalse( $checks['product_return_policy_schema']['pending'], 'WooCommerce adds the returns policy since 11.3' );
+ $this->assertContains( 'product_shipping_schema', ( new \ReflectionClassConstant( StoreOutputChecks::class, 'PENDING' ) )->getValue(), 'The list is not empty' );
+ $this->assertSame( ! StoreConditions::serves_ucp_checkout(), $checks['ucp_checkout']['pending'], 'The UCP checkout check runs once this WooCommerce serves UCP checkout' );
+ }
+
+ /**
+ * @testdox The returns policy check passes for a policy on an offer or on the store's item, as WooCommerce adds it, fails without one, and couldn't check without product details.
+ */
+ public function test_return_policy_on_offer_or_store(): void {
+ $returns = '{"@type":"MerchantReturnPolicy","merchantReturnLink":"' . home_url( '/refund_returns/' ) . '"}';
+ $ld = static fn( string $graph ): string => '<script type="application/ld+json">{"@context":"https://schema.org","@graph":[' . $graph . ']}</script>';
+ $responses = $this->good_store();
+ $result = function ( string $graph ) use ( $responses, $ld ): ?bool {
+ $responses[ $this->product_path() ] = array( 200, self::page( $ld( $graph ) ) );
+ $this->serve( $responses );
+ return array_column( $this->sut->all(), 'ok', 'id' )['product_return_policy_schema'];
+ };
+
+ $this->assertTrue( $result( '{"@type":"Product","name":"Mug","offers":{"@type":"Offer","price":"10"}},{"@type":"OnlineStore","name":"Shop","hasMerchantReturnPolicy":' . $returns . '}' ), 'WooCommerce adds it to the OnlineStore item' );
+ $this->assertTrue( $result( '{"@type":"Product","name":"Mug","offers":{"@type":"Offer","price":"10","hasMerchantReturnPolicy":' . $returns . '}}' ), 'On the offer' );
+ $this->assertFalse( $result( '{"@type":"Product","name":"Mug","offers":{"@type":"Offer","price":"10"}},{"@type":"OnlineStore","name":"Shop"}' ) );
+ $this->assertNull( $result( '{"@type":"OnlineStore","name":"Shop"}' ), 'Without product details it couldn\'t check, as the other product details checks' );
}
/**
@@ -400,6 +468,18 @@ class ServedOutputChecksTest extends WC_Unit_Test_Case {
$this->assertTrue( $buy_action->invoke( null, array( $product ) ) );
$this->assertTrue( $buy_action->invoke( null, array( array( 'potentialAction' => array( array( '@type' => array( 'BuyAction' ) ) ) ) ) ) );
$this->assertFalse( $buy_action->invoke( null, array( array( 'potentialAction' => array( '@type' => 'ViewAction' ) ) ) ) );
+
+ $nested = array(
+ '@type' => 'Product',
+ 'offers' => array(
+ '@type' => 'AggregateOffer',
+ 'offers' => array(
+ '@type' => 'Offer',
+ 'hasMerchantReturnPolicy' => array( '@type' => 'MerchantReturnPolicy' ),
+ ),
+ ),
+ );
+ $this->assertTrue( $offer_has->invoke( null, array( $nested ), 'hasMerchantReturnPolicy' ), 'Policy on a nested Offer inside AggregateOffer' );
}
/**
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php
index 3e5e0103778..b89728a686f 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php
@@ -125,7 +125,7 @@ class StoreConditionsTest extends WC_Unit_Test_Case {
}
/**
- * @testdox Guest checkout off is only recommended, so it doesn't block the switch.
+ * @testdox Guest checkout off is Optional, so it doesn't block the switch.
*/
public function test_store_conditions_checks(): void {
self::make_store_ready();
@@ -136,6 +136,18 @@ class StoreConditionsTest extends WC_Unit_Test_Case {
$this->assertSame( array(), $this->sut->failing_required() );
$this->assertFalse( $checks['guest_checkout']['ok'] );
$this->assertSame( StoreConditions::LEVEL_RECOMMENDED, $checks['guest_checkout']['level'] );
+ $this->assertFalse( StoreConditions::shows_required( $checks['guest_checkout'] ), 'AI assistants can still build carts without guest checkout' );
+ }
+
+ /**
+ * @testdox The UCP and policy page fixes link to the Agentic commerce settings tab, the policy ones to their field.
+ */
+ public function test_fix_links_open_agentic_commerce(): void {
+ $checks = array_column( $this->sut->all(), 'fix_url', 'id' );
+ $tab = admin_url( 'admin.php?page=wc-settings&tab=agentic-commerce' );
+
+ $this->assertSame( $tab, $checks['ucp_on'] );
+ $this->assertSame( $tab . '#' . AgenticCommerceSettings::TERMS_PAGE_OPTION, $checks['terms_page'] );
}
/**
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php
index 369a50eb31e..0887e86f091 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php
@@ -4,6 +4,7 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;
use Automattic\WooCommerce\Internal\AgentReadiness\JsonLd;
+use Automattic\WooCommerce\Internal\AgentReadiness\RemoteRules;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreOutputChecks;
use WC_Helper_Product;
use WC_Structured_Data;
@@ -446,22 +447,27 @@ class StoreOutputChecksTest extends WC_Unit_Test_Case {
}
/**
- * @testdox A shop-only product is sampled. A newer search-only product is not.
+ * @testdox The sampled product is one the scan checks: a search-only product is sampled before an older shop-only one, a newer Hidden product is not.
*/
- public function test_product_checks_include_shop_only_products(): void {
- $product = WC_Helper_Product::create_simple_product();
- $product->set_catalog_visibility( 'catalog' );
- $product->set_image_id( self::factory()->attachment->create_object( array( 'file' => 'image.jpg' ) ) );
- $product->set_date_created( time() - HOUR_IN_SECONDS );
- $product->save();
- $product = wc_get_product( $product->get_id() );
+ public function test_product_checks_sample_checked_products(): void {
+ $shop_only = WC_Helper_Product::create_simple_product();
+ $shop_only->set_catalog_visibility( 'catalog' );
+ $shop_only->set_date_created( time() - 2 * HOUR_IN_SECONDS );
+ $shop_only->save();
$search_only = WC_Helper_Product::create_simple_product();
$search_only->set_catalog_visibility( 'search' );
+ $search_only->set_image_id( self::factory()->attachment->create_object( array( 'file' => 'image.jpg' ) ) );
+ $search_only->set_date_created( time() - HOUR_IN_SECONDS );
$search_only->save();
+ $search_only = wc_get_product( $search_only->get_id() );
+ $hidden = WC_Helper_Product::create_simple_product();
+ $hidden->set_catalog_visibility( 'hidden' );
+ $hidden->save();
$this->serve(
array(
- self::path_of( $product ) => array( 200, self::page_with( array( self::core_product_jsonld( $product ) ) ) ),
- self::path_of( $search_only ) => array( 200, self::page_with( array() ) ),
+ self::path_of( $shop_only ) => array( 200, self::page_with( array() ) ),
+ self::path_of( $search_only ) => array( 200, self::page_with( array( self::core_product_jsonld( $search_only ) ) ) ),
+ self::path_of( $hidden ) => array( 200, self::page_with( array() ) ),
)
);
@@ -847,4 +853,26 @@ class StoreOutputChecksTest extends WC_Unit_Test_Case {
$this->assertSame( array( true, true, true ), $this->product_results() );
}
+
+ /**
+ * @testdox A check the rules file turns off doesn't run and is left out of the results.
+ */
+ public function test_a_check_the_rules_file_turns_off_is_left_out(): void {
+ update_option(
+ RemoteRules::OPTION,
+ array(
+ 'version' => '2026-11-15',
+ 'checks' => array(),
+ 'store_checks' => array( 'llms_txt_present' => array( 'off' => true ) ),
+ ),
+ false
+ );
+ $this->serve( array() );
+
+ $results = $this->results();
+
+ $this->assertArrayNotHasKey( 'llms_txt_present', $results );
+ $this->assertArrayHasKey( 'llms_txt_valid', $results, 'Only the named check is off' );
+ $this->assertArrayHasKey( 'canonical_url', $results );
+ }
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreResponsesTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreResponsesTest.php
index dd25dcce01b..7d6fa5c1839 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreResponsesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreResponsesTest.php
@@ -89,6 +89,31 @@ class StoreResponsesTest extends WC_Unit_Test_Case {
$this->assertSame( array( home_url( '/missing' ), home_url( '/timeout' ), home_url( '/' ) ), $this->requested );
}
+ /**
+ * @testdox A POST is kept per body: a different body to the same URL is sent, and sending it again replaces only its own answer.
+ */
+ public function test_post_json_is_kept_per_body(): void {
+ $sent = array();
+ add_filter(
+ 'pre_http_request',
+ function ( $pre, $args ) use ( &$sent ) {
+ unset( $pre );
+ $sent[] = $args['body'];
+ return self::response( 200, $args['body'] );
+ },
+ 10,
+ 2
+ );
+ $sut = new StoreResponses( true );
+
+ $this->assertSame( '{"a":1}', $sut->post_json( '/echo', array( 'a' => 1 ) )['body'] );
+ $this->assertSame( '{"b":2}', $sut->post_json( '/echo', array( 'b' => 2 ) )['body'] );
+ $this->assertSame( '{"a":1}', $sut->post_json( '/echo', array( 'a' => 1 ) )['body'], 'An earlier body is still read from this scan' );
+ $this->assertSame( '{"b":2}', $sut->post_json_again( '/echo', array( 'b' => 2 ) )['body'] );
+ $this->assertSame( '{"a":1}', $sut->post_json( '/echo', array( 'a' => 1 ) )['body'], 'Sending one body again keeps the other' );
+ $this->assertSame( array( '{"a":1}', '{"b":2}', '{"b":2}' ), $sent );
+ }
+
/**
* @testdox A failed Markdown request to the home page doesn't stop the scan when the page itself loads.
*/