Commit f5d1cd674c1 for woocommerce
commit f5d1cd674c124f80165967094c85e12e72e76f39
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date: Sun Dec 6 11:05:23 2026 +0100
AI shopping health: brand and barcode guidance for makers, GTINs on SQLite and from barcode plugins (#71839)
* Guide stores that make their own products on brand and barcodes
AI shopping health left makers stuck: the barcode fix said to never use
a number you create yourself, and nothing said what brand to use for
your own goods. The brand fix now says to use the store name as the
brand, and the barcode fix says barcode numbers are optional for
products you make yourself, with a link to GS1. Missing barcode numbers
rank after every other Fix first issue when most of the check's example
products have the store name as their brand. The check itself still
reports as before.
Part of WOOAI-1964.
* Find duplicate GTINs on SQLite in AI shopping health
The shared GTIN query used TRIM( LEADING '0' ), _utf8mb4 hex literals and
IF(), which the SQLite integration (Studio, Playground) can't run or runs
wrong, so every scan logged an error and duplicate GTINs were never found.
The query now only reads GTIN rows, in batches, and PHP strips separators
and leading zeros with the same helpers the checks use. On MySQL and
MariaDB the result is the same as before.
Part of WOOAI-1977.
* Read barcode plugin GTINs in every AI shopping health GTIN check
ProductFields::gtin() is now the one place that reads a product's GTIN:
WooCommerce's GTIN field, else EAN for WooCommerce (_alg_ean), Germanized
(_ts_gtin) or Google for WooCommerce (_wc_gla_gtin). The missing, invalid
and duplicate GTIN checks, the product page GTIN check and the UCP catalog
barcodes all use it, so a store with plugin barcodes no longer passes one
row and fails another. A save that changes only these fields tests the
product again.
Part of WOOAI-1974.
* Keep the page barcode check on the GTIN WooCommerce prints
Structured data only prints the product's GTIN field. A barcode stored
only by a barcode plugin still counts for the missing, invalid and
duplicate checks and for the UCP catalog. The page check stays skipped
when WooCommerce would not have printed one.
* Match the stored-scan test to the shared GTIN query
The catalog read is now a meta_key IN list. The assertion that a
single-product check does not scan the catalog was still looking for
the old equality, so it passed even when the scan ran.
* Keep the GS1 link attached in translated barcode guidance
The linked name is the same translated string as the placeholder in
the fix line, so a translation can move the sentence and the link
still lands on that name.
* Run the shared-GTIN parity check only on MySQL
The comparison uses TRIM(LEADING) and charset introducers, which SQLite
cannot run. The PHP result is still asserted on every engine, and the
batch-size override follows ProductScan::GTIN_BATCH.
* Match store-brand and shared-barcode checks to the stored values
A product with two brands is not the store, even when their names join into the store name. Shared barcodes follow the first scalar value of each field and live in a temporary table, and a failed read is not cached or allowed to fail a save. The catalog exports a plugin barcode only when its check digit is valid.
* Find shared GTINs without a temporary table, and align GTIN reads
The shared-GTIN scan wrote owners to a temporary table, which needs the
CREATE TEMPORARY TABLES privilege, and capped the shared keys at 5,001,
so a catalog with more shared GTINs missed some duplicates. It now keeps
each key's first owner in PHP (about 5 MB per 100,000 GTINs) and returns
every shared key; only the stored report is capped.
- The duplicate check reads stored GTINs, as the scan does, so a filter
on the GTIN field can't make the two disagree.
- A store-brand match keeps shortcode-like text in names.
- UCP barcodes from a barcode plugin are no longer stripped to digits, so
a value readiness calls invalid is not exported.
- Tests reach the code they guard.
Part of WOOAI-1964.
* Keep a failed barcode lookup from breaking checks, page it by post id, and match the page GTIN
- get_failing_check_ids() judges without shared barcodes when the lookup fails, and the run-check ability returns an error, instead of throwing.
- The shared-barcode read pages by post id, so it can use the post_id index; an item that fills a whole batch is finished by meta id.
- The UCP catalog validates WooCommerce's own GTIN as the product page structured data does, so both print the same value. Plugin GTINs still need a valid check digit.
* Find shared GTINs by paging through products, not ordered postmeta
Each page reads up to 1,000 published product ids by primary key, then only
their GTIN rows, so the read no longer walks or sorts postmeta, order meta
included.
* Test a product again when a barcode plugin writes its field outside a save
A plugin that calls update_post_meta() after the product save left the stored
issues as they were until the next scan. Writes to the brand, MPN and barcode
plugin fields now test the product at the end of the request, once, for up to
50 products per request and only once a scan has run.
* Compare stored brand, MPN and barcode fields without getter filters
A plugin filtering how _alg_ean or another field reads made every stock-only
save, such as a checkout, look like a field change and test the product again.
* Skip barcode placeholders as shared GTINs, and read the GTIN field as products do
A plugin field holding "0" or "N/A" on two products flagged both as a shared
GTIN. The scan also read WooCommerce's GTIN field raw, so junk such as "n/a"
hid a plugin barcode the product itself uses. A meta delete across all posts
no longer tests the global post.
diff --git a/plugins/woocommerce/changelog/fix-ai-shopping-health-barcode-plugin-gtins b/plugins/woocommerce/changelog/fix-ai-shopping-health-barcode-plugin-gtins
new file mode 100644
index 00000000000..eb4c8fd99a5
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-ai-shopping-health-barcode-plugin-gtins
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+AI shopping health now reads barcode numbers from EAN for WooCommerce, Germanized, and Google for WooCommerce, and AI assistants receive them.
diff --git a/plugins/woocommerce/changelog/fix-ai-shopping-health-duplicate-gtin-sqlite b/plugins/woocommerce/changelog/fix-ai-shopping-health-duplicate-gtin-sqlite
new file mode 100644
index 00000000000..3b13bcb7ab5
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-ai-shopping-health-duplicate-gtin-sqlite
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+AI shopping health now finds products that share a barcode number on SQLite sites, such as WordPress Studio and Playground.
diff --git a/plugins/woocommerce/changelog/wooai-1964-maker-brand-guidance b/plugins/woocommerce/changelog/wooai-1964-maker-brand-guidance
new file mode 100644
index 00000000000..7d05bf6a8d6
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1964-maker-brand-guidance
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+AI shopping health tells stores that make their own products to use the store name as the brand, and that barcode numbers are optional for them.
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/components/check-row.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/components/check-row.tsx
index 7036e6675e1..8acf4603142 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/components/check-row.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/components/check-row.tsx
@@ -286,7 +286,7 @@ export const CheckRow = ( {
) }
{ row.fix && (
<Text variant="body-sm" className="wc-sales-readiness-row__fix">
- { row.fix }
+ <TextWithLink text={ row.fix } link={ row.fix_link } />
</Text>
) }
{ row.seen_at && (
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/test/check-row.test.tsx b/plugins/woocommerce/client/admin/client/sales-readiness/test/check-row.test.tsx
index 8479e1b3b1a..90d2ad709ca 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/test/check-row.test.tsx
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/test/check-row.test.tsx
@@ -93,6 +93,30 @@ describe( 'CheckRow', () => {
);
} );
+ it( 'links a name in the fix line, and keeps the text around it', () => {
+ const { container } = renderRow(
+ row( {
+ id: 'missing_gtin',
+ text: 'Barcode numbers help AI assistants match your products.',
+ fix: 'Barcode numbers are optional for products you make yourself. You can get them from GS1.',
+ fix_link: {
+ href: 'https://www.gs1.org/standards/get-barcodes',
+ text: 'GS1',
+ },
+ } )
+ );
+
+ expect( screen.getByRole( 'link', { name: /GS1/ } ) ).toHaveAttribute(
+ 'href',
+ 'https://www.gs1.org/standards/get-barcodes'
+ );
+ expect(
+ container.querySelector( '.wc-sales-readiness-row__fix' )
+ ).toHaveTextContent(
+ 'Barcode numbers are optional for products you make yourself. You can get them from GS1.'
+ );
+ } );
+
it( 'links the name where the server says it starts, not where the same word appears first', () => {
const { container } = renderRow(
row( {
diff --git a/plugins/woocommerce/client/admin/client/sales-readiness/types.ts b/plugins/woocommerce/client/admin/client/sales-readiness/types.ts
index 99c6863c2cf..e81f8cae82c 100644
--- a/plugins/woocommerce/client/admin/client/sales-readiness/types.ts
+++ b/plugins/woocommerce/client/admin/client/sales-readiness/types.ts
@@ -42,6 +42,8 @@ export interface CheckRow {
seen_at: ViewLink | null;
/** A name in the text to link, such as a tool to test with. */
text_link?: TextLink | null;
+ /** A name in the fix line to link, such as where to get barcode numbers. */
+ fix_link?: TextLink | null;
/** A check that couldn't run because it waits for the merchant, as in coming soon mode. */
waiting?: boolean;
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
index 3611b5cb8a1..2b7687cd5a4 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgentReadiness.php
@@ -756,11 +756,19 @@ class AgentReadiness {
* as the scan counts it; other products the scan leaves out (other types,
* set to Hidden, unpublished) have no issues.
*
+ * If the shared-barcode lookup fails, no barcode counts as shared, so a feed export keeps running.
+ *
* @param \WC_Product $product Product or variation.
* @return array<int, string>
*/
public function get_failing_check_ids( \WC_Product $product ): array {
- $result = $this->check_product( $product );
+ try {
+ $result = $this->check_product( $product );
+ } catch ( \RuntimeException $exception ) {
+ $scan = new ProductScan();
+ $scan->use_shared_gtins( array() );
+ $result = $this->judge_product( $product, $scan );
+ }
return null === $result ? array() : array_map( 'strval', array_keys( $result['checks'] ) );
}
@@ -780,8 +788,30 @@ class AgentReadiness {
*
* @param \WC_Product $product Product or variation.
* @return array{product_id:int,checks:array<string, array<string, array{field:string,effect:string}>>,statuses:array<string, string>}|null
+ *
+ * @throws \RuntimeException When the shared-barcode lookup fails.
*/
public function check_product( \WC_Product $product ): ?array {
+ if ( null === $this->product_scan ) {
+ $this->product_scan = new ProductScan();
+ $stored = get_option( self::REPORT_OPTION );
+ if ( is_array( $stored ) && is_array( $stored['shared_gtins'] ?? null ) ) {
+ $this->product_scan->use_shared_gtins( $stored['shared_gtins'] );
+ }
+ }
+ return $this->judge_product( $product, $this->product_scan );
+ }
+
+ /**
+ * One product as the given scan judges it. See check_product().
+ *
+ * @param \WC_Product $product Product or variation.
+ * @param ProductScan $scan Scan to judge with.
+ * @return array{product_id:int,checks:array<string, array<string, array{field:string,effect:string}>>,statuses:array<string, string>}|null
+ *
+ * @throws \RuntimeException When the shared-barcode lookup fails.
+ */
+ private function judge_product( \WC_Product $product, ProductScan $scan ): ?array {
if ( $product instanceof \WC_Product_Variation ) {
$parent = wc_get_product( $product->get_parent_id() );
if ( ! $parent instanceof \WC_Product ) {
@@ -792,15 +822,8 @@ class AgentReadiness {
if ( ! ProductScan::covers( $product ) ) {
return null;
}
- if ( null === $this->product_scan ) {
- $this->product_scan = new ProductScan();
- $stored = get_option( self::REPORT_OPTION );
- if ( is_array( $stored ) && is_array( $stored['shared_gtins'] ?? null ) ) {
- $this->product_scan->use_shared_gtins( $stored['shared_gtins'] );
- }
- }
$active = $this->get_active_rules();
- $checks = $this->product_scan->failures( $product, $active['rules'], $active['channel_rules'] );
+ $checks = $scan->failures( $product, $active['rules'], $active['channel_rules'] );
return array(
'product_id' => $product->get_id(),
'checks' => $checks,
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/DuplicateGtinCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/DuplicateGtinCheck.php
index 1254635bae3..7d2f4fa138c 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/DuplicateGtinCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/DuplicateGtinCheck.php
@@ -69,7 +69,8 @@ class DuplicateGtinCheck extends AbstractReadinessCheck {
if ( ! ProductFields::needs_identifiers( $product ) ) {
return false;
}
- foreach ( ProductFields::gtins( $product ) as $gtin ) {
+ // Stored values, as the scan that finds shared GTINs reads them.
+ foreach ( ProductFields::gtins( $product, 'edit' ) as $gtin ) {
if ( $scan->is_shared_gtin( $gtin ) ) {
return true;
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingBrandCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingBrandCheck.php
index 56afc71717c..7355744c9d4 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingBrandCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingBrandCheck.php
@@ -43,7 +43,7 @@ class MissingBrandCheck extends AbstractReadinessCheck {
* What to do about it.
*/
public function fix(): string {
- return __( 'Add a brand. Google allows an empty brand only when the product truly has none.', 'woocommerce' );
+ return __( 'Add a brand. For products the store makes itself, use the store name as the brand. Google allows an empty brand only when the product truly has none.', 'woocommerce' );
}
/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php
index 3c40c0ef3cb..ad85d77cab4 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/Checks/MissingGtinCheck.php
@@ -47,7 +47,7 @@ class MissingGtinCheck extends AbstractReadinessCheck {
* What to do about it.
*/
public function fix(): string {
- return __( 'Add the GTIN (UPC, EAN or ISBN) from the packaging or supplier to the product, or to each variation of a variable product; never make one up.', 'woocommerce' );
+ return __( 'Add the GTIN (UPC, EAN or ISBN) from the packaging or supplier to the product, or to each variation of a variable product; never make one up. Products the store makes itself don\'t need one; GS1 issues GTINs to stores that want them.', 'woocommerce' );
}
/**
@@ -93,7 +93,7 @@ class MissingGtinCheck extends AbstractReadinessCheck {
* @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() );
+ return ProductFields::needs_identifiers( $item ) && '' === ProductFields::gtin( $item );
}
/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductFields.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductFields.php
index fe8e828ddc9..53a408f1aff 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductFields.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductFields.php
@@ -18,6 +18,12 @@ class ProductFields {
*/
public const GTIN_SEPARATORS = array( '-', ' ', "\t", "\n", "\r", "\x0B", "\x0C", "\u{00A0}", "\u{2007}", "\u{202F}", "\u{FEFF}" );
+ /**
+ * Meta keys of barcode plugins that keep a GTIN outside WooCommerce's GTIN field, in the
+ * order gtin() reads them: EAN for WooCommerce, Germanized, Google for WooCommerce.
+ */
+ public const GTIN_PLUGIN_META_KEYS = array( '_alg_ean', '_ts_gtin', '_wc_gla_gtin' );
+
/**
* Brand taxonomies brand() reads, in order: WooCommerce, Perfect Brands, YITH.
*/
@@ -36,6 +42,16 @@ class ProductFields {
return $text;
}
+ /**
+ * A name to compare: entities decoded, spaces collapsed, lower case. Shortcode-like text stays, as it is part of the name.
+ *
+ * @param string $name Store or brand name.
+ */
+ private static function comparable_name( string $name ): string {
+ $name = html_entity_decode( $name, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
+ return wc_strtolower( trim( (string) preg_replace( '/[\s\x{00A0}\x{2007}\x{202F}\x{FEFF}]+/u', ' ', $name ) ) );
+ }
+
/**
* Text left once shortcodes, HTML and entities such as are gone.
*
@@ -54,17 +70,43 @@ class ProductFields {
* @param \WC_Product $product Product, not a variation.
*/
public static function brand( \WC_Product $product ): string {
+ return implode( ', ', self::brand_names( $product ) );
+ }
+
+ /**
+ * Brand names brand() joins, in that order. One entry per term, so two
+ * brands are not one name that happens to contain a comma.
+ *
+ * @param \WC_Product $product Product, not a variation.
+ * @return array<int, string>
+ */
+ private static function brand_names( \WC_Product $product ): array {
foreach ( self::BRAND_TAXONOMIES as $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
continue;
}
$terms = get_the_terms( $product->get_id(), $taxonomy );
if ( is_array( $terms ) && ! empty( $terms ) ) {
- return implode( ', ', wp_list_pluck( $terms, 'name' ) );
+ return array_map( 'strval', wp_list_pluck( $terms, 'name' ) );
}
}
$values = array_map( 'trim', self::attribute_values( $product, array( 'brand' ) ) );
- return implode( ', ', array_diff( $values, array( '' ) ) );
+ return array_values( array_diff( $values, array( '' ) ) );
+ }
+
+ /**
+ * Whether the product's brand is the store's name, as for goods the store makes itself.
+ * Case, extra spaces and HTML entities don't matter; a product with several brands doesn't match.
+ *
+ * @param \WC_Product $product Product, not a variation.
+ */
+ public static function is_store_brand( \WC_Product $product ): bool {
+ $names = self::brand_names( $product );
+ if ( 1 !== count( $names ) ) {
+ return false;
+ }
+ $store = self::comparable_name( (string) get_bloginfo( 'name' ) );
+ return '' !== $store && self::comparable_name( $names[0] ) === $store;
}
/**
@@ -192,15 +234,16 @@ class ProductFields {
}
/**
- * Normalised GTINs on the product and its published variations.
+ * Normalised GTINs of the product and its published variations, as gtin() reads them.
*
* @param \WC_Product $product Product.
+ * @param string $context 'view' applies the GTIN field's filters; 'edit' reads the stored value, as the shared-GTIN scan does.
* @return array<int, string>
*/
- public static function gtins( \WC_Product $product ): array {
+ public static function gtins( \WC_Product $product, string $context = 'view' ): array {
$gtins = array();
foreach ( array_merge( array( $product ), self::variations( $product ) ) as $item ) {
- $gtin = self::normalise_gtin( (string) $item->get_global_unique_id() );
+ $gtin = self::gtin( $item, $context );
if ( '' !== $gtin ) {
$gtins[] = $gtin;
}
@@ -208,10 +251,31 @@ class ProductFields {
return array_values( array_unique( $gtins ) );
}
+ /**
+ * The normalised GTIN of a product or variation, or '': WooCommerce's GTIN field, else the
+ * first barcode plugin field that has one. The missing, invalid and duplicate checks and the
+ * UCP catalog read it here. The product page check does not: structured data prints only
+ * WooCommerce's GTIN field.
+ *
+ * @param \WC_Product $item Product or variation.
+ * @param string $context 'view' applies the GTIN field's filters; 'edit' reads the stored value.
+ */
+ public static function gtin( \WC_Product $item, string $context = 'view' ): string {
+ $gtin = self::normalise_gtin( (string) $item->get_global_unique_id( $context ) );
+ foreach ( self::GTIN_PLUGIN_META_KEYS as $key ) {
+ if ( '' !== $gtin ) {
+ break;
+ }
+ $value = $item->get_meta( $key, true, $context );
+ $gtin = self::normalise_gtin( is_scalar( $value ) ? (string) $value : '' );
+ }
+ return $gtin;
+ }
+
/**
* Remove the hyphens and spaces, including non-breaking ones, that core
- * allows inside a GTIN and that imports leave around it. The duplicate
- * GTIN query strips the same characters.
+ * allows inside a GTIN and that imports leave around it. Shared GTINs
+ * are compared after the same stripping, in PHP.
*
* @param string $gtin Stored GTIN.
*/
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
index b4198f56bc9..7526685e75d 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductScan.php
@@ -114,6 +114,11 @@ class ProductScan {
*/
public const SHARED_GTINS_LIMIT = 5000;
+ /**
+ * Products read per query when looking for shared GTINs.
+ */
+ public const GTIN_BATCH = 1000;
+
/**
* Normalised GTIN keys carried by more than one published product.
*
@@ -571,7 +576,7 @@ class ProductScan {
'intval',
$wpdb->get_col(
$wpdb->prepare(
- // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- One %d placeholder per product.
+ // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- One %d placeholder per product.
"SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product_variation' AND post_parent IN ({$placeholders})",
array_map( 'intval', $product_ids )
)
@@ -752,55 +757,135 @@ class ProductScan {
/**
* Shared GTIN keys, read from the catalog the first time they're needed.
*
- * @return array<string, bool>
+ * @return array<string, true>
+ *
+ * @throws \RuntimeException When a catalog query fails. Nothing is cached, so the next read tries again.
*/
private function shared_gtin_keys(): array {
if ( null === $this->shared_gtins ) {
- global $wpdb;
-
- // Read from postmeta, not wc_product_meta_lookup: imports and direct
- // meta writes skip both the lookup table and core's uniqueness check.
- // Only shared GTINs come back, so memory follows the duplicates.
- // The separators go in as hex literals: a non-ASCII query sends
- // wpdb into its per-table charset checks.
- $normalised = 'pm.meta_value';
- foreach ( ProductFields::GTIN_SEPARATORS as $separator ) {
- $normalised = "REPLACE( {$normalised}, _utf8mb4 X'" . bin2hex( $separator ) . "', '' )";
- }
- // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $normalised is built from constant hex literals.
- $gtins = (array) $wpdb->get_col(
+ $this->shared_gtins = $this->read_shared_gtin_keys();
+ }
+ return $this->shared_gtins;
+ }
+
+ /**
+ * GTIN keys carried by more than one published product.
+ *
+ * Read from postmeta, not wc_product_meta_lookup: imports and direct meta
+ * writes skip both the lookup table and core's uniqueness check. Each item's
+ * GTIN is picked as ProductFields::gtin() picks it, including an empty or
+ * non-scalar first row for a field. Pages through published products by id,
+ * then reads their GTIN rows; PHP keeps each key's first owner, about 5 MB per 100,000 GTINs.
+ *
+ * @return array<string, true>
+ *
+ * @throws \RuntimeException When a catalog query fails.
+ */
+ private function read_shared_gtin_keys(): array {
+ global $wpdb;
+
+ $keys = array_merge( array( '_global_unique_id' ), ProductFields::GTIN_PLUGIN_META_KEYS );
+ $positions = array_flip( $keys );
+ $in_keys = implode( ', ', array_fill( 0, count( $keys ), '%s' ) );
+ $owners = array();
+ $shared = array();
+ $last_id = 0;
+ while ( true ) {
+ $wpdb->last_error = '';
+ $items = (array) $wpdb->get_results(
$wpdb->prepare(
"
- SELECT owned.gtin
- FROM (
- SELECT DISTINCT IF( p.post_type = %s, p.post_parent, p.ID ) AS owner_id,
- TRIM( LEADING '0' FROM {$normalised} ) AS gtin
- FROM {$wpdb->postmeta} pm
- INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
- INNER JOIN {$wpdb->posts} owner ON owner.ID = IF( p.post_type = %s, p.post_parent, p.ID )
- WHERE pm.meta_key = %s
- AND pm.meta_value != ''
- AND p.post_type IN ( %s, %s )
- AND p.post_status = %s
- AND owner.post_status = %s
- ) owned
- GROUP BY owned.gtin
- HAVING COUNT(*) > 1
+ SELECT p.ID, CASE WHEN p.post_type = %s THEN p.post_parent ELSE p.ID END AS owner_id
+ FROM {$wpdb->posts} p
+ INNER JOIN {$wpdb->posts} owner ON owner.ID = CASE WHEN p.post_type = %s THEN p.post_parent ELSE p.ID END
+ WHERE p.ID > %d
+ AND p.post_type IN ( %s, %s )
+ AND p.post_status = %s
+ AND owner.post_status = %s
+ ORDER BY p.ID
+ LIMIT %d
",
'product_variation',
'product_variation',
- '_global_unique_id',
+ $last_id,
'product',
'product_variation',
'publish',
- 'publish'
- )
+ 'publish',
+ self::GTIN_BATCH
+ ),
+ ARRAY_N
);
- // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
-
- $this->shared_gtins = array_fill_keys( array_map( 'strval', $gtins ), true );
+ if ( '' !== self::db_error() ) {
+ throw new \RuntimeException( 'Agent readiness could not list shared barcodes.' );
+ }
+ if ( array() === $items ) {
+ break;
+ }
+ $item_owners = array();
+ foreach ( $items as $item ) {
+ $item_owners[ (int) $item[0] ] = (int) $item[1];
+ }
+ $last_id = (int) end( $items )[0];
+ $in_ids = implode( ', ', array_fill( 0, count( $item_owners ), '%d' ) );
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $in_ids and $in_keys hold placeholders.
+ $rows = (array) $wpdb->get_results(
+ $wpdb->prepare(
+ "
+ SELECT pm.post_id, pm.meta_key, pm.meta_value
+ FROM {$wpdb->postmeta} pm
+ WHERE pm.meta_key IN ( {$in_keys} )
+ AND pm.post_id IN ( {$in_ids} )
+ ORDER BY pm.meta_id
+ ",
+ array_merge( $keys, array_keys( $item_owners ) )
+ ),
+ ARRAY_N
+ );
+ // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
+ if ( '' !== self::db_error() ) {
+ throw new \RuntimeException( 'Agent readiness could not list shared barcodes.' );
+ }
+ // Per item: the first row of each field, and the GTIN from the earliest field that has one.
+ $seen = array();
+ $picked = array();
+ foreach ( $rows as $row ) {
+ $item = (int) $row[0];
+ $meta_key = (string) $row[1];
+ if ( isset( $seen[ $item ][ $meta_key ] ) ) {
+ continue;
+ }
+ $seen[ $item ][ $meta_key ] = true;
+ $position = $positions[ $meta_key ] ?? PHP_INT_MAX;
+ if ( isset( $picked[ $item ] ) && $picked[ $item ][0] <= $position ) {
+ continue;
+ }
+ $raw = maybe_unserialize( $row[2] );
+ $value = is_scalar( $raw ) ? (string) $raw : '';
+ if ( '_global_unique_id' === $meta_key ) {
+ // As set_global_unique_id() keeps it when the product loads, so the pick matches gtin().
+ $value = (string) preg_replace( '/[^' . \WC_Product::GLOBAL_UNIQUE_ID_CHARACTERS . ']/', '', $value );
+ }
+ $value = ProductFields::normalise_gtin( $value );
+ if ( '' !== $value ) {
+ $picked[ $item ] = array( $position, $value );
+ }
+ }
+ foreach ( $picked as $item => $pick ) {
+ $owner = $item_owners[ $item ];
+ $key = ProductFields::gtin_key( $pick[1] );
+ // A placeholder such as "0" or "N/A" is not a barcode two products can share.
+ if ( ! preg_match( '/^\d+[Xx]?$/', $key ) ) {
+ continue;
+ }
+ if ( ! isset( $owners[ $key ] ) ) {
+ $owners[ $key ] = $owner;
+ } elseif ( $owners[ $key ] !== $owner ) {
+ $shared[ (string) $key ] = true;
+ }
+ }
}
- return $this->shared_gtins;
+ return $shared;
}
/**
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php b/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
index c0017092d19..f764d2b0cd5 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ProductsList.php
@@ -21,9 +21,9 @@ class ProductsList {
private const STOCK_ONLY_CHANGES = array( 'stock_quantity', 'stock_status', 'total_sales', 'date_modified' );
/**
- * Meta the brand and MPN checks read. A save can change only these, and get_changes() lists properties.
+ * Meta the brand, MPN and GTIN checks read. A save can change only these, and get_changes() lists properties.
*/
- private const READINESS_META = array( '_wc_gla_brand', '_wc_gla_mpn' );
+ private const READINESS_META = array( '_wc_gla_brand', '_wc_gla_mpn', ...ProductFields::GTIN_PLUGIN_META_KEYS );
/**
* The most products tested again at the end of one request. Deleting a term thousands
@@ -82,6 +82,9 @@ class ProductsList {
add_action( 'woocommerce_trash_product_variation', array( $this, 'handle_variation_removed' ) );
add_action( 'woocommerce_before_delete_product_variation', array( $this, 'handle_before_variation_delete' ) );
add_action( 'woocommerce_delete_product_variation', array( $this, 'handle_variation_removed' ) );
+ add_action( 'added_post_meta', array( $this, 'handle_meta_change' ), 10, 3 );
+ add_action( 'updated_post_meta', array( $this, 'handle_meta_change' ), 10, 3 );
+ add_action( 'deleted_post_meta', array( $this, 'handle_meta_change' ), 10, 3 );
add_action( 'added_term_relationship', array( $this, 'handle_terms_changed' ), 10, 3 );
add_action( 'deleted_term_relationships', array( $this, 'handle_terms_changed' ), 10, 3 );
add_action( 'pre_get_posts', array( $this, 'apply_filter' ) );
@@ -123,13 +126,14 @@ class ProductsList {
}
/**
- * Whether this save changes the brand or MPN meta the checks read.
+ * Whether this save changes the brand, MPN or GTIN meta the checks read.
*
* @param \WC_Product $product Product being saved.
*/
private static function readiness_meta_changed( \WC_Product $product ): bool {
foreach ( self::READINESS_META as $key ) {
- if ( $product->get_meta( $key ) !== get_post_meta( $product->get_id(), $key, true ) ) {
+ // The edit context skips getter filters, so a filtered value isn't taken for a change.
+ if ( $product->get_meta( $key, true, 'edit' ) !== get_post_meta( $product->get_id(), $key, true ) ) {
return true;
}
}
@@ -171,7 +175,12 @@ class ProductsList {
ProductFailures::forget( $product_id );
return;
}
- $result = $this->agent_readiness->check_product( $product );
+ try {
+ $result = $this->agent_readiness->check_product( $product );
+ } catch ( \RuntimeException $exception ) {
+ // The product is already saved. A failed barcode lookup must not replace the stored result or fail the save.
+ return;
+ }
if ( null === $result ) {
ProductFailures::forget( $product_id );
return;
@@ -285,6 +294,33 @@ class ProductsList {
}
}
+ /**
+ * Note a product to test again when a barcode plugin writes its brand, MPN or GTIN field
+ * outside a product save, for example with update_post_meta() after the save.
+ *
+ * @internal
+ *
+ * @param mixed $meta_id Meta id, or ids for a delete.
+ * @param mixed $object_id Post id.
+ * @param mixed $meta_key Meta key.
+ */
+ public function handle_meta_change( $meta_id, $object_id, $meta_key ): void {
+ unset( $meta_id );
+ // delete_post_meta_by_key() passes no post id; get_post_type( 0 ) would read the global post.
+ if ( (int) $object_id <= 0 || ! in_array( $meta_key, self::READINESS_META, true ) ) {
+ return;
+ }
+ $type = get_post_type( (int) $object_id );
+ if ( 'product' === $type ) {
+ $this->retest_at_shutdown( (int) $object_id );
+ } elseif ( 'product_variation' === $type ) {
+ $parent_id = (int) wp_get_post_parent_id( (int) $object_id );
+ if ( $parent_id > 0 ) {
+ $this->retest_at_shutdown( $parent_id );
+ }
+ }
+ }
+
/**
* Test a product again at the end of the request, once however many changes note it.
* Without a stored report there is nothing to update, so nothing is noted, and past
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index c489dec6e62..6a6cbb5b89d 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -45,6 +45,8 @@ A variable product with some priced variations fails `missing_regular_price` but
Two Google exceptions, per product: `missing_brand` leaves Google out when Google for WooCommerce sends its own brand (`_wc_gla_brand`), and `missing_gtin` leaves Google out when the product has a brand and an MPN (`_wc_gla_mpn` or an "MPN" attribute). Brands set through Google for WooCommerce attribute mapping rules are not read yet.
+A product's GTIN is WooCommerce's GTIN field, else the first barcode plugin field that has one: EAN for WooCommerce (`_alg_ean`), Germanized (`_ts_gtin`), Google for WooCommerce (`_wc_gla_gtin`). `ProductFields::gtin()` reads it for the missing, invalid and duplicate GTIN checks and the UCP catalog's barcodes. The product page GTIN check does not: WooCommerce's structured data prints only the GTIN field, so a barcode kept only in a plugin field is skipped there, the same way a brand WooCommerce does not print is skipped.
+
## Scope
Only published simple and variable products are checked, the types agents can buy today. Agents find other types through the UCP catalog, but its cart sends only a product and a quantity: grouped and external products aren't purchasable, and subscriptions, bookings and bundles need a plan, a date or options it doesn't send. Two groups are counted instead of checked, so the merchant sees them without being asked to fix them:
@@ -114,7 +116,7 @@ The checks from `no_noindex_directives` down pass on a stock store today. They s
## Failures per product
-`refresh_report()` stores what each product fails in product meta (`ProductFailures`), one row per check and per channel status, plus a `checked` row on every product the checks cover, passing ones included. `ProductsList` updates a product's rows when it is saved, except for a save that changes only stock or nothing, and at the end of the request when a category, brand or attribute term is added to it or removed (the editor, quick edit and bulk edit save terms before the product, and deleting a term saves no product; `ProductsList::RETEST_LIMIT` products per request, the rest waiting for the next daily check; only products noted on the site current at the end of the request, so a change made while switched to another site of a multisite network waits for that site's next save or check), removes them when it is trashed, tests the parent again when a variation is trashed, restored or deleted, and filters the Products list on them for the links from the readiness pages (`?agent_readiness=<value>`); there is no column or dropdown on the list. A notice above the list, before other notices, says it shows products from AI shopping health, with a Show all products link (`ProductsList::filter_notice()`). For a failing check it also names the issue with the report's title and count ("Add a brand to 11 products", from `ReadinessCopy::product_check()` and `ProductFailures::counts()`) and links back to AI shopping health. A covered product without rows was not tested, by the scan's product limit. The stored report's product counts are read from these rows, the total from the `checked` rows, so a product fixed, added or removed since the scan counts now. The example products per check can be out of date; the count links to the filtered Products list. The scan stores the GTINs more than one product shares in the report (`shared_gtins`, not returned by the report readers, up to `ProductScan::SHARED_GTINS_LIMIT`), so checking one product on save or with the run ability doesn't read every published product. Past the limit, nothing is stored and a check of one product reads the catalog. A GTIN shared since the scan, on the saved product or another, is flagged at the next scan. Core refuses an exact duplicate on save, so this is one that differs only by separators or leading zeros, or a direct meta write.
+`refresh_report()` stores what each product fails in product meta (`ProductFailures`), one row per check and per channel status, plus a `checked` row on every product the checks cover, passing ones included. `ProductsList` updates a product's rows when it is saved, except for a save that changes only stock or nothing, and at the end of the request when a category, brand or attribute term is added to it or removed, or a brand, MPN or barcode plugin field is written outside a save (`update_post_meta()` after `save()`) (the editor, quick edit and bulk edit save terms before the product, and deleting a term saves no product; `ProductsList::RETEST_LIMIT` products per request, the rest waiting for the next daily check; only products noted on the site current at the end of the request, so a change made while switched to another site of a multisite network waits for that site's next save or check), removes them when it is trashed, tests the parent again when a variation is trashed, restored or deleted, and filters the Products list on them for the links from the readiness pages (`?agent_readiness=<value>`); there is no column or dropdown on the list. A notice above the list, before other notices, says it shows products from AI shopping health, with a Show all products link (`ProductsList::filter_notice()`). For a failing check it also names the issue with the report's title and count ("Add a brand to 11 products", from `ReadinessCopy::product_check()` and `ProductFailures::counts()`) and links back to AI shopping health. A covered product without rows was not tested, by the scan's product limit. The stored report's product counts are read from these rows, the total from the `checked` rows, so a product fixed, added or removed since the scan counts now. The example products per check can be out of date; the count links to the filtered Products list. The scan stores the GTINs more than one product shares in the report (`shared_gtins`, not returned by the report readers, up to `ProductScan::SHARED_GTINS_LIMIT`), so checking one product on save or with the run ability doesn't read every published product. Past the limit, nothing is stored and a check of one product reads the catalog. The catalog read pages through published products by id and compares their GTINs in PHP, so it also works on SQLite (Studio, Playground); memory holds one product id per distinct GTIN. A GTIN shared since the scan, on the saved product or another, is flagged at the next scan. Core refuses an exact duplicate on save, so this is one that differs only by separators or leading zeros, a barcode plugin's field, or a direct meta write.
## What the store declares to agents
@@ -221,7 +223,7 @@ Sales readiness opens with when the last check ran and Check again ("Check your
The product checks, under "Listings in AI shopping apps", show how many products each channel can list ("2 of 15 can be listed"), then each failing product check, titled with what to do and its count ("Add a brand to 13 products"), why it matters, and "View N products", which opens the Products list filtered to them. With up to three failing products the title names them ("Add a brand to Blue hoodie and Red cap") when their failures are stored; one product without them is "a product", and more than three are counted. The copy is in `ReadinessCopy`. Product image alt text isn't listed there, since the `images_have_alt` store check covers it.
-Fix first, a card of its own, lists the required setup steps that fail, then the top three other issues. When it holds only setup steps, its first line counts them as the Setup checklist does, and it has no ranking line or link. Required setup steps include the ones shown as Required (`StoreConditions::SHOWN_REQUIRED`, or `store_checks` in the rules file): `search_visible`, `payment_method`, `order_emails`, `privacy_page`, `terms_page` and `refund_returns_page`. Guest checkout is optional. Of the scanned checks, a failing `ucp_profile` or `ucp_checkout` is Required with UCP on, and so is one that keeps AI assistants off the store's pages, except `pages_public`: a store whose pages all need a login, such as a members-only store, chose that and can still be ready for AI assistants that sign in. It is Recommended: it shows in Store access without a badge and in Fix first under Needed to list products, and doesn't count toward the required steps or keep AI shopping from being turned on. A failing `ucp_endpoints_live` has no badge, like any failing check that isn't Required, and stays out of Fix first, since it can fail now and then with nothing changed on the store. While AI shopping is off, Store access notes that some checks only run when it is on; when the card has no other check to show, it says what turning AI shopping on checks instead, with a Turn on AI shopping button. A question card's badge counts its issues, says All passed, Couldn't check when nothing failed but a check tried to run and couldn't, or Not checked yet while the checks wait for the merchant (the row says why). Issues are ranked by what they stop, then by sales: store checks that block `listing` (such as structured data) and product checks that keep products off a channel (`not_listable`), then product checks that only make products harder to find. Within each, the larger share of sales on the affected products comes first, then the larger product count, then page order. Without sales to compare, a product check's count is multiplied by the AI apps it affects, so 3 products kept out of 3 apps come before 5 products kept out of 1. Store checks with no sales link, such as a missing meta description, stay out of Fix first. `ProductSales` reads each product's net sales over the last 90 days from the Analytics lookup tables (`wc_order_product_lookup` joined with `wc_order_stats`), with the order statuses Analytics excludes left out and variations counted toward their parent and on their own. The scan adds up the sales of each check's failing products. A check a variable product fails through some of its variations (a missing price or GTIN, a missing variation image, or an option set to "any") adds only those variations' sales. An invalid GTIN, a GTIN shared with another product, and an image under 500 pixels still count the whole product's sales, which only changes the rank. The report stores each check's `sales_share` (0 to 1) and `sales` (`days`, `orders`, `imported`). While Analytics is off, `sales` is null. With fewer than `ProductSales::MIN_ORDERS` (20) orders in the period, too few to rank by, shares are null. They are null too while a store with at least 20 orders has under 90% of them in Analytics (`imported` false), as when past orders were never imported. Orders in several currencies are summed without conversion, as Analytics does. In both cases Fix first ranks by product count and AI apps, and says why. It says to start with the fixes that affect the most sales, over the period the figures cover, only when an issue on the card sold something; otherwise it says it ranks by product count. A share is rounded to 4 places and any sales keep at least 0.0001, so small sales never read as "No sales". A share is not shown once a check's count changes after the scan, since it was measured on the products failing then, but Fix first still ranks the check by it (`ranked_share`), so fixing one product doesn't move the issue down. Under headings for what each group stops (Required for AI shopping, Needed to list products, Helps shoppers find products), a product issue is badged by its share of sales ("38% of sales"); its line starts with the share, the first saying over which period ("38% of your sales in the last 90 days."); products that sold nothing in the period say "No sales" instead of 0%.
+Fix first, a card of its own, lists the required setup steps that fail, then the top three other issues. When it holds only setup steps, its first line counts them as the Setup checklist does, and it has no ranking line or link. Required setup steps include the ones shown as Required (`StoreConditions::SHOWN_REQUIRED`, or `store_checks` in the rules file): `search_visible`, `payment_method`, `order_emails`, `privacy_page`, `terms_page` and `refund_returns_page`. Guest checkout is optional. Of the scanned checks, a failing `ucp_profile` or `ucp_checkout` is Required with UCP on, and so is one that keeps AI assistants off the store's pages, except `pages_public`: a store whose pages all need a login, such as a members-only store, chose that and can still be ready for AI assistants that sign in. It is Recommended: it shows in Store access without a badge and in Fix first under Needed to list products, and doesn't count toward the required steps or keep AI shopping from being turned on. A failing `ucp_endpoints_live` has no badge, like any failing check that isn't Required, and stays out of Fix first, since it can fail now and then with nothing changed on the store. While AI shopping is off, Store access notes that some checks only run when it is on; when the card has no other check to show, it says what turning AI shopping on checks instead, with a Turn on AI shopping button. A question card's badge counts its issues, says All passed, Couldn't check when nothing failed but a check tried to run and couldn't, or Not checked yet while the checks wait for the merchant (the row says why). Issues are ranked by what they stop, then by sales: store checks that block `listing` (such as structured data) and product checks that keep products off a channel (`not_listable`), then product checks that only make products harder to find. Within each, the larger share of sales on the affected products comes first, then the larger product count, then page order. Missing barcode numbers (`missing_gtin`) rank after every other issue when more than half of the check's example products (the up to 10 the report lists, still failing) have the store's name as their brand (`ProductFields::is_store_brand()`: case, extra spaces and HTML entities don't matter; a product with several brands doesn't match). A store that makes its own goods needs no barcode numbers for them, so the row still shows on its card and in Fix first when nothing else is left, but doesn't push out other fixes. Its fix line says barcode numbers are optional for products the store makes and links GS1, and the brand fix says to use the store name as the brand. Without sales to compare, a product check's count is multiplied by the AI apps it affects, so 3 products kept out of 3 apps come before 5 products kept out of 1. Store checks with no sales link, such as a missing meta description, stay out of Fix first. `ProductSales` reads each product's net sales over the last 90 days from the Analytics lookup tables (`wc_order_product_lookup` joined with `wc_order_stats`), with the order statuses Analytics excludes left out and variations counted toward their parent and on their own. The scan adds up the sales of each check's failing products. A check a variable product fails through some of its variations (a missing price or GTIN, a missing variation image, or an option set to "any") adds only those variations' sales. An invalid GTIN, a GTIN shared with another product, and an image under 500 pixels still count the whole product's sales, which only changes the rank. The report stores each check's `sales_share` (0 to 1) and `sales` (`days`, `orders`, `imported`). While Analytics is off, `sales` is null. With fewer than `ProductSales::MIN_ORDERS` (20) orders in the period, too few to rank by, shares are null. They are null too while a store with at least 20 orders has under 90% of them in Analytics (`imported` false), as when past orders were never imported. Orders in several currencies are summed without conversion, as Analytics does. In both cases Fix first ranks by product count and AI apps, and says why. It says to start with the fixes that affect the most sales, over the period the figures cover, only when an issue on the card sold something; otherwise it says it ranks by product count. A share is rounded to 4 places and any sales keep at least 0.0001, so small sales never read as "No sales". A share is not shown once a check's count changes after the scan, since it was measured on the products failing then, but Fix first still ranks the check by it (`ranked_share`), so fixing one product doesn't move the issue down. Under headings for what each group stops (Required for AI shopping, Needed to list products, Helps shoppers find products), a product issue is badged by its share of sales ("38% of sales"); its line starts with the share, the first saying over which period ("38% of your sales in the last 90 days."); products that sold nothing in the period say "No sales" instead of 0%.
Tracks event: `agentic_commerce_ucp_toggled` (`enabled`), sent only when the store allows tracking.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php
index 4bf936a31e8..f49a4f7f9ff 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCheckPage.php
@@ -724,7 +724,7 @@ class ReadinessCheckPage implements RegisterHooksInterface {
$rows = array();
foreach ( $failing as $check ) {
$issue = self::product_issue( $check, $linked );
- $rows[] = self::row( (string) ( $check['id'] ?? '' ), 'open', $issue['title'], $issue['why'], $issue['fix'], self::products_link( (int) $check['count'], (string) ( $check['id'] ?? '' ), $linked ) );
+ $rows[] = self::row( (string) ( $check['id'] ?? '' ), 'open', $issue['title'], $issue['why'], $issue['fix'], self::products_link( (int) $check['count'], (string) ( $check['id'] ?? '' ), $linked ), null, null, null, $issue['fix_link'] );
}
$listed = array();
foreach ( $channels as $channel_id => $channel ) {
@@ -948,9 +948,10 @@ class ReadinessCheckPage implements RegisterHooksInterface {
* @param array{0:string,1:string}|null $badge Badge class and text: Required.
* @param array{href:string,text:string}|null $seen_at The page a conflict was seen on.
* @param array{href:string,text:string,at?:int}|null $text_link A name in the text to link, such as a tool to test with, and where it starts.
+ * @param array{href:string,text:string}|null $fix_link A name in the fix line to link.
* @return array<string, mixed>
*/
- private static function row( string $id, string $state, string $title, string $text, string $fix = '', ?array $link = null, ?array $badge = null, ?array $seen_at = null, ?array $text_link = null ): array {
+ private static function row( string $id, string $state, string $title, string $text, string $fix = '', ?array $link = null, ?array $badge = null, ?array $seen_at = null, ?array $text_link = null, ?array $fix_link = null ): array {
return array(
'id' => $id,
'state' => $state,
@@ -961,17 +962,19 @@ class ReadinessCheckPage implements RegisterHooksInterface {
'link' => $link,
'seen_at' => $seen_at,
'text_link' => $text_link,
+ 'fix_link' => $fix_link,
);
}
/**
* Fix first: the required steps that fail, then the top FIX_FIRST_ISSUES other issues, ranked by
* what they stop (listing, then findability) and, within that, by the share of sales on the
- * products they affect, then by how many products, then in page order.
+ * products they affect, then by how many products, then in page order. Missing barcode numbers
+ * on mostly own-brand products rank after everything else.
*
* @param 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}> $checks Store checks shown on the page.
* @param array<string, mixed> $report Stored report.
- * @return array<int, array{id:string,tier:int,title:string,why:string,link:array{href:string,text:string,sr?:string}|null,share:float|null,store:bool,rank:float,count:int}>
+ * @return array<int, array{id:string,tier:int,title:string,why:string,link:array{href:string,text:string,sr?:string}|null,share:float|null,store:bool,rank:float,count:int,last:bool}>
*/
private function fix_first_items( array $checks, array $report ): array {
$required = array();
@@ -996,6 +999,7 @@ class ReadinessCheckPage implements RegisterHooksInterface {
// A store-wide issue affects every product, so it ranks as all sales.
'rank' => 1.0,
'count' => PHP_INT_MAX,
+ 'last' => false,
);
if ( $is_required ) {
$required[] = $item;
@@ -1023,14 +1027,28 @@ class ReadinessCheckPage implements RegisterHooksInterface {
'store' => false,
'rank' => $rank,
'count' => 0.0 < $rank ? $count : $count * max( 1, $apps ),
+ // A store that makes its own goods needs no barcode numbers for them.
+ 'last' => 'missing_gtin' === ( $check['id'] ?? '' ) && self::mostly_store_brand( (array) ( $check['product_ids'] ?? array() ) ),
);
}
- // Tier first, then the larger share of sales, then more products, then page order (usort isn't stable before PHP 8).
+ // Own-brand barcodes last, then tier, the larger share of sales, more products, and page order (usort isn't stable before PHP 8).
$order = array_flip( array_keys( $issues ) );
- uksort( $issues, static fn( int $a, int $b ): int => array( $issues[ $a ]['tier'], $issues[ $b ]['rank'], $issues[ $b ]['count'], $order[ $a ] ) <=> array( $issues[ $b ]['tier'], $issues[ $a ]['rank'], $issues[ $a ]['count'], $order[ $b ] ) );
+ uksort( $issues, static fn( int $a, int $b ): int => array( $issues[ $a ]['last'], $issues[ $a ]['tier'], $issues[ $b ]['rank'], $issues[ $b ]['count'], $order[ $a ] ) <=> array( $issues[ $b ]['last'], $issues[ $b ]['tier'], $issues[ $a ]['rank'], $issues[ $a ]['count'], $order[ $b ] ) );
return array_merge( $required, array_slice( $issues, 0, self::FIX_FIRST_ISSUES ) );
}
+ /**
+ * Whether more than half of a check's example products (the up to 10 the report lists, still failing)
+ * have the store's name as their brand.
+ *
+ * @param array<int, mixed> $product_ids Example product ids.
+ */
+ private static function mostly_store_brand( array $product_ids ): bool {
+ $products = array_filter( array_map( 'wc_get_product', array_map( 'intval', $product_ids ) ) );
+ $own = array_filter( $products, array( ProductFields::class, 'is_store_brand' ) );
+ return count( $own ) * 2 > count( $products );
+ }
+
/**
* The Fix first card: items under a heading for what each group of issues stops, with a line on
* how it is ranked. Each issue says in bold what it affects. With nothing to fix,
@@ -1193,7 +1211,7 @@ class ReadinessCheckPage implements RegisterHooksInterface {
*
* @param array<string, mixed> $check Failing product check from the report.
* @param bool $linked Whether each product's failures are stored, so a few failing products can be named.
- * @return array{title:string,why:string,fix:string}
+ * @return array{title:string,why:string,fix:string,fix_link:array{href:string,text:string}|null}
*/
private static function product_issue( array $check, bool $linked ): array {
$count = (int) ( $check['count'] ?? 0 );
@@ -1202,15 +1220,17 @@ class ReadinessCheckPage implements RegisterHooksInterface {
$copy = ReadinessCopy::product_check( $id, $count, $names );
if ( null === $copy ) {
return array(
- 'title' => (string) ( $check['label'] ?? '' ),
- 'why' => (string) ( $check['why'] ?? '' ),
- 'fix' => (string) ( $check['fix'] ?? '' ),
+ 'title' => (string) ( $check['label'] ?? '' ),
+ 'why' => (string) ( $check['why'] ?? '' ),
+ 'fix' => (string) ( $check['fix'] ?? '' ),
+ 'fix_link' => null,
);
}
return array(
- 'title' => $copy['action'],
- 'why' => $copy['why'],
- 'fix' => $copy['fix'],
+ 'title' => $copy['action'],
+ 'why' => $copy['why'],
+ 'fix' => $copy['fix'],
+ 'fix_link' => $copy['fix_link'],
);
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCopy.php b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCopy.php
index 9f42c5bac63..ab15c460d44 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCopy.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/ReadinessCopy.php
@@ -21,6 +21,11 @@ final class ReadinessCopy {
*/
public const UCP_PLAYGROUND_URL = 'https://ucpplayground.com/';
+ /**
+ * GS1's page on getting barcode numbers (GTINs), for stores that make their own products.
+ */
+ public const GS1_URL = 'https://www.gs1.org/standards/get-barcodes';
+
/**
* Up to how many failing products a fix title names; more are given as a count.
*/
@@ -200,7 +205,7 @@ final class ReadinessCopy {
* @param string $id Check id.
* @param int $count Number of products.
* @param string[] $names Names of the failing products when known, or none.
- * @return array{action:string,why:string,fix:string}|null Null for a check without copy here.
+ * @return array{action:string,why:string,fix:string,fix_link:array{href:string,text:string}|null}|null Null for a check without copy here. `fix_link` is a name in the fix line to link.
*/
public static function product_check( string $id, int $count, array $names = array() ): ?array {
$n = number_format_i18n( $count );
@@ -210,14 +215,23 @@ final class ReadinessCopy {
/* translators: %s: names of up to three products, such as "Blue hoodie and Red cap", or number of products. */
self::title( $count, $names, _n( 'Add a brand to %s', 'Add a brand to %s', $count, 'woocommerce' ), __( 'Add a brand to a product', 'woocommerce' ), sprintf( _n( 'Add a brand to %s product', 'Add a brand to %s products', $count, 'woocommerce' ), $n ) ),
__( 'ChatGPT only lists products that have a brand. In Google and Copilot, a brand makes products easier to find.', 'woocommerce' ),
- $count > 1 ? __( 'Find them in Products, and add a brand to each one.', 'woocommerce' ) : ''
+ $count > 1 ? __( 'Find them in Products, and add a brand to each one. If you make your own products, use your store name as the brand.', 'woocommerce' ) : __( 'If you make your own products, use your store name as the brand.', 'woocommerce' )
);
case 'missing_gtin':
+ $gs1 = _x( 'GS1', 'organization that issues barcode numbers', 'woocommerce' );
return self::product(
/* translators: %s: names of up to three products, such as "Blue hoodie and Red cap", or number of products. */
self::title( $count, $names, _n( 'Add a barcode number to %s', 'Add barcode numbers to %s', $count, 'woocommerce' ), __( 'Add a barcode number to a product', 'woocommerce' ), sprintf( _n( 'Add a barcode number to %s product', 'Add barcode numbers to %s products', $count, 'woocommerce' ), $n ) ),
__( 'Barcode numbers, like a UPC, EAN, or ISBN, help AI assistants match your products to what shoppers search for.', 'woocommerce' ),
- __( 'Use the number from the packaging or your supplier, not one you create yourself.', 'woocommerce' )
+ sprintf(
+ /* translators: %s: GS1, the organization that issues barcode numbers. */
+ __( 'Use the number from the packaging or your supplier, never one you make up. Barcode numbers are optional for products you make yourself. You can get them from %s.', 'woocommerce' ),
+ $gs1
+ ),
+ array(
+ 'href' => self::GS1_URL,
+ 'text' => $gs1,
+ )
);
case 'invalid_gtin':
return self::product(
@@ -308,16 +322,18 @@ final class ReadinessCopy {
/**
* A product check's copy.
*
- * @param string $action What to do.
- * @param string $why Why it matters.
- * @param string $fix Fix line, or ''.
- * @return array{action:string,why:string,fix:string}
+ * @param string $action What to do.
+ * @param string $why Why it matters.
+ * @param string $fix Fix line, or ''.
+ * @param array{href:string,text:string}|null $fix_link A name in the fix line to link, or null.
+ * @return array{action:string,why:string,fix:string,fix_link:array{href:string,text:string}|null}
*/
- private static function product( string $action, string $why, string $fix = '' ): array {
+ private static function product( string $action, string $why, string $fix = '', ?array $fix_link = null ): array {
return array(
- 'action' => $action,
- 'why' => $why,
- 'fix' => $fix,
+ 'action' => $action,
+ 'why' => $why,
+ 'fix' => $fix,
+ 'fix_link' => $fix_link,
);
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php b/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php
index dff0cafd861..5780ad5d591 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/RunCheckAbility.php
@@ -95,7 +95,11 @@ class RunCheckAbility implements AbilityDefinition {
if ( ! $product instanceof \WC_Product ) {
return new \WP_Error( 'woocommerce_agent_readiness_product_not_found', __( 'Product not found.', 'woocommerce' ), array( 'status' => 404 ) );
}
- $result = $readiness->check_product( $product );
+ try {
+ $result = $readiness->check_product( $product );
+ } catch ( \RuntimeException $exception ) {
+ return new \WP_Error( 'woocommerce_agent_readiness_check_failed', __( 'The product could not be checked. Try again.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
if ( null === $result ) {
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 ) );
}
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
index 61cfe70f6eb..fca78d76035 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreOutputChecks.php
@@ -2059,8 +2059,8 @@ class StoreOutputChecks {
/**
* Whether the page gives the product a valid GTIN, from WooCommerce or any other source. When it doesn't, a
- * failure only when WooCommerce would have printed one, the product's own valid GTIN; otherwise null, since
- * missing_gtin and invalid_gtin report the stored value.
+ * failure only when WooCommerce would have printed one, the product's own valid GTIN field. A barcode kept
+ * only in a plugin field is not printed, so this stays null; missing_gtin passes that product, as it reads the plugin field.
*
* @param array<int, array<string, mixed>> $products Product items.
* @param \WC_Product|null $product The product of the page.
@@ -2074,7 +2074,7 @@ class StoreOutputChecks {
return true;
}
}
- // WooCommerce prints the product's own GTIN on its page, never a variation's.
+ // WooCommerce prints the product's own GTIN field on its page, never a variation's or a barcode plugin's.
$own = (string) preg_replace( '/\D/', '', (string) $product->get_global_unique_id() );
return ProductFields::is_valid_gtin( $own ) ? false : null;
}
diff --git a/plugins/woocommerce/src/Internal/ProductFeed/Mapping/UcpProductMapper.php b/plugins/woocommerce/src/Internal/ProductFeed/Mapping/UcpProductMapper.php
index 7eff6f67a28..4e95684df40 100644
--- a/plugins/woocommerce/src/Internal/ProductFeed/Mapping/UcpProductMapper.php
+++ b/plugins/woocommerce/src/Internal/ProductFeed/Mapping/UcpProductMapper.php
@@ -3,6 +3,7 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Internal\ProductFeed\Mapping;
+use Automattic\WooCommerce\Internal\AgentReadiness\ProductFields;
use Automattic\WooCommerce\StoreApi\Formatters\MoneyFormatter;
use Automattic\WooCommerce\StoreApi\SchemaController;
use Automattic\WooCommerce\StoreApi\Schemas\V1\ProductSchema;
@@ -810,8 +811,10 @@ class UcpProductMapper implements ProductShapeMapperInterface {
}
/**
- * Build a variant's barcodes from its GTIN, normalized and validated by the product structured data,
- * so the catalog and the structured data never disagree on a GTIN.
+ * Build a variant's barcodes from its GTIN, read as AI shopping health reads it (WooCommerce's GTIN
+ * field, else a barcode plugin's). WooCommerce's own GTIN is cleaned and validated as the product
+ * page structured data does, so both print the same value. A plugin's GTIN, which the page does not
+ * print, needs a valid check digit.
*
* A variation's GTIN is its own: the parent's identifies a different item.
*
@@ -823,8 +826,16 @@ class UcpProductMapper implements ProductShapeMapperInterface {
if ( ! $structured_data instanceof \WC_Structured_Data ) {
return array();
}
- $gtin = (string) $structured_data->prepare_gtin( (string) $product->get_global_unique_id() );
- if ( ! $structured_data->is_valid_gtin( $gtin ) ) {
+ // A plugin's value is only stripped of separators, so a value readiness calls invalid is not exported.
+ $own = (string) $product->get_global_unique_id();
+ if ( '' !== ProductFields::normalise_gtin( $own ) ) {
+ $gtin = (string) $structured_data->prepare_gtin( $own );
+ $valid = (bool) $structured_data->is_valid_gtin( $gtin );
+ } else {
+ $gtin = ProductFields::gtin( $product );
+ $valid = ProductFields::is_valid_gtin( $gtin );
+ }
+ if ( ! $valid ) {
return array();
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php
index dda760b8fe4..46deabd6830 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgentReadinessTest.php
@@ -7,6 +7,7 @@ use Automattic\WooCommerce\Internal\AgentReadiness\AgentReadiness;
use Automattic\WooCommerce\Internal\AgentReadiness\ProductScan;
use Automattic\WooCommerce\Internal\AgentReadiness\ReadinessRule;
use Automattic\WooCommerce\Internal\AgentReadiness\RemoteRules;
+use Automattic\WooCommerce\Internal\AgentReadiness\RunCheckAbility;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreConditions;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreOutputChecks;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreResponses;
@@ -395,7 +396,7 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
delete_post_meta( $second_id, '_global_unique_id' );
$queries = 0;
$count = static function ( $query ) use ( &$queries ) {
- $queries += false !== strpos( (string) $query, 'HAVING COUNT(*) > 1' ) ? 1 : 0;
+ $queries += false !== strpos( (string) $query, "pm.meta_key IN ( '_global_unique_id'" ) ? 1 : 0;
return $query;
};
add_filter( 'query', $count );
@@ -406,6 +407,38 @@ class AgentReadinessTest extends WC_Unit_Test_Case {
$this->assertSame( 0, $queries );
}
+ /**
+ * @testdox When the shared-barcode lookup fails, checking one product throws, failing check ids still come back, and the run-check ability returns an error.
+ */
+ public function test_failed_shared_barcode_lookup(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $product->set_global_unique_id( '4006381333931' );
+ $product->save();
+ delete_option( AgentReadiness::REPORT_OPTION );
+
+ $fail = static function ( $query ) {
+ return is_string( $query ) && false !== strpos( $query, "pm.meta_key IN ( '_global_unique_id'" ) ? 'SELECT 1 FROM wc_ar_missing_gtin_table' : $query;
+ };
+ add_filter( 'query', $fail );
+ global $wpdb;
+ $suppress = $wpdb->suppress_errors( true );
+ try {
+ $ids = $this->sut->get_failing_check_ids( $product );
+ $this->assertContains( 'missing_images', $ids, 'The other checks still run' );
+ $this->assertNotContains( 'duplicate_gtin', $ids );
+
+ $error = RunCheckAbility::execute( array( 'product_id' => $product->get_id() ) );
+ $this->assertInstanceOf( \WP_Error::class, $error );
+ $this->assertSame( 'woocommerce_agent_readiness_check_failed', $error->get_error_code() );
+
+ $this->expectException( \RuntimeException::class );
+ $this->sut->check_product( $product );
+ } finally {
+ remove_filter( 'query', $fail );
+ $wpdb->suppress_errors( $suppress );
+ }
+ }
+
/**
* @testdox Hidden products and unsupported types are counted, not checked; search-only and shop-only products are checked.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
index c882fdafa19..341b4ff23e8 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
@@ -1244,6 +1244,76 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
$this->assertSame( array( 'missing_images', 'missing_brand' ), array_column( $this->view()['fix_first']['items'], 'id' ), '3 products in 3 apps come before 5 products in 1' );
}
+ /**
+ * @testdox Missing barcode numbers rank after every other issue in Fix first when most of their example products have the store name as brand, and still show when nothing else is left.
+ */
+ public function test_output_fix_first_ranks_own_brand_barcodes_last(): void {
+ $this->make_every_step_pass();
+ $name = get_option( 'blogname' );
+ update_option( 'blogname', 'Hill Roasters' );
+ $ids = array();
+ foreach ( array( 'hill roasters', 'Hill Roasters', 'Acme' ) as $brand ) {
+ $product = WC_Helper_Product::create_simple_product();
+ wp_set_object_terms( $product->get_id(), $brand, 'product_brand' );
+ $ids[] = $product->get_id();
+ }
+ $check = static fn( string $id, int $count, float $share, string $effect, array $product_ids = array() ): array => array(
+ 'id' => $id,
+ 'label' => $id . ' label',
+ 'why' => $id . ' why.',
+ 'fix' => $id . ' fix.',
+ 'channels' => array(
+ 'chatgpt' => array(
+ 'field' => 'field',
+ 'effect' => $effect,
+ ),
+ ),
+ 'count' => $count,
+ 'product_ids' => $product_ids,
+ 'sales_share' => $share,
+ );
+ $report = static fn( array $gtin_ids, bool $others = true ): array => array(
+ 'generated_at' => gmdate( 'c' ),
+ 'products' => 40,
+ 'store_checks' => array(),
+ 'channels' => array(),
+ 'checks' => array_merge(
+ array( $check( 'missing_gtin', 30, 0.9, ReadinessRule::EFFECT_GAPS, $gtin_ids ) ),
+ $others ? array(
+ $check( 'missing_images', 1, 0.02, ReadinessRule::EFFECT_NOT_LISTABLE ),
+ $check( 'uncategorised', 2, 0.05, ReadinessRule::EFFECT_GAPS ),
+ $check( 'title_too_long', 1, 0.01, ReadinessRule::EFFECT_GAPS ),
+ ) : array()
+ ),
+ 'sales' => array(
+ 'days' => 90,
+ 'orders' => 30,
+ ),
+ );
+ $ranked = fn(): array => array_column( $this->view()['fix_first']['items'], 'id' );
+
+ try {
+ update_option( AgentReadiness::REPORT_OPTION, $report( array( $ids[2] ) ) );
+ $this->assertSame( array( 'missing_images', 'missing_gtin', 'uncategorised' ), $ranked(), 'Another brand: barcodes rank by their share of sales' );
+
+ update_option( AgentReadiness::REPORT_OPTION, $report( array( $ids[0], $ids[2] ) ) );
+ $this->assertSame( array( 'missing_images', 'missing_gtin', 'uncategorised' ), $ranked(), 'Half the examples are the store brand: not most, so the rank stays' );
+
+ update_option( AgentReadiness::REPORT_OPTION, $report( $ids ) );
+ $this->assertSame( array( 'missing_images', 'uncategorised', 'title_too_long' ), $ranked(), 'Most examples are the store brand: barcodes rank after every other issue, here out of the top 3' );
+ $row = array_column( array_column( $this->view()['sections'], null, 'id' )['products']['rows'], null, 'id' )['missing_gtin'] ?? null;
+ $this->assertNotNull( $row, 'The check still reports on its card' );
+ $this->assertSame( ReadinessCopy::GS1_URL, $row['fix_link']['href'], 'Its fix line links GS1' );
+
+ update_option( AgentReadiness::REPORT_OPTION, $report( $ids, false ) );
+ $fix_first = $this->view()['fix_first'];
+ $this->assertSame( array( 'missing_gtin' ), array_column( $fix_first['items'], 'id' ), 'With nothing else to fix, barcodes still show' );
+ $this->assertSame( 'Helps shoppers find products', $fix_first['items'][0]['tier'] );
+ } finally {
+ update_option( 'blogname', $name );
+ }
+ }
+
/**
* @testdox Fix first lists the failing required steps, then the top 3 issues: what keeps products off a channel, then what makes them harder to find, each ranked by its share of sales.
*/
@@ -1760,7 +1830,7 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
$this->assertNotNull( $view['fix_first'], 'When it last ran, Fix first, then a card per question' );
$brand = $this->row( 'Add a brand to ' . $product->get_name() );
$this->assertSame( 'ChatGPT only lists products that have a brand. In Google and Copilot, a brand makes products easier to find.', $brand['text'], 'One failing product is named in the title; the text says why a brand matters' );
- $this->assertSame( '', $brand['fix'], 'Adding a brand needs no fix line' );
+ $this->assertSame( 'If you make your own products, use your store name as the brand.', $brand['fix'], 'One product needs no where-to-find line, only what to use as the brand when the store makes it' );
$this->assertStringNotContainsString( 'Required by', $json );
$this->assertStringNotContainsString( 'Harder to find on', $json, 'Only channels that can\'t list the product are tagged' );
$this->assertSame( 'View product', $brand['link']['text'], 'One product, as in the design' );
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
index 7569ace58c1..5898866f1f8 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ProductsListTest.php
@@ -133,6 +133,27 @@ class ProductsListTest extends WC_Unit_Test_Case {
$this->assertSame( array(), ProductFailures::for_product( $product->get_id() ) );
}
+ /**
+ * @testdox A stock save is still skipped when a plugin filters how a barcode field reads.
+ */
+ public function test_stock_save_is_skipped_with_filtered_meta(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ update_post_meta( $product->get_id(), '_alg_ean', '04006381333931' );
+ $this->readiness->refresh_report();
+ $product = wc_get_product( $product->get_id() );
+ delete_post_meta( $product->get_id(), ProductFailures::META_KEY );
+ $trim = static fn( $value ) => ltrim( (string) $value, '0' );
+ add_filter( 'woocommerce_product_get__alg_ean', $trim );
+ try {
+ $product->set_stock_quantity( 7 );
+ $product->save();
+ } finally {
+ remove_filter( 'woocommerce_product_get__alg_ean', $trim );
+ }
+
+ $this->assertSame( array(), ProductFailures::for_product( $product->get_id() ) );
+ }
+
/**
* @testdox A save that changes only the Google brand or MPN tests the product again.
*/
@@ -154,6 +175,91 @@ class ProductsListTest extends WC_Unit_Test_Case {
$this->assertContains( 'missing_images', ProductFailures::for_product( $product->get_id() ), 'Stock plus MPN is not a stock-only save' );
}
+ /**
+ * @testdox A save keeps the stored result when the shared-barcode lookup fails.
+ */
+ public function test_save_keeps_rows_when_shared_barcode_lookup_fails(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $product->set_global_unique_id( '4006381333931' );
+ $product->save();
+ $this->readiness->refresh_report();
+ $before = ProductFailures::for_product( $product->get_id() );
+ $this->assertContains( 'missing_images', $before );
+
+ $stored = get_option( AgentReadiness::REPORT_OPTION );
+ unset( $stored['shared_gtins'] );
+ update_option( AgentReadiness::REPORT_OPTION, $stored, false );
+
+ // The hooked list may hold a readiness service from an earlier container, with its lookups cached.
+ remove_all_actions( 'woocommerce_after_product_object_save' );
+ add_action( 'woocommerce_after_product_object_save', array( $this->sut, 'handle_after_save' ) );
+
+ $failed = false;
+ $fail = static function ( $query ) use ( &$failed ) {
+ if ( is_string( $query ) && false !== strpos( $query, "pm.meta_key IN ( '_global_unique_id'" ) ) {
+ $failed = true;
+ return 'SELECT 1 FROM wc_ar_missing_gtin_table';
+ }
+ return $query;
+ };
+ add_filter( 'query', $fail );
+ global $wpdb;
+ $suppress = $wpdb->suppress_errors( true );
+ try {
+ $product->set_name( 'Still saved' );
+ // Would clear missing_images if the product were tested again.
+ $product->set_image_id( $this->factory->attachment->create_upload_object( DIR_TESTDATA . '/images/canola.jpg' ) );
+ $product->save();
+ } finally {
+ remove_filter( 'query', $fail );
+ $wpdb->suppress_errors( $suppress );
+ }
+
+ $this->assertTrue( $failed, 'The save reached the shared-barcode lookup' );
+ $this->assertSame( 'Still saved', wc_get_product( $product->get_id() )->get_name() );
+ $this->assertSame( $before, ProductFailures::for_product( $product->get_id() ) );
+ }
+
+ /**
+ * @testdox A save that changes only a barcode plugin's GTIN tests the product again.
+ */
+ public function test_barcode_plugin_gtin_save_is_rechecked(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $this->readiness->refresh_report();
+ $this->assertContains( 'missing_gtin', ProductFailures::for_product( $product->get_id() ) );
+
+ $product->update_meta_data( '_alg_ean', '4006381333931' );
+ $product->save();
+
+ $this->assertNotContains( 'missing_gtin', ProductFailures::for_product( $product->get_id() ) );
+ }
+
+ /**
+ * @testdox A barcode plugin field written outside a product save, on the product or a variation, is tested at the end of the request, once.
+ */
+ public function test_barcode_plugin_meta_write_is_rechecked(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $variable = WC_Helper_Product::create_variation_product();
+ $this->readiness->refresh_report();
+ $this->assertContains( 'missing_gtin', ProductFailures::for_product( $product->get_id() ) );
+ $this->assertContains( 'missing_gtin', ProductFailures::for_product( $variable->get_id() ) );
+
+ update_post_meta( $product->get_id(), '_alg_ean', '4006381333931' );
+ foreach ( $variable->get_children() as $child_id ) {
+ update_post_meta( $child_id, '_ts_gtin', '9780306406157' );
+ }
+ $this->assertContains( 'missing_gtin', ProductFailures::for_product( $product->get_id() ), 'Tested at the end of the request' );
+
+ $this->run_retest();
+
+ $this->assertNotContains( 'missing_gtin', ProductFailures::for_product( $product->get_id() ) );
+ $this->assertNotContains( 'missing_gtin', ProductFailures::for_product( $variable->get_id() ) );
+
+ delete_post_meta( $product->get_id(), '_alg_ean' );
+ $this->run_retest();
+ $this->assertContains( 'missing_gtin', ProductFailures::for_product( $product->get_id() ), 'Removing the field is tested too' );
+ }
+
/**
* @testdox A save that changes nothing doesn't test the product again.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php
index 41fd3d3b341..5dd3fc04b6f 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php
@@ -186,6 +186,43 @@ class ReadinessChecksTest extends WC_Unit_Test_Case {
$this->assertArrayHasKey( FeedChannels::CHATGPT, $channels );
}
+ /**
+ * @testdox A product's brand is the store's when it matches the store name, ignoring case, extra spaces and entities; several brands, another brand, none, or a store with no name don't match.
+ */
+ public function test_is_store_brand(): void {
+ $name = get_option( 'blogname' );
+ update_option( 'blogname', 'Hill & Vale Roasters' );
+ try {
+ $product = WC_Helper_Product::create_simple_product();
+ $this->assertFalse( ProductFields::is_store_brand( $product ), 'No brand' );
+
+ wp_set_object_terms( $product->get_id(), ' hill & vale roasters ', 'product_brand' );
+ $this->assertTrue( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'Case, spaces and entities differ' );
+
+ wp_set_object_terms( $product->get_id(), array( 'Hill & Vale Roasters', 'Acme' ), 'product_brand' );
+ $this->assertFalse( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'Several brands' );
+
+ wp_set_object_terms( $product->get_id(), 'Acme', 'product_brand' );
+ $this->assertFalse( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'Another brand' );
+
+ update_option( 'blogname', 'Acme' );
+ wp_set_object_terms( $product->get_id(), 'Acme [gallery]', 'product_brand' );
+ $this->assertFalse( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'Shortcode-like text is part of the brand name' );
+
+ update_option( 'blogname', 'Salt, Pepper' );
+ wp_set_object_terms( $product->get_id(), array( 'Salt', 'Pepper' ), 'product_brand' );
+ $this->assertFalse( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'Two brands joined with a comma are not one brand' );
+ wp_set_object_terms( $product->get_id(), 'Salt, Pepper', 'product_brand' );
+ $this->assertTrue( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'One brand whose name contains a comma' );
+
+ update_option( 'blogname', '' );
+ wp_set_object_terms( $product->get_id(), array(), 'product_brand' );
+ $this->assertFalse( ProductFields::is_store_brand( wc_get_product( $product->get_id() ) ), 'No store name and no brand' );
+ } finally {
+ update_option( 'blogname', $name );
+ }
+ }
+
/**
* @testdox A variable product fails when any published variation lacks its own GTIN; the parent needs none, and virtual or disabled variations are skipped.
*/
@@ -329,6 +366,310 @@ class ReadinessChecksTest extends WC_Unit_Test_Case {
}
}
+ /**
+ * @testdox The duplicate check compares stored GTINs, as the scan does, not a value a filter puts on the GTIN or a barcode plugin field.
+ */
+ public function test_duplicate_gtin_reads_stored_values(): void {
+ $first = WC_Helper_Product::create_simple_product();
+ $second = WC_Helper_Product::create_simple_product();
+ update_post_meta( $first->get_id(), '_alg_ean', '4006381333931' );
+ update_post_meta( $second->get_id(), '_alg_ean', '4006381333931' );
+ $first_id = $first->get_id();
+ $filter = static function ( $gtin, $product ) use ( $first_id ) {
+ return $product instanceof \WC_Product && $product->get_id() === $first_id ? '036000291452' : $gtin;
+ };
+ $sut = new DuplicateGtinCheck();
+ foreach ( array( 'woocommerce_product_get_global_unique_id', 'woocommerce_product_get__alg_ean' ) as $hook ) {
+ add_filter( $hook, $filter, 10, 2 );
+ try {
+ $this->assertTrue( $sut->fails( wc_get_product( $first_id ), new ProductScan() ), "The first product stores the shared GTIN ($hook)" );
+ $this->assertTrue( $sut->fails( wc_get_product( $second->get_id() ), new ProductScan() ), "The second product stores the shared GTIN ($hook)" );
+ } finally {
+ remove_filter( $hook, $filter, 10 );
+ }
+ }
+ }
+
+ /**
+ * @testdox Shared GTINs are the ones the MySQL query with TRIM( LEADING '0' ) found: leading zeros and separators ignored, one owner per variable product, unpublished products and variations left out, barcode plugin fields read in order.
+ */
+ public function test_shared_gtins_match_the_mysql_query(): void {
+ global $wpdb;
+ $set = static function ( int $id, string $gtin ): void {
+ update_post_meta( $id, '_global_unique_id', $gtin );
+ };
+ $simple = static fn( string $status = 'publish' ): int => WC_Helper_Product::create_simple_product( true, array( 'status' => $status ) )->get_id();
+
+ // One GTIN on three products, written with a leading zero and with separators.
+ $set( $simple(), '4006381333931' );
+ $set( $simple(), '04006381333931' );
+ $set( $simple(), "4006-381\u{00A0}333931" );
+ // A no-break space only.
+ $set( $simple(), "\u{202F}12345601" );
+ $set( $simple(), '12345601' );
+ // A variable product and its variations with one GTIN: one owner.
+ $variable = WC_Helper_Product::create_variation_product();
+ $set( $variable->get_id(), '036000291452' );
+ foreach ( $variable->get_children() as $child_id ) {
+ $set( $child_id, '0036000291452' );
+ }
+ // A draft product, and a variation of a draft parent, don't count.
+ $set( $simple(), '96385074' );
+ $set( $simple( 'draft' ), '96385074' );
+ $draft = WC_Helper_Product::create_variation_product();
+ wp_update_post(
+ array(
+ 'ID' => $draft->get_id(),
+ 'post_status' => 'draft',
+ )
+ );
+ $set( $draft->get_children()[0], '12345670' );
+ $set( $simple(), '12345670' );
+ // A disabled variation of a published parent doesn't count.
+ $disabled = WC_Helper_Product::create_variation_product();
+ $hidden = $disabled->get_children()[0];
+ wp_update_post(
+ array(
+ 'ID' => $hidden,
+ 'post_status' => 'private',
+ )
+ );
+ $set( $hidden, '55123457' );
+ $set( $simple(), '55123457' );
+ // Barcode plugin fields: one GTIN in three plugins' fields, and a plugin value
+ // behind a filled WooCommerce field that is not read.
+ update_post_meta( $simple(), '_alg_ean', '73513537' );
+ update_post_meta( $simple(), '_ts_gtin', '0073513537' );
+ $behind = $simple();
+ $set( $behind, ' ' );
+ update_post_meta( $behind, '_wc_gla_gtin', '73513537' );
+ $hides = $simple();
+ $set( $hides, '50000003' );
+ update_post_meta( $hides, '_wc_gla_gtin', '96385074' );
+
+ $saw = false;
+ $marked = static function ( $query ) use ( &$saw ) {
+ $saw = $saw || false !== strpos( (string) $query, "pm.meta_key IN ( '_global_unique_id'" );
+ return $query;
+ };
+ add_filter( 'query', $marked );
+ $found = ( new ProductScan() )->shared_gtins();
+ remove_filter( 'query', $marked );
+ $this->assertTrue( $saw, 'The catalog query is the one a stored scan is checked against' );
+ sort( $found );
+ $this->assertSame( array( '12345601', '73513537', '4006381333931' ), $found );
+ if ( ! empty( $wpdb->is_mysql ) ) {
+ $this->assertSame( $this->shared_gtins_by_mysql(), $found, 'Same result as the query this replaced' );
+ }
+
+ // Two rows per batch, so the shared GTINs span batches.
+ $small = static fn( $query ) => str_replace( 'LIMIT ' . ProductScan::GTIN_BATCH, 'LIMIT 2', (string) $query );
+ add_filter( 'query', $small );
+ $batched = ( new ProductScan() )->shared_gtins();
+ remove_filter( 'query', $small );
+ sort( $batched );
+ $this->assertSame( $found, $batched, 'Read in small batches' );
+ }
+
+ /**
+ * @testdox A shared barcode follows gtin(): the first row of a field, and a scalar value. A failed page is not kept.
+ */
+ public function test_shared_gtins_follow_the_product_gtin(): void {
+ $simple = static fn(): int => WC_Helper_Product::create_simple_product()->get_id();
+
+ $empty_first = $simple();
+ add_post_meta( $empty_first, '_alg_ean', '' );
+ add_post_meta( $empty_first, '_alg_ean', '4006381333931' );
+ update_post_meta( $empty_first, '_ts_gtin', '73513537' );
+ update_post_meta( $simple(), '_alg_ean', '4006381333931' );
+
+ $serialized = $simple();
+ update_post_meta( $serialized, '_alg_ean', array( '96385074' ) );
+ update_post_meta( $serialized, '_ts_gtin', '12345601' );
+ update_post_meta( $simple(), '_global_unique_id', '96385074' );
+ update_post_meta( $simple(), '_ts_gtin', '12345601' );
+
+ $found = ( new ProductScan() )->shared_gtins();
+ $this->assertSame( array( '12345601' ), $found, 'An empty first row and a non-scalar value are skipped for the next field, as gtin() does' );
+
+ $fail = static function ( $query ) {
+ return is_string( $query ) && false !== strpos( $query, "pm.meta_key IN ( '_global_unique_id'" )
+ ? 'SELECT 1 FROM wc_ar_missing_gtin_table'
+ : $query;
+ };
+ add_filter( 'query', $fail );
+ global $wpdb;
+ $suppress = $wpdb->suppress_errors( true );
+ $scan = new ProductScan();
+ try {
+ $scan->shared_gtins();
+ $this->fail( 'A failed page was stored as the whole catalog' );
+ } catch ( \RuntimeException $exception ) {
+ $this->assertStringContainsString( 'shared barcodes', $exception->getMessage() );
+ } finally {
+ remove_filter( 'query', $fail );
+ $wpdb->suppress_errors( $suppress );
+ }
+
+ $saw = false;
+ $mark = static function ( $query ) use ( &$saw ) {
+ $saw = $saw || ( is_string( $query ) && false !== strpos( $query, "pm.meta_key IN ( '_global_unique_id'" ) );
+ return $query;
+ };
+ add_filter( 'query', $mark );
+ $again = $scan->shared_gtins();
+ remove_filter( 'query', $mark );
+ $this->assertTrue( $saw, 'The lookup runs again instead of reusing the failed page' );
+ $this->assertSame( array( '12345601' ), $again );
+ }
+
+ /**
+ * @testdox A shared barcode ignores placeholders, and reads WooCommerce's GTIN field as the product does, so junk in it falls back to a plugin field.
+ */
+ public function test_shared_gtins_skip_placeholders_and_clean_the_core_field(): void {
+ $simple = static fn(): int => WC_Helper_Product::create_simple_product()->get_id();
+ $dup = new DuplicateGtinCheck();
+
+ $placeholders = array();
+ foreach ( array( 'N/A', 'n/a', '0', '00' ) as $value ) {
+ $placeholders[] = $simple();
+ update_post_meta( end( $placeholders ), '_alg_ean', $value );
+ }
+
+ $junk = $simple();
+ update_post_meta( $junk, '_global_unique_id', 'n/a' );
+ update_post_meta( $junk, '_alg_ean', '4006381333931' );
+ update_post_meta( $simple(), '_global_unique_id', '4006381333931' );
+ $quoted = $simple();
+ update_post_meta( $quoted, '_global_unique_id', "'036000291452" );
+ update_post_meta( $simple(), '_global_unique_id', '036000291452' );
+
+ $scan = new ProductScan();
+ $found = $scan->shared_gtins();
+ sort( $found );
+ $this->assertSame( array( '36000291452', '4006381333931' ), $found );
+ $this->assertSame( '4006381333931', ProductFields::gtin( wc_get_product( $junk ), 'edit' ), 'The product reads the plugin field past the junk' );
+ $this->assertTrue( $dup->fails( wc_get_product( $junk ), $scan ) );
+ $this->assertTrue( $dup->fails( wc_get_product( $quoted ), $scan ) );
+ foreach ( $placeholders as $id ) {
+ $this->assertFalse( $dup->fails( wc_get_product( $id ), $scan ), 'A placeholder is not a shared barcode' );
+ }
+ }
+
+ /**
+ * Shared GTINs as the earlier MySQL query found them, barcode plugin fields included, with TRIM( LEADING '0' ), which SQLite can't run.
+ *
+ * @return array<int, string>
+ */
+ private function shared_gtins_by_mysql(): array {
+ global $wpdb;
+ $normalise = static function ( string $column ): string {
+ foreach ( ProductFields::GTIN_SEPARATORS as $separator ) {
+ $column = "REPLACE( {$column}, _utf8mb4 X'" . bin2hex( $separator ) . "', '' )";
+ }
+ return $column;
+ };
+ $value = $normalise( 'pm.meta_value' );
+ $earlier = $normalise( 'earlier.meta_value' );
+ $keys = array_merge( array( '_global_unique_id' ), ProductFields::GTIN_PLUGIN_META_KEYS );
+ $in = implode( ', ', array_fill( 0, count( $keys ), '%s' ) );
+ $order = static function ( string $column ) use ( $keys, $wpdb ): string {
+ $cases = '';
+ foreach ( $keys as $position => $key ) {
+ $cases .= $wpdb->prepare( ' WHEN %s THEN %d', $key, $position );
+ }
+ return "CASE {$column}{$cases} END";
+ };
+ $earlier_order = $order( 'earlier.meta_key' );
+ $value_order = $order( 'pm.meta_key' );
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.DirectDatabaseQuery
+ $gtins = $wpdb->get_col(
+ $wpdb->prepare(
+ "
+ SELECT owned.gtin
+ FROM (
+ SELECT DISTINCT IF( p.post_type = %s, p.post_parent, p.ID ) AS owner_id,
+ TRIM( LEADING '0' FROM {$value} ) AS gtin
+ FROM {$wpdb->postmeta} pm
+ INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
+ INNER JOIN {$wpdb->posts} owner ON owner.ID = IF( p.post_type = %s, p.post_parent, p.ID )
+ WHERE pm.meta_key IN ( {$in} )
+ AND {$value} != ''
+ AND NOT EXISTS (
+ SELECT 1 FROM {$wpdb->postmeta} earlier
+ WHERE earlier.post_id = pm.post_id
+ AND earlier.meta_key IN ( {$in} )
+ AND {$earlier_order} < {$value_order}
+ AND {$earlier} != ''
+ )
+ AND p.post_type IN ( %s, %s )
+ AND p.post_status = %s
+ AND owner.post_status = %s
+ ) owned
+ GROUP BY owned.gtin
+ HAVING COUNT(*) > 1
+ ",
+ array_merge(
+ array( 'product_variation', 'product_variation' ),
+ $keys,
+ $keys,
+ array( 'product', 'product_variation', 'publish', 'publish' )
+ )
+ )
+ );
+ // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.DirectDatabaseQuery
+ $gtins = array_map( 'strval', (array) $gtins );
+ sort( $gtins );
+ return $gtins;
+ }
+
+ /**
+ * @testdox A GTIN from a barcode plugin counts in the missing, invalid and duplicate checks; WooCommerce's GTIN field is read first.
+ */
+ public function test_barcode_plugin_gtins_count_in_every_gtin_check(): void {
+ $missing = new MissingGtinCheck();
+ $invalid = SimpleCheck::table()['invalid_gtin'];
+ $duplicate = new DuplicateGtinCheck();
+
+ $ean = WC_Helper_Product::create_simple_product();
+ update_post_meta( $ean->get_id(), '_alg_ean', '4006381333931' );
+ $ean = wc_get_product( $ean->get_id() );
+
+ $variable = WC_Helper_Product::create_variation_product();
+ $valid = array( '12345601', '12345618', '12345625', '12345632', '12345649', '12345656', '12345663', '12345670' );
+ foreach ( array_values( $variable->get_children() ) as $i => $child_id ) {
+ update_post_meta( $child_id, '_ts_gtin', $valid[ $i ] );
+ }
+ ProductFields::forget_variations( $variable->get_id() );
+ $variable = wc_get_product( $variable->get_id() );
+
+ $google = WC_Helper_Product::create_simple_product();
+ update_post_meta( $google->get_id(), '_wc_gla_gtin', '4006381333932' );
+ $google = wc_get_product( $google->get_id() );
+
+ // Same EAN as $ean, in WooCommerce's field, plus an older plugin value that is not read.
+ $core = WC_Helper_Product::create_simple_product();
+ update_post_meta( $core->get_id(), '_global_unique_id', '04006381333931' );
+ update_post_meta( $core->get_id(), '_alg_ean', '036000291452' );
+ $core = wc_get_product( $core->get_id() );
+ $other = WC_Helper_Product::create_simple_product();
+ update_post_meta( $other->get_id(), '_global_unique_id', '036000291452' );
+ $other = wc_get_product( $other->get_id() );
+
+ $scan = new ProductScan();
+ $this->assertSame( '4006381333931', ProductFields::gtin( $ean ) );
+ $this->assertSame( '04006381333931', ProductFields::gtin( $core ), 'WooCommerce\'s GTIN field is read first' );
+ $this->assertFalse( $missing->fails( $ean, $scan ), 'An EAN for WooCommerce GTIN is a GTIN' );
+ $this->assertFalse( $invalid->fails( $ean, $scan ) );
+ $this->assertFalse( $missing->fails( $variable, $scan ), 'Germanized GTINs on each variation' );
+ $this->assertFalse( $invalid->fails( $variable, $scan ) );
+ $this->assertFalse( $missing->fails( $google, $scan ) );
+ $this->assertTrue( $invalid->fails( $google, $scan ), 'A Google for WooCommerce GTIN with a wrong check digit' );
+ $this->assertTrue( $duplicate->fails( $ean, $scan ), 'The plugin GTIN is shared with another product\'s GTIN field' );
+ $this->assertTrue( $duplicate->fails( $core, $scan ) );
+ $this->assertFalse( $duplicate->fails( $other, $scan ), 'A plugin value behind a filled GTIN field is not read, so it shares nothing' );
+ }
+
/**
* @testdox A small main image is a gap on Google before January 31, 2027 and required from then.
*
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessCopyTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessCopyTest.php
index 604cca53256..f24521d685c 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessCopyTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessCopyTest.php
@@ -139,11 +139,22 @@ class ReadinessCopyTest extends WC_Unit_Test_Case {
}
/**
- * @testdox The brand fix says where to find the products only when there are several.
+ * @testdox The brand fix says where to find the products only when there are several, and always tells stores that make their own products to use the store name.
*/
public function test_brand_fix_only_for_several_products(): void {
- $this->assertSame( 'Find them in Products, and add a brand to each one.', ReadinessCopy::product_check( 'missing_brand', 3 )['fix'] );
- $this->assertSame( '', ReadinessCopy::product_check( 'missing_brand', 1 )['fix'] ?? '' );
+ $this->assertSame( 'Find them in Products, and add a brand to each one. If you make your own products, use your store name as the brand.', ReadinessCopy::product_check( 'missing_brand', 3 )['fix'] );
+ $this->assertSame( 'If you make your own products, use your store name as the brand.', ReadinessCopy::product_check( 'missing_brand', 1 )['fix'] );
+ }
+
+ /**
+ * @testdox The barcode fix says barcode numbers are optional for products the store makes, and links GS1 in that line.
+ */
+ public function test_gtin_fix_links_gs1(): void {
+ $copy = ReadinessCopy::product_check( 'missing_gtin', 2 );
+ $this->assertSame( 'Use the number from the packaging or your supplier, never one you make up. Barcode numbers are optional for products you make yourself. You can get them from GS1.', $copy['fix'] );
+ $this->assertSame( ReadinessCopy::GS1_URL, $copy['fix_link']['href'] );
+ $this->assertStringContainsString( $copy['fix_link']['text'], $copy['fix'], 'The linked name is in the fix line' );
+ $this->assertNull( ReadinessCopy::product_check( 'missing_brand', 2 )['fix_link'], 'Other checks link nothing in their fix line' );
}
/**
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php
index bf7b557f66b..75ce0b6cd40 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreOutputChecksTest.php
@@ -4,7 +4,9 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;
use Automattic\WooCommerce\Enums\ProductStockStatus;
+use Automattic\WooCommerce\Internal\AgentReadiness\Checks\MissingGtinCheck;
use Automattic\WooCommerce\Internal\AgentReadiness\JsonLd;
+use Automattic\WooCommerce\Internal\AgentReadiness\ProductScan;
use Automattic\WooCommerce\Internal\AgentReadiness\RemoteRules;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreOutputChecks;
use Automattic\WooCommerce\Internal\AgentReadiness\StoreResponses;
@@ -1217,6 +1219,26 @@ class StoreOutputChecksTest extends WC_Unit_Test_Case {
$this->assertNull( $this->served_identifiers( $product, array( $plugin ) )['gtin'], 'A virtual product needs no GTIN' );
}
+ /**
+ * @testdox A GTIN kept by a barcode plugin counts in missing_gtin. The page check passes when the page prints it, and stays skipped when WooCommerce's GTIN field is empty.
+ */
+ public function test_served_gtin_from_a_barcode_plugin(): void {
+ $product = WC_Helper_Product::create_simple_product();
+ $product->update_meta_data( '_alg_ean', '4006381333931' );
+ $product->save();
+ $plugin = array(
+ '@type' => 'Product',
+ 'name' => $product->get_name(),
+ );
+
+ $this->assertTrue( $this->served_identifiers( $product, array( $plugin + array( 'gtin13' => '4006381333931' ) ) )['gtin'], 'The plugin prints its GTIN' );
+ $this->assertFalse( ( new MissingGtinCheck() )->fails( $product, new ProductScan() ), 'The same GTIN counts in missing_gtin' );
+
+ $missing = $this->served_identifiers( $product, array( $plugin ) );
+ $this->assertNull( $missing['gtin'], 'WooCommerce would not have printed a plugin field' );
+ $this->assertFalse( $missing['gtin_conflict'] );
+ }
+
/**
* @testdox The brand check passes when the page gives a brand from any source, and fails only when the product has a WooCommerce brand the page doesn't give.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/ProductFeed/Mapping/UcpProductMapperTest.php b/plugins/woocommerce/tests/php/src/Internal/ProductFeed/Mapping/UcpProductMapperTest.php
index 6d396a9a946..43bfd4e264d 100644
--- a/plugins/woocommerce/tests/php/src/Internal/ProductFeed/Mapping/UcpProductMapperTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/ProductFeed/Mapping/UcpProductMapperTest.php
@@ -424,12 +424,42 @@ class UcpProductMapperTest extends \WC_Unit_Test_Case {
$mapper->map_product( $product )['variants'][0]['barcodes']
);
+ $product->set_global_unique_id( '4006381333932' );
+ $product->save();
+
+ $this->assertSame( '4006381333932', $mapper->map_product( $product )['variants'][0]['barcodes'][0]['value'], 'WooCommerce\'s own GTIN is sent as the product page prints it, check digit or not' );
+
$product->set_global_unique_id( '12345' );
$product->save();
$this->assertArrayNotHasKey( 'barcodes', $mapper->map_product( $product )['variants'][0] );
}
+ /**
+ * @testdox A GTIN kept by a barcode plugin should be sent when WooCommerce's GTIN field is empty, and WooCommerce's should win when both are set.
+ */
+ public function test_barcode_plugin_gtin_is_sent(): void {
+ $mapper = new UcpProductMapper( 'USD' );
+ $product = WC_Helper_Product::create_simple_product();
+ $product->update_meta_data( '_alg_ean', '4006381333931' );
+ $product->save();
+
+ $this->assertSame( '4006381333931', $mapper->map_product( $product )['variants'][0]['barcodes'][0]['value'] );
+
+ $product->update_meta_data( '_alg_ean', '4006381333932' );
+ $product->save();
+ $this->assertArrayNotHasKey( 'barcodes', $mapper->map_product( $product )['variants'][0], 'A plugin barcode with a bad check digit is left out' );
+
+ $product->update_meta_data( '_alg_ean', 'EAN:4006381333931' );
+ $product->save();
+ $this->assertArrayNotHasKey( 'barcodes', $mapper->map_product( $product )['variants'][0], 'A plugin barcode with letters is left out, as readiness calls it invalid' );
+
+ $product->set_global_unique_id( '036000291452' );
+ $product->save();
+
+ $this->assertSame( '036000291452', $mapper->map_product( $product )['variants'][0]['barcodes'][0]['value'] );
+ }
+
/**
* @testdox Each variation should send its own GTIN, not the parent's.
*/