Commit 7ee176e37d9 for woocommerce
commit 7ee176e37d9ec59cab8d1ac867f9ab909c3fdbdc
Author: Sam Najian <dev@najian.info>
Date: Fri Dec 4 18:18:30 2026 +0100
Fix currency mapping in HPOS legacy reports (#71849)
* Fix currency mapping in HPOS legacy reports
* Add changelog entry for HPOS report currency
* Fix legacy currency references in HPOS report clauses
* Derive report money formatting from the HPOS column maps
The money keys were a hard-coded list that duplicated the column maps, so a newly mapped money column would have lost the legacy rounding.
* Address review feedback on #71849
- Leave backtick-quoted identifiers that merely contain a currency reference untouched.
* Address review feedback on #71849
- Allow storage switches with unsynced orders for the whole report builder
test class, so tearDown() can restore storage when HPOS is off.
- Use possessive quantifiers for quoted content in the currency pattern so
long literals can't exhaust the PCRE JIT stack, and keep the fragment if
PCRE fails.
- Match meta_value case-insensitively and treat $ as an identifier character.
diff --git a/plugins/woocommerce/changelog/fix-hpos-legacy-report-currency b/plugins/woocommerce/changelog/fix-hpos-legacy-report-currency
new file mode 100644
index 00000000000..56ba8bbb5b3
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-hpos-legacy-report-currency
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Restore EC Sales List and other legacy reports that read order currency when HPOS is enabled.
diff --git a/plugins/woocommerce/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilder.php b/plugins/woocommerce/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilder.php
index 4e272439a39..358b35b3b75 100644
--- a/plugins/woocommerce/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilder.php
+++ b/plugins/woocommerce/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilder.php
@@ -293,6 +293,11 @@ class HposLegacyOrderReportQueryBuilder {
/**
* Whether a data row resolves to a mapped HPOS money column.
*
+ * Read from the column maps rather than a separate key list, so a newly mapped
+ * money column gets the legacy format without a second edit. HPOS names every
+ * DECIMAL(26,8) money column `*_amount`; other mapped columns, such as
+ * `currency`, must be selected as stored.
+ *
* @param string $type Row type.
* @param string $raw_key Original meta key.
*
@@ -304,7 +309,9 @@ class HposLegacyOrderReportQueryBuilder {
}
$schema = $this->get_report_schema();
- return isset( $schema['order_column'][ $raw_key ] ) || isset( $schema['op_data_column'][ $raw_key ] );
+ $column = $schema['order_column'][ $raw_key ] ?? $schema['op_data_column'][ $raw_key ] ?? '';
+
+ return '_amount' === substr( $column, -7 );
}
/**
@@ -753,8 +760,9 @@ class HposLegacyOrderReportQueryBuilder {
$this->report_schema = array(
'gmt_offset' => (int) ( (float) get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ),
'order_column' => array(
- '_order_total' => 'orders.total_amount',
- '_order_tax' => 'orders.tax_amount',
+ '_order_total' => 'orders.total_amount',
+ '_order_tax' => 'orders.tax_amount',
+ '_order_currency' => 'orders.currency',
// On a refund row, wc_orders.total_amount stores the negative refund total.
// Legacy callers expect the positive `_refund_amount` meta value, so it
// is intentionally not mapped here.
@@ -764,7 +772,8 @@ class HposLegacyOrderReportQueryBuilder {
'_order_shipping_tax' => 'op_data.shipping_tax_amount',
),
'where_meta_column' => array(
- '_customer_user' => 'orders.customer_id',
+ '_customer_user' => 'orders.customer_id',
+ '_order_currency' => 'orders.currency',
),
'address_column' => $this->build_address_column_map(),
);
@@ -838,7 +847,7 @@ class HposLegacyOrderReportQueryBuilder {
}
/**
- * Translate legacy `posts.<col>` and bare `<col>` references in an arbitrary SQL fragment.
+ * Translate legacy post columns and currency metadata references in a SQL fragment.
*
* Both passes cover every column in {@see self::legacy_to_hpos_column_map()}: legacy callers
* often leave these unqualified (e.g. WooCommerce Subscriptions before 7.8.0 passed a bare
@@ -852,6 +861,34 @@ class HposLegacyOrderReportQueryBuilder {
* @return string Translated fragment safe to drop into an HPOS query.
*/
private function translate_legacy_sql_fragment( string $fragment ): string {
+ // Currency selects no longer join metadata, so callers' references to that alias need the HPOS column too.
+ // Quantifiers are possessive so long quoted content can't exhaust the PCRE JIT stack.
+ $currency_pattern = <<<'REGEX'
+/
+ # String literals are skipped whole. An escape may precede any character, including a linefeed.
+ (?s: '(?:[^'\\]++|\\.)*+' | "(?:[^"\\]++|\\.)*+" )(*SKIP)(*F)
+ |
+ # [parent_]meta__order_currency.meta_value, with either part optionally backtick-quoted.
+ # Column names are case-insensitive in MySQL; table aliases are not on every platform.
+ (?<![\w$.`])
+ (?<alias_quote>`?)(?<parent>parent_)?meta__order_currency\k<alias_quote>
+ \s*\.\s*
+ (?<column_quote>`?)(?i:meta_value)\k<column_quote>
+ (?![\w$`])
+ |
+ # Any other backtick-quoted identifier is skipped whole, as it may contain the reference as plain text.
+ `(?:[^`]++|``)*+`(*SKIP)(*F)
+/x
+REGEX;
+ // On a PCRE failure keep the caller's fragment rather than emitting an empty clause.
+ $fragment = preg_replace_callback(
+ $currency_pattern,
+ static function ( $matches ) {
+ return empty( $matches['parent'] ) ? 'orders.currency' : 'parent_orders.currency';
+ },
+ $fragment
+ ) ?? $fragment;
+
$map = $this->legacy_to_hpos_column_map();
$alternation = implode( '|', array_keys( $map ) );
diff --git a/plugins/woocommerce/tests/php/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilderTest.php b/plugins/woocommerce/tests/php/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilderTest.php
index 9e08e31a53a..6300f9a6338 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Admin/Reports/HposLegacyOrderReportQueryBuilderTest.php
@@ -43,6 +43,9 @@ class HposLegacyOrderReportQueryBuilderTest extends WC_Unit_Test_Case {
$this->original_hpos_usage = OrderUtil::custom_orders_table_usage_is_enabled();
$this->original_gmt_offset = (string) get_option( 'gmt_offset' );
$this->original_timezone_string = (string) get_option( 'timezone_string' );
+ // Tests switch storage with unsynced orders in place; without this, switching back
+ // in tearDown() throws when HPOS is not the default storage.
+ add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
}
/**
@@ -55,6 +58,276 @@ class HposLegacyOrderReportQueryBuilderTest extends WC_Unit_Test_Case {
parent::tearDown();
}
+ /**
+ * @testdox Should select currency codes without numeric formatting (WOOEUVA-141).
+ * @testWith ["meta", "orders"]
+ * ["parent_meta", "parent_orders"]
+ * @param string $type Data source type.
+ * @param string $alias Expected orders table alias.
+ */
+ public function test_currency_selection_preserves_code( string $type, string $alias ): void {
+ OrderHelper::toggle_cot_feature_and_usage( true );
+ $query = ( new HposLegacyOrderReportQueryBuilder() )->build_query(
+ array(
+ 'data' => array(
+ '_order_currency' => array(
+ 'type' => $type,
+ 'function' => '',
+ 'name' => 'currency',
+ ),
+ '_order_total' => array(
+ 'type' => $type,
+ 'function' => '',
+ 'name' => 'total',
+ ),
+ ),
+ ),
+ 0,
+ 0
+ );
+
+ $this->assertStringContainsString( "{$alias}.currency as currency", $query['select'] );
+ $this->assertStringNotContainsString( "ROUND({$alias}.currency", $query['select'], 'Currency codes must not be rounded as money.' );
+ $this->assertStringContainsString( "ROUND({$alias}.total_amount", $query['select'], 'Money columns should retain their numeric formatting.' );
+ $this->assertStringNotContainsString( 'meta__order_currency', $query['join'] );
+ }
+
+ /**
+ * @testdox Should include completed B2B orders in grouped currency reports (WOOEUVA-141).
+ * @testWith ["_billing_vat_number"]
+ * ["_vat_number"]
+ * @param string $vat_key Current or legacy VAT metadata key.
+ */
+ public function test_ec_sales_report_returns_hpos_orders( string $vat_key ): void {
+ global $wpdb;
+ OrderHelper::toggle_cot_feature_and_usage( true );
+ update_option( 'timezone_string', 'UTC' );
+
+ foreach ( array( 'FI23365096', 'FI23365096', '' ) as $vat_number ) {
+ $order = new \WC_Order();
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->set_date_created( '2026-11-01 12:00:00' );
+ $order->set_billing_country( 'FI' );
+ $order->set_currency( 'EUR' );
+ $order->set_total( '100' );
+ $order->update_meta_data( $vat_key, $vat_number );
+ $order->save();
+ }
+
+ $data = array(
+ '_order_total' => array(
+ 'type' => 'meta',
+ 'function' => 'SUM',
+ 'name' => 'total_sales',
+ ),
+ );
+ foreach ( array( $vat_key, '_billing_country', '_shipping_country', '_order_currency' ) as $key ) {
+ $data[ $key ] = array(
+ 'type' => 'meta',
+ 'function' => '',
+ 'name' => $key,
+ 'join_type' => '_shipping_country' === $key ? 'LEFT' : 'INNER',
+ );
+ }
+
+ $query = ( new HposLegacyOrderReportQueryBuilder() )->build_query(
+ array(
+ 'data' => $data,
+ 'where' => array(
+ array(
+ 'key' => "meta_{$vat_key}.meta_value",
+ 'value' => '',
+ 'operator' => '!=',
+ ),
+ ),
+ 'group_by' => $vat_key,
+ 'order_by' => "{$vat_key} ASC",
+ 'order_status' => array( OrderStatus::COMPLETED ),
+ 'filter_range' => true,
+ ),
+ strtotime( '2026-10-01' ),
+ strtotime( '2026-12-31' )
+ );
+
+ $rows = $wpdb->get_results( implode( ' ', $query ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is prepared by the report builder.
+
+ $this->assertCount( 1, $rows, 'The two B2B orders should form one VAT-number group.' );
+ $this->assertSame( 'FI23365096', $rows[0]->{$vat_key} );
+ $this->assertSame( 'EUR', $rows[0]->_order_currency );
+ $this->assertSame( 'FI', $rows[0]->_billing_country );
+ $this->assertEquals( 200, $rows[0]->total_sales );
+ }
+
+ /**
+ * @testdox Should filter by the stored order currency without requiring metadata (WOOEUVA-141).
+ */
+ public function test_currency_filter_uses_hpos_column(): void {
+ global $wpdb;
+ OrderHelper::toggle_cot_feature_and_usage( true );
+ foreach ( array( 'EUR', 'USD' ) as $currency ) {
+ $order = new \WC_Order();
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->set_currency( $currency );
+ $order->save();
+ }
+
+ $query = ( new HposLegacyOrderReportQueryBuilder() )->build_query(
+ array(
+ 'data' => array(
+ '_order_currency' => array(
+ 'type' => 'meta',
+ 'function' => '',
+ 'name' => 'currency',
+ ),
+ ),
+ 'where_meta' => array(
+ // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Exercise the legacy report input contract.
+ array(
+ 'meta_key' => '_order_currency',
+ 'meta_value' => 'EUR',
+ 'operator' => '=',
+ ),
+ // phpcs:enable
+ ),
+ ),
+ 0,
+ 0
+ );
+
+ $rows = $wpdb->get_results( implode( ' ', $query ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is prepared by the report builder.
+
+ $this->assertCount( 1, $rows, 'Only the EUR order should match the currency filter.' );
+ $this->assertSame( 'EUR', $rows[0]->currency );
+ }
+
+ /**
+ * @testdox Should preserve legacy currency references in report filters, grouping and sorting.
+ * @testWith ["meta", true, true]
+ * ["parent_meta", true, true]
+ * ["meta", false, true]
+ * ["parent_meta", false, true]
+ * ["meta", true, false]
+ * ["parent_meta", true, false]
+ * ["meta", false, false]
+ * ["parent_meta", false, false]
+ * @param string $type Data source type.
+ * @param bool $hpos Whether HPOS is authoritative.
+ * @param bool $select_currency Whether currency is selected or only used in the filter.
+ */
+ public function test_currency_aliases_work_in_report_clauses( string $type, bool $hpos, bool $select_currency ): void {
+ global $wpdb;
+ OrderHelper::toggle_cot_feature_and_usage( $hpos );
+ require_once WC_ABSPATH . 'includes/admin/reports/class-wc-admin-report.php';
+
+ foreach ( array( 'EUR', 'EUR', 'USD', 'GBP' ) as $currency ) {
+ $order = new \WC_Order();
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->set_currency( $currency );
+ $order->save();
+
+ if ( 'parent_meta' === $type ) {
+ $child = new \WC_Order();
+ $child->set_parent_id( $order->get_id() );
+ $child->set_status( OrderStatus::COMPLETED );
+ $child->set_currency( 'CAD' );
+ $child->save();
+ }
+ }
+
+ $currency_column = "{$type}__order_currency.meta_value";
+ $args = array(
+ 'data' => array(
+ 'ID' => array(
+ 'type' => 'post_data',
+ 'function' => 'COUNT',
+ 'name' => 'total_orders',
+ ),
+ ),
+ 'where' => array(
+ '_order_currency' => array(
+ 'type' => $type,
+ 'key' => $currency_column,
+ 'operator' => 'IN',
+ 'value' => array( 'EUR', 'USD' ),
+ ),
+ ),
+ 'group_by' => $currency_column,
+ 'order_by' => "{$currency_column} ASC",
+ 'query_type' => 'get_results',
+ 'nocache' => true,
+ );
+ if ( $select_currency ) {
+ $args['data']['_order_currency'] = array(
+ 'type' => $type,
+ 'function' => '',
+ 'name' => 'currency',
+ );
+ }
+
+ $sut = new \WC_Admin_Report();
+ $rows = $sut->get_order_report_data( $args );
+
+ $this->assertSame( '', $wpdb->last_error );
+ $this->assertCount( 2, $rows );
+ $this->assertEquals( 2, $rows[0]->total_orders, 'EUR orders should be grouped first.' );
+ $this->assertEquals( 1, $rows[1]->total_orders, 'USD orders should be grouped second.' );
+ if ( $select_currency ) {
+ $this->assertSame( 'EUR', $rows[0]->currency );
+ $this->assertSame( 'USD', $rows[1]->currency );
+ }
+ }
+
+ /**
+ * @testdox Should translate currency columns without changing literals or unrelated identifiers.
+ * @testWith ["meta__order_currency.meta_value", "orders.currency"]
+ * ["parent_meta__order_currency.meta_value", "parent_orders.currency"]
+ * ["`meta__order_currency`.`meta_value`", "orders.currency"]
+ * ["`parent_meta__order_currency` . `meta_value`", "parent_orders.currency"]
+ * ["COALESCE(meta__order_currency.meta_value, 'meta__order_currency.meta_value')", "COALESCE(orders.currency, 'meta__order_currency.meta_value')"]
+ * ["'prefix meta__order_currency.meta_value'", "'prefix meta__order_currency.meta_value'"]
+ * ["\"prefix parent_meta__order_currency.meta_value\"", "\"prefix parent_meta__order_currency.meta_value\""]
+ * ["`meta__order_currency.meta_value`", "`meta__order_currency.meta_value`"]
+ * ["`prefix meta__order_currency.meta_value suffix`", "`prefix meta__order_currency.meta_value suffix`"]
+ * ["`a parent_meta__order_currency.meta_value b` DESC, meta__order_currency.meta_value ASC", "`a parent_meta__order_currency.meta_value b` DESC, orders.currency ASC"]
+ * ["meta__order_currency.META_VALUE", "orders.currency"]
+ * ["parent_meta__order_currency.Meta_Value", "parent_orders.currency"]
+ * ["`meta__order_currency`.`META_VALUE`", "orders.currency"]
+ * ["'meta__order_currency.META_VALUE'", "'meta__order_currency.META_VALUE'"]
+ * ["CONCAT('a\\\nb', meta__order_currency.meta_value, 'x')", "CONCAT('a\\\nb', orders.currency, 'x')"]
+ * ["CONCAT(\"a\\\nb\", parent_meta__order_currency.meta_value, \"x\")", "CONCAT(\"a\\\nb\", parent_orders.currency, \"x\")"]
+ * ["'a\\\nmeta__order_currency.meta_value'", "'a\\\nmeta__order_currency.meta_value'"]
+ * ["custom_meta__order_currency.meta_value", "custom_meta__order_currency.meta_value"]
+ * ["custom$meta__order_currency.meta_value", "custom$meta__order_currency.meta_value"]
+ * ["meta__order_currency.meta_value$suffix", "meta__order_currency.meta_value$suffix"]
+ * ["order_item_meta__order_currency.meta_value", "order_item_meta__order_currency.meta_value"]
+ * ["meta__order_currency.meta_value_suffix", "meta__order_currency.meta_value_suffix"]
+ * @param string $fragment Legacy SQL fragment.
+ * @param string $expected Expected translated SQL fragment.
+ */
+ public function test_currency_reference_translation_preserves_other_tokens( string $fragment, string $expected ): void {
+ OrderHelper::toggle_cot_feature_and_usage( true );
+ $sut = wc_get_container()->get( HposLegacyOrderReportQueryBuilder::class );
+ $query = $sut->build_query( array( 'order_by' => $fragment ), 0, 0 );
+
+ $this->assertSame( 'ORDER BY ' . $expected, $query['order_by'] );
+ }
+
+ /**
+ * @testdox Should translate currency references next to quoted content too long for the PCRE JIT stack.
+ * @testWith ["'"]
+ * ["\""]
+ * ["`"]
+ * @param string $quote Quote character wrapping the long content.
+ */
+ public function test_currency_reference_translation_handles_long_quoted_content( string $quote ): void {
+ OrderHelper::toggle_cot_feature_and_usage( true );
+ $quoted = $quote . str_repeat( 'a', 50000 ) . $quote;
+ $sut = wc_get_container()->get( HposLegacyOrderReportQueryBuilder::class );
+ $query = $sut->build_query( array( 'order_by' => "FIELD(meta__order_currency.meta_value, {$quoted})" ), 0, 0 );
+
+ $this->assertSame( "ORDER BY FIELD(orders.currency, {$quoted})", $query['order_by'] );
+ }
+
/**
* @testdox Should build HPOS-backed clauses with the expected columns, joins and date bounds.
*/