Automattic\WooCommerce\Internal\Admin

Analytics::process_refund_fix_batchpublicWC 10.8.0

Process one batch of refund orders for the analytics fix.

Fetches up to 100 orders with incorrect refund stats (cursor-based so concurrent imports cannot shift the result window) and re-imports each directly. Schedules itself for the next cursor position when the batch is full, stopping automatically once no more rows are found.

Method of the class: Analytics{}

No Hooks.

Returns

null. Nothing (null).

Usage

$Analytics = new Analytics();
$Analytics->process_refund_fix_batch( $min_order_id ): void;
$min_order_id(int)
Exclusive lower bound on order_id; 0 for the first batch.

Changelog

Since 10.8.0 Introduced.

Analytics::process_refund_fix_batch() code WC 10.9.4

public function process_refund_fix_batch( $min_order_id = 0 ): void {
	global $wpdb;

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$refunded_orders = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT order_stats.order_id
			FROM {$wpdb->prefix}wc_order_stats AS order_stats
			INNER JOIN {$wpdb->prefix}wc_order_stats AS parent_stats ON order_stats.parent_id = parent_stats.order_id
			WHERE order_stats.total_sales < 0
				AND order_stats.total_sales = order_stats.net_total
				AND order_stats.total_sales != order_stats.shipping_total
				AND order_stats.total_sales != order_stats.tax_total
				AND (parent_stats.shipping_total > 0 OR parent_stats.tax_total > 0)
				AND order_stats.order_id > %d
			ORDER BY order_stats.order_id ASC
			LIMIT 100",
			$min_order_id
		)
	);

	if ( ! $refunded_orders ) {
		if ( $wpdb->last_error ) {
			throw new \Exception( $wpdb->last_error ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
		}
		return;
	}

	foreach ( $refunded_orders as $refunded_order ) {
		OrdersScheduler::import( intval( $refunded_order->order_id ) );
	}

	if ( count( $refunded_orders ) >= 100 ) {
		$last_order_id = intval( end( $refunded_orders )->order_id );
		WC()->queue()->schedule_single(
			time() + 5,
			'woocommerce_analytics_refund_fix_batch',
			array( $last_order_id ),
			'wc-admin-data'
		);
	}
}