Commit 9faf2190dc5 for woocommerce
commit 9faf2190dc5fa6c694b7ec18595f05d0552b13f4
Author: Christopher Hertel <mail@christopher-hertel.de>
Date: Mon Nov 23 18:03:48 2026 +0100
Add order refund abilities to the Abilities API (#70935)
* Add order refund abilities to Core
Add woocommerce/order-refunds-query, which lists the refunds of an order, and
woocommerce/order-refund-create, which refunds an amount or lines of an order,
manually or through the payment gateway.
The refund ability creates the refund with wc_create_refund(), as the admin
screen and the REST API do. An order lock and a fingerprint of each call keep
a retried call from refunding twice; allow_duplicate_of lets a deliberate
repeat through. Failures that wc_create_refund() hides, such as a hook failing
after the gateway refunded or a failed save, are reported with errors that say
not to refund again.
* Address refund review: name saved refunds, accept older overrides, fixed error codes
- Wrap an extension field failure after the refund exists with
saved_write_error(), so the error names the refund and says not to send it
again.
- Accept allow_duplicate_of for a settled refund of the order past the
duplicate window when the call repeats it, instead of a mismatch error.
- Refuse a call with neither amount nor line_items before locking the order,
naming both fields.
- Delete a refund that an Error left behind when it was thrown while
wc_create_refund() saved the refund before woocommerce_create_refund, and
say that no money moved.
- Report a database error while checking the order lock as lock_failed, not
as lock_lost.
- Map the refund engine codes to fixed ability codes that keep refund_total
whole, with invalid_request as the fallback.
- Load the recent refunds of the order once per call.
* Cover the remaining refund review cases with tests
- A refund field callback that throws after a gateway refund names the saved
refund and says the gateway refunded it.
- allow_duplicate_of past the window is refused for a refund of another order
and for a refund the call does not repeat.
- An engine error code without a mapping becomes invalid_request, keeping its
message and status, with the engine code in the data.
* Drop "recent" from the allow_duplicate_of mismatch error, since older refunds are accepted too
* Delete only the new refund after an early crash, and say a retry will likely fail
- The refund kept for deletion after an Error before woocommerce_create_refund
is now only one without an ID, so an older refund of the order that a
callback saves during the call is never deleted.
- The failed error says the refund was not sent to the payment gateway, and
that the merchant should check the error before a retry.
* Tag and clean up only the refund the ability creates, not one a callback makes
The refund that wc_create_refund() saves first is the one the call creates, so
woocommerce_create_refund now tags only that refund. A refund of the same order
that a callback creates during the call, such as a gateway refund, no longer
gets the fingerprints or the lock check, and is not deleted after an Error.
* Match the refunds REST permission, name a kept refund, and the newer duplicate
- Creating a refund also needs the refund create permission that the refunds
REST endpoint checks, and a refund ID names its order only to users with
access to that order.
- When an extension stops the deletion of a failed refund, the error names
the refund that is still on the order instead of asking to record it.
- When the input and the resolved fingerprint match different refunds, the
duplicate error names the newer one, so one allow_duplicate_of is enough.
* Recognise the ability's refund by its amount, reason and user, and bulk-load refunds
- A refund that a callback makes before the ability's refund is first saved
also has no ID, so the refund is captured and tagged only when its amount,
reason and refunded_by match the call. After an Error, the cleanup no longer
deletes such a refund.
- The duplicate check loads the order's refunds with one wc_get_orders() call
instead of one wc_get_order() call per refund.
* Match the ability's refund on stored values, and fingerprint it if it was never tagged
- The match reads the refund in the edit context, so a filter on a refund
getter, such as one that redacts the reason, no longer stops the refund
being tagged and leaves the retry unguarded.
- When wc_create_refund() returns a refund that was never tagged, the
fingerprints are written onto it afterwards, so a retry is still refused
as a duplicate.
* Tell the agent to report a duplicate refund, and override it only when the merchant asks
The duplicate error offered allow_duplicate_of to any caller that "means to" refund again, which a
retrying agent always does. It now says the first call went through, to tell the merchant, and to
send allow_duplicate_of only when the merchant asks for a second refund. The field description says
never to send it to retry a call.
* Tag the ability's refund by a per-call marker, and keep a paid refund after an Error
- wc_create_refund() gets a marker unique to the call, which
woocommerce_create_refund passes on with the refund, so only that refund is
tagged, even when an extension changed it. A refund that reaches the hook
without the marker is another call's and is never tagged or deleted.
- After an Error, a refund that is already paid is kept as the record of the
money, so a retry is refused. A paid refund that the call cannot tell for
its own is left alone, and the error says to check the refunds first.
- The match on amount, reason and user, and the fingerprint fallback after a
successful call, are gone.
diff --git a/plugins/woocommerce/changelog/wooai-1543-order-refund-abilities b/plugins/woocommerce/changelog/wooai-1543-order-refund-abilities
new file mode 100644
index 00000000000..e7df9d013df
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1543-order-refund-abilities
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let AI agents list an order's refunds and refund an order, manually or through the payment gateway.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 2b0b805839d..231b2b8633e 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -13,6 +13,8 @@ use Automattic\WooCommerce\Abilities\ActionableAbility;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderAddNote;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderCreate;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderNotesQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\OrderRefundCreate;
+use Automattic\WooCommerce\Internal\Abilities\Domain\OrderRefundsQuery;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderSendEmail;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderDelete;
use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdate;
@@ -82,6 +84,8 @@ class AbilitiesLoader {
OrderAddNote::class,
OrderCreate::class,
OrderNotesQuery::class,
+ OrderRefundsQuery::class,
+ OrderRefundCreate::class,
OrderSendEmail::class,
OrderDelete::class,
OrderUpdate::class,
@@ -172,7 +176,7 @@ class AbilitiesLoader {
* @since 11.3.0
*/
public static function register_core_resources(): void {
- foreach ( array( 'product', 'order', 'order_item', 'product_term', 'product_review', 'customer' ) as $resource_name ) {
+ foreach ( array( 'product', 'order', 'order_item', 'order_refund', 'product_term', 'product_review', 'customer' ) as $resource_name ) {
ExtensibleAbilities::register_resource( $resource_name );
}
}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderRefundCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderRefundCreate.php
new file mode 100644
index 00000000000..b63270f5fd4
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderRefundCreate.php
@@ -0,0 +1,886 @@
+<?php
+/**
+ * Order refund create ability class file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\AbilityDefinition;
+use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\OrderAbilityTrait;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\OrderRefundAbilityTrait;
+use Automattic\WooCommerce\Internal\RestApi\Refunds\DataUtils;
+use Automattic\WooCommerce\Utilities\NumberUtil;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Refunds an order with wc_create_refund(), as the admin screen and the REST API do, after checking that the
+ * call does not repeat a recent refund.
+ */
+class OrderRefundCreate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use OrderAbilityTrait;
+ use OrderRefundAbilityTrait;
+
+ /**
+ * Seconds for which a refund blocks the same refund of the order, so a call retried after a timeout cannot refund twice.
+ */
+ private const DUPLICATE_WINDOW = 10 * MINUTE_IN_SECONDS;
+
+ /**
+ * Refund meta with the fingerprint of the call that created the refund.
+ */
+ private const FINGERPRINT_META_KEY = '_woocommerce_ability_refund_fingerprint';
+
+ /**
+ * Refund meta with the fingerprint of the amount and lines the call resolved to, so the same refund sent in another form matches.
+ */
+ private const RESOLVED_FINGERPRINT_META_KEY = '_woocommerce_ability_refund_resolved_fingerprint';
+
+ /**
+ * Refund meta set when the call asked the gateway to refund the payment.
+ */
+ private const PAYMENT_REQUESTED_META_KEY = '_woocommerce_ability_refund_payment_requested';
+
+ /**
+ * Option that locks the refunds of one order, followed by the order ID.
+ */
+ private const LOCK_OPTION_PREFIX = 'woocommerce_ability_order_refund_lock_';
+
+ /**
+ * Key of the wc_create_refund() argument that carries a value unique to the call, which woocommerce_create_refund
+ * passes on with the refund, so a refund that a callback makes during the call is not taken for the call's own.
+ */
+ public const CALL_ARG = 'woocommerce_ability_call';
+
+ /**
+ * Seconds after which a lock is stale, longer than a gateway call takes, so a crashed request cannot block the order.
+ */
+ private const LOCK_TTL = 5 * MINUTE_IN_SECONDS;
+
+ /**
+ * Ability error code suffixes for the codes of the refund engine, so a new or renamed engine code does not change them.
+ */
+ private const ENGINE_ERROR_CODES = array(
+ 'invalid_refund_request' => 'invalid_request',
+ 'order_not_refundable' => 'order_not_refundable',
+ 'invalid_refund_amount' => 'invalid_amount',
+ 'refund_exceeds_remaining' => 'exceeds_remaining',
+ 'missing_line_item_id' => 'missing_line_item_id',
+ 'duplicate_line_item' => 'duplicate_line_item',
+ 'line_item_not_found' => 'line_item_not_found',
+ 'unsupported_item_type' => 'unsupported_item_type',
+ 'invalid_line_item' => 'invalid_line_item',
+ 'line_item_already_refunded' => 'line_item_already_refunded',
+ 'invalid_quantity' => 'invalid_quantity',
+ 'quantity_exceeds_refundable' => 'quantity_exceeds_refundable',
+ 'missing_quantity_or_refund_total' => 'missing_quantity_or_refund_total',
+ 'invalid_refund_total' => 'invalid_refund_total',
+ 'refund_total_exceeds_line' => 'refund_total_exceeds_line',
+ 'refund_total_exceeds_remaining' => 'refund_total_exceeds_remaining',
+ 'duplicate_tax_id' => 'duplicate_tax_id',
+ );
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/order-refund-create';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Refund order', 'woocommerce' ),
+ 'description' => __(
+ 'Refund an amount or lines of an order. With refund_payment, the payment gateway sends the money back; without it, the refund is only recorded and the money is returned outside WooCommerce.',
+ 'woocommerce'
+ ),
+ 'category' => 'woocommerce',
+ 'input_schema' => self::build_input_schema(),
+ 'output_schema' => self::build_output_schema(),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_refund_order' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => true,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Refund the order while holding its lock, so a second call cannot pass the duplicate and amount checks
+ * before the first refund is saved.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ if ( ! isset( $input['amount'] ) && ! isset( $input['line_items'] ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_missing_amount',
+ __( 'No amount or lines to refund were sent, so no refund was created. Send amount, line_items, or both.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ $order_id = $input['id'];
+ $lock = self::lock_order( $order_id );
+ if ( false === $lock ) {
+ return self::lock_failed_error();
+ }
+ if ( null === $lock ) {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_in_progress',
+ __( 'Another refund of this order is in progress. List the refunds of the order with woocommerce/order-refunds-query before you refund it again.', 'woocommerce' ),
+ array( 'status' => 409 )
+ );
+ }
+
+ try {
+ $order = self::get_order_from_input( $input );
+ if ( is_wp_error( $order ) ) {
+ return $order;
+ }
+
+ return self::refund( $order, $input, $lock );
+ } finally {
+ self::unlock_order( $order_id, $lock );
+ }
+ }
+
+ /**
+ * Check the call against recent refunds and the gateway, then create the refund.
+ *
+ * @param \WC_Order $order Order.
+ * @param array $input Ability input.
+ * @param string $lock Lock value of the call.
+ * @return array|\WP_Error
+ */
+ private static function refund( \WC_Order $order, array $input, string $lock ) {
+ $decimals = wc_get_price_decimals();
+ $refund_payment = $input['refund_payment'] ?? false;
+
+ $allowed_id = $input['allow_duplicate_of'] ?? 0;
+ $allowed_found = false;
+ $recent = self::find_recent_refunds( $order );
+ $fingerprint = self::fingerprint( $order, $input, $decimals );
+ $duplicate = self::find_duplicate( $recent, self::FINGERPRINT_META_KEY, $fingerprint, $allowed_id, $allowed_found );
+ if ( null !== $duplicate && self::is_unsettled( $duplicate ) ) {
+ return self::duplicate_error( $duplicate );
+ }
+
+ $prepared = wc_get_container()->get( DataUtils::class )->prepare_refund_creation_or_error(
+ $order,
+ $input['line_items'] ?? array(),
+ isset( $input['amount'] ),
+ isset( $input['amount'] ) ? NumberUtil::round( (float) $input['amount'], $decimals ) : null,
+ 'woocommerce-abilities'
+ );
+ if ( is_wp_error( $prepared ) ) {
+ return null !== $duplicate ? self::duplicate_error( $duplicate ) : self::refund_error( $prepared );
+ }
+
+ $amount = NumberUtil::round( (float) $prepared['amount'], $decimals );
+ $resolved_fingerprint = self::fingerprint(
+ $order,
+ array(
+ 'amount' => $amount,
+ 'line_items' => array_map(
+ static fn( array $line ): array => array(
+ 'line_item_id' => $line['line_item_id'],
+ 'refund_total' => $line['refund_total'] ?? null,
+ ),
+ $prepared['schema_line_items']
+ ),
+ 'refund_payment' => $refund_payment,
+ ),
+ $decimals
+ );
+ $duplicate = self::blocking_refund( $duplicate, self::find_duplicate( $recent, self::RESOLVED_FINGERPRINT_META_KEY, $resolved_fingerprint, $allowed_id, $allowed_found ) );
+ if ( null !== $duplicate ) {
+ return self::duplicate_error( $duplicate );
+ }
+
+ if ( $allowed_id > 0 && ! $allowed_found && ! self::repeats_older_refund( $order, $allowed_id, $fingerprint, $resolved_fingerprint ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_duplicate_mismatch',
+ sprintf(
+ /* translators: %d: refund ID. */
+ __( 'Refund %d is not a refund of this order with the same amount and lines, so no refund was created. Send allow_duplicate_of only with the refund ID that a duplicate error returned, and the same input as that call.', 'woocommerce' ),
+ $allowed_id
+ ),
+ array( 'status' => 400 )
+ );
+ }
+
+ if ( $refund_payment && ! self::gateway_can_refund( $order ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_gateway_unsupported',
+ __( 'The payment gateway of this order cannot refund it automatically. Send refund_payment as false to record a manual refund, and return the money outside WooCommerce.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ $order_id = $order->get_id();
+ $tagged = null;
+ $saved = false;
+ $paid = false;
+ $lock_error = null;
+
+ /**
+ * The refund of the order that saved first during the call and has not reached woocommerce_create_refund as
+ * another call's, so the call's own until then. $watch_paid sets it, which PHPStan does not follow into $tag.
+ *
+ * @var \WC_Order_Refund|null $candidate
+ */
+ $candidate = null;
+ $marker = wp_generate_uuid4();
+ $reason = isset( $input['reason'] ) ? sanitize_textarea_field( $input['reason'] ) : null;
+
+ // First, so the meta is on the refund before callbacks that move money see it, and a lost lock declines it before they run.
+ $tag = static function ( $refund, $args ) use ( $order_id, $lock, $marker, $fingerprint, $resolved_fingerprint, $refund_payment, &$candidate, &$tagged, &$lock_error ): void {
+ if ( ! $refund instanceof \WC_Order_Refund || $refund->get_parent_id( 'edit' ) !== $order_id ) {
+ return;
+ }
+ if ( ! is_array( $args ) || ( $args[ self::CALL_ARG ] ?? null ) !== $marker ) {
+ if ( $refund === $candidate ) {
+ $candidate = null;
+ }
+ return;
+ }
+ if ( null !== $tagged ) {
+ return;
+ }
+ $tagged = $refund;
+ $holds = self::holds_lock( $order_id, $lock );
+ if ( true !== $holds ) {
+ $lock_error = null === $holds ? self::lock_failed_error() : self::lock_lost_error();
+ throw new \Exception( 'The refund lock of the order could not be confirmed.' );
+ }
+ self::add_fingerprints( $refund, $fingerprint, $resolved_fingerprint, $refund_payment );
+ };
+ // wc_create_refund() sets the paid flag only after the gateway refunded, so a save that carries it means the money moved.
+ $watch_paid = static function ( $refund ) use ( $order_id, &$candidate, &$tagged, &$paid ): void {
+ if ( null === $candidate && $refund instanceof \WC_Order_Refund && 0 === $refund->get_id() && $refund->get_parent_id( 'edit' ) === $order_id ) {
+ $candidate = $refund;
+ }
+ $paid = $paid || ( null !== $tagged && $refund === $tagged && $refund->get_refunded_payment() );
+ };
+ $watch_save = static function ( $refund ) use ( &$tagged, &$saved ): void {
+ $saved = $saved || ( null !== $tagged && $refund === $tagged );
+ };
+
+ add_action( 'woocommerce_create_refund', $tag, PHP_INT_MIN, 2 );
+ add_action( 'woocommerce_before_order_refund_object_save', $watch_paid, PHP_INT_MIN );
+ add_action( 'woocommerce_after_order_refund_object_save', $watch_save, PHP_INT_MIN );
+ /**
+ * Whether a callback threw an Error. Set in the catch, which PHPStan takes for dead.
+ *
+ * @var bool $crashed
+ */
+ $crashed = false;
+ try {
+ $result = wc_create_refund(
+ array(
+ 'amount' => $amount,
+ 'reason' => $reason,
+ 'order_id' => $order_id,
+ 'line_items' => $prepared['line_items'],
+ 'refund_payment' => $refund_payment,
+ 'restock_items' => $input['restock_items'] ?? false,
+ self::CALL_ARG => $marker,
+ )
+ );
+ } catch ( \Error $e ) { // @phpstan-ignore catch.neverThrown (Callbacks that wc_create_refund() runs can throw an Error, which its @throws does not list.)
+ // wc_create_refund() catches only exceptions, so delete the half-made refund as it would. It saves the refund before woocommerce_create_refund, so the refund can exist untagged.
+ // A paid refund stays as the record of the money, so a retry finds it, and an untagged one was paid by another call.
+ $crashed = true;
+ $result = new \WP_Error( 'error', $e->getMessage() );
+ $made = $tagged ?? $candidate;
+ if ( null !== $made && $made->get_id() > 0 && ! $made->get_refunded_payment( 'edit' ) ) {
+ $made->delete( true );
+ }
+ } finally {
+ remove_action( 'woocommerce_create_refund', $tag, PHP_INT_MIN );
+ remove_action( 'woocommerce_before_order_refund_object_save', $watch_paid, PHP_INT_MIN );
+ remove_action( 'woocommerce_after_order_refund_object_save', $watch_save, PHP_INT_MIN );
+ }
+
+ if ( $result instanceof \WC_Order_Refund ) {
+ // An order save stores its exception instead of throwing, so wc_create_refund() goes on after a failed save.
+ $save_error = $result->get_last_save_error();
+ if ( null !== $save_error ) {
+ /* translators: 1: refund ID, 2: error message. */
+ $message = __( 'Refund %1$d was created, but it could not be saved in full: %2$s Do not refund again. Check the order instead.', 'woocommerce' );
+ if ( $paid ) {
+ /* translators: 1: refund ID, 2: error message. */
+ $message = __( 'The payment gateway refunded the payment and refund %1$d was created, but it could not be saved in full: %2$s Do not refund again. Check the order instead.', 'woocommerce' );
+ }
+
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_incomplete',
+ sprintf( $message, $result->get_id(), $save_error->getMessage() ),
+ array(
+ 'status' => 500,
+ 'refund_id' => $result->get_id(),
+ 'refunded_payment' => $paid,
+ )
+ );
+ }
+
+ $formatted = self::format_refund_for_response( $result );
+ if ( is_wp_error( $formatted ) ) {
+ return ExtensibleAbilities::saved_write_error( $formatted, 'order_refund', $result->get_id(), array( 'refunded_payment' => $paid ) );
+ }
+
+ return array( 'refund' => $formatted );
+ }
+
+ $made = $tagged ?? $candidate;
+ if ( null !== $made && $made->get_id() > 0 && wc_get_order( $made->get_id() ) instanceof \WC_Order_Refund ) {
+ if ( null === $tagged && $made->get_refunded_payment( 'edit' ) ) {
+ return self::unconfirmed_refund_error( $made->get_id(), $result );
+ }
+ return self::kept_refund_error( $made->get_id(), $result, $paid );
+ }
+
+ if ( $crashed && null === $tagged ) {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_failed',
+ /* translators: %s: error message. */
+ sprintf( __( 'The refund failed before it was sent to the payment gateway, so no refund was created and no money was returned: %s The same error will likely stop a retry, so ask the merchant to check it before you refund again.', 'woocommerce' ), $result->get_error_message() ),
+ array( 'status' => 500 )
+ );
+ }
+
+ return self::create_error( $result, $order_id, $lock_error, $saved || $crashed, $paid, $refund_payment && ! $crashed );
+ }
+
+ /**
+ * Mark a refund with the fingerprints of the call, and as asked to refund the payment when it was. Not saved.
+ *
+ * @param \WC_Order_Refund $refund Refund.
+ * @param string $fingerprint Fingerprint of the call input.
+ * @param string $resolved_fingerprint Fingerprint of the amount and lines the call resolved to.
+ * @param bool $refund_payment Whether the call asked the gateway to refund the payment.
+ */
+ private static function add_fingerprints( \WC_Order_Refund $refund, string $fingerprint, string $resolved_fingerprint, bool $refund_payment ): void {
+ $refund->update_meta_data( self::FINGERPRINT_META_KEY, $fingerprint );
+ $refund->update_meta_data( self::RESOLVED_FINGERPRINT_META_KEY, $resolved_fingerprint );
+ if ( $refund_payment ) {
+ $refund->update_meta_data( self::PAYMENT_REQUESTED_META_KEY, 'yes' );
+ }
+ }
+
+ /**
+ * The error of a call that failed before its refund reached the payment gateway, while a paid refund of the order
+ * that it cannot tell for its own was saved during the call. That refund is left as it is.
+ *
+ * @param int $refund_id ID of the paid refund.
+ * @param mixed $result Result of wc_create_refund().
+ * @return \WP_Error
+ */
+ private static function unconfirmed_refund_error( int $refund_id, $result ): \WP_Error {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_failed',
+ sprintf(
+ /* translators: 1: error message, 2: refund ID. */
+ __( 'The refund failed before it was sent to the payment gateway: %1$s Refund %2$d of this order, which the payment gateway refunded, was saved during the call, but the call could not confirm that it made it. Check the refunds of the order with the merchant before you retry.', 'woocommerce' ),
+ is_wp_error( $result ) ? $result->get_error_message() : __( 'The refund could not be created.', 'woocommerce' ),
+ $refund_id
+ ),
+ array(
+ 'status' => 500,
+ 'refund_id' => $refund_id,
+ )
+ );
+ }
+
+ /**
+ * The error of a failed call whose refund is still on the order, because an extension stopped its deletion.
+ *
+ * @param int $refund_id Refund ID.
+ * @param mixed $result Result of wc_create_refund().
+ * @param bool $paid Whether the gateway refunded the payment.
+ * @return \WP_Error
+ */
+ private static function kept_refund_error( int $refund_id, $result, bool $paid ): \WP_Error {
+ /* translators: 1: refund ID, 2: error message. */
+ $message = __( 'Refund %1$d is still on the order, though a later step failed and WooCommerce could not delete it: %2$s Do not refund again. Check the order, and the payment with the merchant, instead.', 'woocommerce' );
+ if ( $paid ) {
+ /* translators: 1: refund ID, 2: error message. */
+ $message = __( 'Refund %1$d is still on the order and the payment gateway refunded the payment, though a later step failed and WooCommerce could not delete the refund: %2$s Do not refund again. Check the order instead.', 'woocommerce' );
+ }
+
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_incomplete',
+ sprintf( $message, $refund_id, is_wp_error( $result ) ? $result->get_error_message() : __( 'The refund could not be created.', 'woocommerce' ) ),
+ array(
+ 'status' => 500,
+ 'refund_id' => $refund_id,
+ 'refunded_payment' => $paid,
+ )
+ );
+ }
+
+ /**
+ * The error of a wc_create_refund() call that failed. It deletes the refund on any failure, also after the
+ * gateway or a refund callback moved the money, so the error says when a retry could refund twice.
+ *
+ * @param mixed $result Result of wc_create_refund().
+ * @param int $order_id Order ID.
+ * @param \WP_Error|null $lock_error Error of the lock check that declined the refund, if it did.
+ * @param bool $saved Whether the refund was saved after woocommerce_create_refund, or a callback crashed.
+ * @param bool $paid Whether the gateway refunded the payment.
+ * @param bool $refund_payment Whether the call asked the gateway to refund the payment.
+ * @return \WP_Error
+ */
+ private static function create_error( $result, int $order_id, ?\WP_Error $lock_error, bool $saved, bool $paid, bool $refund_payment ): \WP_Error {
+ $reason = is_wp_error( $result ) ? $result->get_error_message() : __( 'The refund could not be created.', 'woocommerce' );
+
+ if ( null !== $lock_error ) {
+ return $lock_error;
+ }
+
+ if ( ! $saved ) {
+ return new \WP_Error( 'woocommerce_ability_order_refund_declined', $reason, array( 'status' => 400 ) );
+ }
+
+ if ( $refund_payment && ! $paid ) {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_gateway_failed',
+ /* translators: %s: error message of the payment gateway. */
+ sprintf( __( 'The payment gateway did not refund the payment, so no refund was created: %s', 'woocommerce' ), $reason ),
+ array( 'status' => 502 )
+ );
+ }
+
+ wc_get_logger()->error(
+ sprintf( 'A refund of order %1$d was deleted after it was saved: %2$s', $order_id, $reason ),
+ array( 'source' => 'woocommerce-refunds' )
+ );
+
+ /* translators: %s: error message. */
+ $message = __( 'The refund failed after extensions ran their refund callbacks, so it may not have been recorded, and an extension may already have refunded the payment: %s Do not refund again. Check with the merchant and the payment gateway whether the money was returned, and record the refund manually if it was.', 'woocommerce' );
+ if ( $paid ) {
+ /* translators: %s: error message. */
+ $message = __( 'The payment gateway refunded the payment, but a later step failed and WooCommerce deleted the refund, so the order does not show it: %s Do not refund again. Record the refund manually.', 'woocommerce' );
+ }
+
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_lost',
+ sprintf( $message, $reason ),
+ array(
+ 'status' => 500,
+ 'order_id' => $order_id,
+ )
+ );
+ }
+
+ /**
+ * Hash of the call input with the lines sorted by ID, taken before the refund is checked, so a retry of a
+ * refund that used up the order still matches it.
+ *
+ * @param \WC_Order $order Order.
+ * @param array $input Ability input.
+ * @param int $decimals Price decimals.
+ * @return string
+ */
+ private static function fingerprint( \WC_Order $order, array $input, int $decimals ): string {
+ $lines = array();
+ foreach ( $input['line_items'] ?? array() as $line ) {
+ $lines[] = array(
+ (int) $line['line_item_id'],
+ isset( $line['quantity'] ) ? (int) $line['quantity'] : null,
+ isset( $line['refund_total'] ) ? wc_format_decimal( NumberUtil::round( (float) $line['refund_total'], $decimals ), $decimals ) : null,
+ );
+ }
+ sort( $lines );
+
+ return md5(
+ (string) wp_json_encode(
+ array(
+ $order->get_id(),
+ isset( $input['amount'] ) ? wc_format_decimal( NumberUtil::round( (float) $input['amount'], $decimals ), $decimals ) : null,
+ $lines,
+ (bool) ( $input['refund_payment'] ?? false ),
+ get_current_user_id(),
+ )
+ )
+ );
+ }
+
+ /**
+ * The newest refund that blocks the call. The refund that allow_duplicate_of names also lets through the older
+ * ones it repeats, so each repeat only needs the ID of the last one, but never a newer refund, which a retry of
+ * the call would have made, or one kept without its payment refunded.
+ *
+ * @param \WC_Order_Refund[] $recent Refunds from find_recent_refunds(), newest first.
+ * @param string $meta_key Meta key of the fingerprint.
+ * @param string $fingerprint Fingerprint of the call.
+ * @param int $allowed_id Refund ID from allow_duplicate_of, or 0.
+ * @param bool $allowed_found Set to true when the refund that allow_duplicate_of names matched.
+ * @return \WC_Order_Refund|null
+ */
+ private static function find_duplicate( array $recent, string $meta_key, string $fingerprint, int $allowed_id, bool &$allowed_found ): ?\WC_Order_Refund {
+ foreach ( $recent as $refund ) {
+ if ( $refund->get_meta( $meta_key ) !== $fingerprint ) {
+ continue;
+ }
+ if ( $refund->get_id() > $allowed_id || self::is_unsettled( $refund ) ) {
+ return $refund;
+ }
+
+ if ( $refund->get_id() === $allowed_id ) {
+ $allowed_found = true;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * The one of two duplicates for the error to name: one without its payment refunded, since it stops every
+ * retry, else the newer one, since allow_duplicate_of with its ID lets the older one through too.
+ *
+ * @param \WC_Order_Refund|null $first Duplicate by the input fingerprint.
+ * @param \WC_Order_Refund|null $second Duplicate by the resolved fingerprint.
+ * @return \WC_Order_Refund|null
+ */
+ private static function blocking_refund( ?\WC_Order_Refund $first, ?\WC_Order_Refund $second ): ?\WC_Order_Refund {
+ if ( null === $first || null === $second ) {
+ return $first ?? $second;
+ }
+ if ( self::is_unsettled( $second ) ) {
+ return $second;
+ }
+
+ return $second->get_id() > $first->get_id() ? $second : $first;
+ }
+
+ /**
+ * Whether allow_duplicate_of names a settled refund of the order, older than the duplicate window, that the
+ * call repeats. A refund past the window no longer blocks the call, so naming it only confirms the repeat.
+ *
+ * @param \WC_Order $order Order.
+ * @param int $allowed_id Refund ID from allow_duplicate_of.
+ * @param string $fingerprint Fingerprint of the call.
+ * @param string $resolved_fingerprint Fingerprint of the amount and lines the call resolved to.
+ * @return bool
+ */
+ private static function repeats_older_refund( \WC_Order $order, int $allowed_id, string $fingerprint, string $resolved_fingerprint ): bool {
+ $refund = wc_get_order( $allowed_id );
+
+ return $refund instanceof \WC_Order_Refund
+ && $refund->get_parent_id() === $order->get_id()
+ && ! self::is_unsettled( $refund )
+ && ( $refund->get_meta( self::FINGERPRINT_META_KEY ) === $fingerprint || $refund->get_meta( self::RESOLVED_FINGERPRINT_META_KEY ) === $resolved_fingerprint );
+ }
+
+ /**
+ * Refunds of the order, newest first, created within the duplicate window or, at any age, kept without their
+ * payment refunded, since a retry would then record the refund twice.
+ *
+ * @param \WC_Order $order Order.
+ * @return \WC_Order_Refund[]
+ */
+ private static function find_recent_refunds( \WC_Order $order ): array {
+ $refunds = wc_get_orders(
+ array(
+ 'type' => 'shop_order_refund',
+ 'parent' => $order->get_id(),
+ 'limit' => -1,
+ 'orderby' => 'ID',
+ 'order' => 'DESC',
+ )
+ );
+
+ $found = array();
+ foreach ( is_array( $refunds ) ? $refunds : array() as $refund ) {
+ if ( ! $refund instanceof \WC_Order_Refund ) {
+ continue;
+ }
+ $created = $refund->get_date_created();
+ if ( self::is_unsettled( $refund ) || ( $created && $created->getTimestamp() > time() - self::DUPLICATE_WINDOW ) ) {
+ $found[] = $refund;
+ }
+ }
+
+ return $found;
+ }
+
+ /**
+ * Whether the call that created the refund asked for the payment to be refunded and the refund is not marked
+ * as paid. A failed call deletes its refund, so only a refund whose paid flag failed to save matches.
+ *
+ * @param \WC_Order_Refund $refund Refund.
+ * @return bool
+ */
+ private static function is_unsettled( \WC_Order_Refund $refund ): bool {
+ return 'yes' === $refund->get_meta( self::PAYMENT_REQUESTED_META_KEY ) && ! $refund->get_refunded_payment();
+ }
+
+ /**
+ * The refusal of a refund that repeats a recent one, with that refund, so a client that retried learns it was made.
+ *
+ * @param \WC_Order_Refund $refund Refund that the call repeats.
+ * @return \WP_Error
+ */
+ private static function duplicate_error( \WC_Order_Refund $refund ): \WP_Error {
+ $created = $refund->get_date_created();
+ $created = $created ? $created->getTimestamp() : time();
+ $formatted = self::format_refund_for_response( $refund );
+
+ if ( self::is_unsettled( $refund ) ) {
+ $message = sprintf(
+ /* translators: 1: refund ID, 2: time since the refund, such as "2 mins". */
+ __( 'Refund %1$d recorded the same refund of this order %2$s ago, so no new refund was created. The payment gateway was asked to refund the payment, but its result was not saved, so it may have refunded the payment. Do not refund again. Check the payment with the merchant and the payment gateway.', 'woocommerce' ),
+ $refund->get_id(),
+ human_time_diff( $created )
+ );
+ } else {
+ $message = sprintf(
+ /* translators: 1: refund ID, 2: time since the refund, such as "2 mins". */
+ __( 'Refund %1$d already refunded the same amount and lines of this order %2$s ago, so no new refund was created. If you sent this call again after an error or a timeout, the first call went through: tell the merchant about refund %1$d and do not refund again. Only if the merchant then asks for a second, identical refund, send the same input with allow_duplicate_of set to %1$d.', 'woocommerce' ),
+ $refund->get_id(),
+ human_time_diff( $created )
+ );
+ }
+
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_duplicate',
+ $message,
+ array(
+ 'status' => 409,
+ 'refund' => is_wp_error( $formatted ) ? array( 'id' => $refund->get_id() ) : $formatted,
+ )
+ );
+ }
+
+ /**
+ * Lock the refunds of an order with an option row, as WC_Install::create_lock() does, taking over a stale lock.
+ *
+ * @param int $order_id Order ID.
+ * @return string|false|null The lock value to release it with, null when another call holds the lock, or false on a database error.
+ */
+ private static function lock_order( int $order_id ) {
+ global $wpdb;
+
+ $name = self::LOCK_OPTION_PREFIX . $order_id;
+ $expires = time() + self::LOCK_TTL;
+
+ // INSERT IGNORE affects no rows while another call holds the lock, so contention is not logged as a DB error.
+ $locked = $wpdb->query(
+ $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %d, 'no')", $name, $expires )
+ );
+ if ( 0 === $locked ) {
+ $locked = $wpdb->query(
+ $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %d WHERE option_name = %s AND option_value < %d", $expires, $name, time() )
+ );
+ }
+ if ( false === $locked ) {
+ return false;
+ }
+
+ return $locked ? (string) $expires : null;
+ }
+
+ /**
+ * Whether the lock row of the order still holds the value of this call.
+ *
+ * @param int $order_id Order ID.
+ * @param string $lock Value that lock_order() returned.
+ * @return bool|null Null on a database error.
+ */
+ private static function holds_lock( int $order_id, string $lock ): ?bool {
+ global $wpdb;
+
+ $value = $wpdb->get_var(
+ $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", self::LOCK_OPTION_PREFIX . $order_id )
+ );
+ if ( null === $value && '' !== $wpdb->last_error ) {
+ return null;
+ }
+
+ return $value === $lock;
+ }
+
+ /**
+ * The error when the order lock cannot be taken or checked. The refund is declined before the gateway runs.
+ *
+ * @return \WP_Error
+ */
+ private static function lock_failed_error(): \WP_Error {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_lock_failed',
+ __( 'The order could not be locked for the refund because of a database error, so no refund was created. It is safe to try again.', 'woocommerce' ),
+ array( 'status' => 500 )
+ );
+ }
+
+ /**
+ * The error when another call took over the order lock as stale while this call was refunding.
+ *
+ * @return \WP_Error
+ */
+ private static function lock_lost_error(): \WP_Error {
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_lock_lost',
+ __( 'This refund took too long, and another refund of the order may have started, so no refund was created. List the refunds of the order with woocommerce/order-refunds-query before you refund it again.', 'woocommerce' ),
+ array( 'status' => 409 )
+ );
+ }
+
+ /**
+ * Release the lock of an order, unless another call took it over as stale.
+ *
+ * @param int $order_id Order ID.
+ * @param string $lock Value that lock_order() returned.
+ */
+ private static function unlock_order( int $order_id, string $lock ): void {
+ global $wpdb;
+
+ $wpdb->query(
+ $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", self::LOCK_OPTION_PREFIX . $order_id, $lock )
+ );
+ }
+
+ /**
+ * Whether the payment gateway of the order can send the money back.
+ *
+ * @param \WC_Order $order Order.
+ * @return bool
+ */
+ private static function gateway_can_refund( \WC_Order $order ): bool {
+ $gateway = wc_get_payment_gateway_by_order( $order );
+
+ return $gateway instanceof \WC_Payment_Gateway && $gateway->can_refund_order( $order );
+ }
+
+ /**
+ * Name an error of the refund engine as an ability error. The message and data stay. A code missing from
+ * ENGINE_ERROR_CODES becomes `invalid_request`, with the engine code in the data, so the ability codes stay fixed.
+ *
+ * @param \WP_Error $error Error of DataUtils::prepare_refund_creation_or_error().
+ * @return \WP_Error
+ */
+ private static function refund_error( \WP_Error $error ): \WP_Error {
+ $code = (string) $error->get_error_code();
+ $data = $error->get_error_data();
+ $data = is_array( $data ) ? $data : array( 'status' => 400 );
+ if ( ! isset( self::ENGINE_ERROR_CODES[ $code ] ) ) {
+ $data['engine_code'] = $code;
+ }
+
+ return new \WP_Error(
+ 'woocommerce_ability_order_refund_' . ( self::ENGINE_ERROR_CODES[ $code ] ?? 'invalid_request' ),
+ $error->get_error_message(),
+ $data
+ );
+ }
+
+ /**
+ * Get the ability input schema.
+ *
+ * @return array
+ */
+ private static function build_input_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Order ID.', 'woocommerce' ),
+ 'minimum' => 1,
+ ),
+ 'amount' => array(
+ 'type' => 'string',
+ 'pattern' => '^[0-9]+(\.[0-9]+)?$',
+ 'description' => __( 'Amount to refund, including tax, such as 12.50. Without line_items, it refunds this amount of the order. With line_items, it defaults to their total and cannot be lower.', 'woocommerce' ),
+ ),
+ 'line_items' => array(
+ 'type' => 'array',
+ 'description' => __( 'Order lines to refund. Send quantity to refund whole units, or refund_total for a tax-inclusive amount of the line.', 'woocommerce' ),
+ 'minItems' => 1,
+ 'items' => array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'line_item_id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'ID of the order line, from the woocommerce/orders-query ability with include_line_items and include_lines.', 'woocommerce' ),
+ 'minimum' => 1,
+ ),
+ 'quantity' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'refund_total' => array(
+ 'type' => 'number',
+ 'description' => __( 'Tax-inclusive amount to refund for the line. Negative only for a discount or credit line.', 'woocommerce' ),
+ ),
+ ),
+ 'required' => array( 'line_item_id' ),
+ 'additionalProperties' => false,
+ ),
+ ),
+ 'reason' => array( 'type' => 'string' ),
+ 'refund_payment' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the payment gateway sends the money back.', 'woocommerce' ),
+ 'default' => false,
+ ),
+ 'restock_items' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether to return the refunded quantities of the product lines to stock.', 'woocommerce' ),
+ 'default' => false,
+ ),
+ 'allow_duplicate_of' => array(
+ 'type' => 'integer',
+ 'description' => __( 'ID of the refund that a duplicate error returned. Send it, with the same input, only when the merchant asked for a second refund after being told about that one. Never send it to retry a failed or timed-out call.', 'woocommerce' ),
+ 'minimum' => 1,
+ ),
+ ),
+ 'required' => array( 'id' ),
+ 'additionalProperties' => false,
+ );
+ }
+
+ /**
+ * Get the ability output schema.
+ *
+ * @return array
+ */
+ private static function build_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'refund' => self::get_refund_output_schema(),
+ ),
+ 'additionalProperties' => false,
+ );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderRefundsQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderRefundsQuery.php
new file mode 100644
index 00000000000..4394daadb66
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderRefundsQuery.php
@@ -0,0 +1,171 @@
+<?php
+/**
+ * Order refunds query ability definition file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\AbilityDefinition;
+use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\OrderAbilityTrait;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\OrderRefundAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Lists the refunds of one order, newest first.
+ */
+class OrderRefundsQuery extends AbstractDomainAbility implements AbilityDefinition {
+
+ use OrderAbilityTrait;
+ use OrderRefundAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/order-refunds-query';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Query order refunds', 'woocommerce' ),
+ 'description' => __(
+ 'List the refunds of an order, newest first. Use the woocommerce/order-refund-create ability to refund an order.',
+ 'woocommerce'
+ ),
+ 'category' => 'woocommerce',
+ 'input_schema' => self::get_input_schema(),
+ 'output_schema' => self::get_output_schema(),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_view_order_refunds' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => true,
+ 'idempotent' => true,
+ 'destructive' => false,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * List the refunds of an order, only those in `include` when it is sent.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ $order = self::get_order_from_input( $input );
+
+ if ( is_wp_error( $order ) ) {
+ return $order;
+ }
+
+ $refunds = $order->get_refunds();
+ usort(
+ $refunds,
+ static function ( \WC_Order_Refund $a, \WC_Order_Refund $b ): int {
+ $a_created = $a->get_date_created();
+ $b_created = $b->get_date_created();
+
+ return array( $b_created ? $b_created->getTimestamp() : 0, $b->get_id() ) <=> array( $a_created ? $a_created->getTimestamp() : 0, $a->get_id() );
+ }
+ );
+ if ( isset( $input['include'] ) ) {
+ $refunds = array_filter(
+ $refunds,
+ static fn( \WC_Order_Refund $refund ): bool => in_array( $refund->get_id(), $input['include'], true )
+ );
+ }
+
+ $refunds = array_values( $refunds );
+ ExtensibleAbilities::prime( 'order_refund', $refunds );
+
+ $items = array();
+ foreach ( $refunds as $refund ) {
+ $item = self::format_refund_for_response( $refund );
+ if ( is_wp_error( $item ) ) {
+ return $item;
+ }
+ $items[] = $item;
+ }
+
+ return array(
+ 'refunds' => $items,
+ 'total' => count( $items ),
+ );
+ }
+
+ /**
+ * Get the ability input schema.
+ *
+ * @return array
+ */
+ private static function get_input_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Order ID.', 'woocommerce' ),
+ 'minimum' => 1,
+ ),
+ 'include' => array(
+ 'type' => 'array',
+ 'description' => __( 'Limit the result to these refund IDs of the order.', 'woocommerce' ),
+ 'items' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ 'minItems' => 1,
+ 'maxItems' => 200,
+ ),
+ ),
+ 'required' => array( 'id' ),
+ 'additionalProperties' => false,
+ );
+ }
+
+ /**
+ * Get the ability output schema.
+ *
+ * @return array
+ */
+ private static function get_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'refunds' => array(
+ 'type' => 'array',
+ 'items' => self::get_refund_output_schema(),
+ ),
+ 'total' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Number of refunds returned.', 'woocommerce' ),
+ ),
+ ),
+ 'additionalProperties' => false,
+ );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
index f9683314bea..fabb079c62c 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
@@ -314,6 +314,15 @@ trait OrderAbilityTrait {
protected static function get_order_from_input( array $input ) {
$order = wc_get_order( $input['id'] );
+ if ( $order instanceof \WC_Order_Refund ) {
+ return new \WP_Error(
+ 'woocommerce_order_not_found',
+ /* translators: 1: refund ID, 2: ID of the refunded order. */
+ sprintf( __( '%1$d is the ID of a refund of order %2$d, not of an order. Use order ID %2$d.', 'woocommerce' ), $input['id'], $order->get_parent_id() ),
+ array( 'status' => 404 )
+ );
+ }
+
if ( ! $order instanceof \WC_Order ) {
return new \WP_Error(
'woocommerce_order_not_found',
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderRefundAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderRefundAbilityTrait.php
new file mode 100644
index 00000000000..bc58a8c6df5
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderRefundAbilityTrait.php
@@ -0,0 +1,181 @@
+<?php
+/**
+ * Order refund ability trait file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Utilities\OrderUtil;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Output of a refund for the order refund abilities. Amounts are positive, though a refund stores its lines as
+ * negative copies of the order lines. The class that uses it also uses DomainAbilityHelpers and OrderAbilityTrait.
+ */
+trait OrderRefundAbilityTrait {
+
+ /**
+ * Check refund access to an order, with the refund create permission that the refunds REST endpoint checks. A
+ * refund ID passes for users who could refund its order, so the lookup can name that order instead of failing
+ * as a permission error.
+ *
+ * @param mixed $input Ability input.
+ * @return bool
+ */
+ public static function can_refund_order( $input = array() ): bool {
+ return wc_rest_check_post_permissions( 'shop_order_refund', 'create' )
+ && ( self::is_refund_id_with_order_access( $input, 'edit' ) || self::can_edit_order( $input ) );
+ }
+
+ /**
+ * Check read access to the refunds of an order. A refund ID passes for users who could read its order, so the
+ * lookup can name that order instead of failing as a permission error.
+ *
+ * @param mixed $input Ability input.
+ * @return bool
+ */
+ public static function can_view_order_refunds( $input = array() ): bool {
+ return self::is_refund_id_with_order_access( $input, 'read' ) || self::can_view_order( $input );
+ }
+
+ /**
+ * Whether the input ID is a refund and the user has the given access to the order it belongs to.
+ *
+ * @param mixed $input Ability input.
+ * @param string $context `read` or `edit`, as for wc_rest_check_post_permissions().
+ * @return bool
+ */
+ private static function is_refund_id_with_order_access( $input, string $context ): bool {
+ $id = self::get_id_from_input( $input );
+ if ( $id <= 0 || 'shop_order_refund' !== OrderUtil::get_order_type( $id ) ) {
+ return false;
+ }
+
+ $refund = wc_get_order( $id );
+
+ return $refund instanceof \WC_Order_Refund
+ && $refund->get_parent_id() > 0
+ && self::check_order_permission( $refund->get_parent_id(), $context );
+ }
+
+ /**
+ * Get the output schema of a refund.
+ *
+ * @return array
+ */
+ protected static function get_refund_output_schema(): array {
+ $schema = array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Refund ID.', 'woocommerce' ),
+ ),
+ 'order_id' => array( 'type' => 'integer' ),
+ 'amount' => array( 'type' => 'string' ),
+ 'reason' => array(
+ 'type' => 'string',
+ 'description' => __( 'Reason for the refund. Omitted when none was given.', 'woocommerce' ),
+ ),
+ 'refunded_by' => array(
+ 'type' => 'integer',
+ 'description' => __( 'ID of the user who made the refund. Omitted when nobody was logged in.', 'woocommerce' ),
+ ),
+ 'refunded_payment' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether WooCommerce recorded that the payment gateway refunded the payment. False for a manual refund, but also when the gateway or an extension refunded it and the refund was not marked as paid, so check with the gateway when a refund error asked you to.', 'woocommerce' ),
+ ),
+ 'date_created' => array(
+ 'type' => 'string',
+ 'format' => 'date-time',
+ 'description' => __( 'Refund date in the store timezone.', 'woocommerce' ),
+ ),
+ 'line_items' => array(
+ 'type' => 'array',
+ 'description' => __( 'Order lines that the refund covers. Empty for a refund of an amount only.', 'woocommerce' ),
+ 'items' => array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'refunded_item_id' => array(
+ 'type' => 'integer',
+ 'description' => __( 'ID of the order line.', 'woocommerce' ),
+ ),
+ 'name' => array( 'type' => 'string' ),
+ 'quantity' => array( 'type' => 'number' ),
+ 'total' => array(
+ 'type' => 'string',
+ 'description' => __( 'Amount refunded for the line, excluding tax. Negative for a discount or credit line.', 'woocommerce' ),
+ ),
+ 'total_tax' => array( 'type' => 'string' ),
+ ),
+ 'additionalProperties' => false,
+ ),
+ ),
+ ),
+ 'additionalProperties' => false,
+ );
+
+ return ExtensibleAbilities::add_fields_schema( $schema, 'order_refund' );
+ }
+
+ /**
+ * Format a refund for the ability output.
+ *
+ * @param \WC_Order_Refund $refund Saved refund.
+ * @return array|\WP_Error
+ */
+ protected static function format_refund_for_response( \WC_Order_Refund $refund ) {
+ $data = array(
+ 'id' => $refund->get_id(),
+ 'order_id' => $refund->get_parent_id(),
+ 'amount' => self::format_amount_for_response( $refund->get_amount() ),
+ 'refunded_payment' => $refund->get_refunded_payment(),
+ 'line_items' => array(),
+ );
+
+ $reason = $refund->get_reason();
+ if ( is_scalar( $reason ) && ! is_bool( $reason ) && '' !== (string) $reason ) {
+ $data['reason'] = (string) $reason;
+ }
+
+ if ( $refund->get_refunded_by() > 0 ) {
+ $data['refunded_by'] = $refund->get_refunded_by();
+ }
+
+ $date_created = self::format_date_for_response( $refund->get_date_created(), false );
+ if ( null !== $date_created ) {
+ $data['date_created'] = $date_created;
+ }
+
+ foreach ( $refund->get_items( array( 'line_item', 'fee', 'shipping' ) ) as $item ) {
+ if ( ! $item instanceof \WC_Order_Item_Product && ! $item instanceof \WC_Order_Item_Fee && ! $item instanceof \WC_Order_Item_Shipping ) {
+ continue;
+ }
+ $data['line_items'][] = array(
+ 'refunded_item_id' => (int) $item->get_meta( '_refunded_item_id' ),
+ 'name' => $item->get_name(),
+ 'quantity' => abs( (float) $item->get_quantity() ),
+ 'total' => self::format_refunded_amount( $item->get_total() ),
+ 'total_tax' => self::format_refunded_amount( $item->get_total_tax() ),
+ );
+ }
+
+ return ExtensibleAbilities::add_fields_to_object( $data, 'order_refund', $refund );
+ }
+
+ /**
+ * Refund lines store the refunded amount negated, so a credit line, refunded with a negative amount, stays negative.
+ *
+ * @param string|float $stored Amount as stored on the refund line.
+ * @return string
+ */
+ private static function format_refunded_amount( $stored ): string {
+ $amount = (float) $stored;
+
+ return self::format_amount_for_response( 0.0 === $amount ? 0.0 : -$amount );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
index 7cad60c10b3..11571dada24 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -58,6 +58,8 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/order-update-status',
'woocommerce/order-add-note',
'woocommerce/order-notes-query',
+ 'woocommerce/order-refunds-query',
+ 'woocommerce/order-refund-create',
'woocommerce/payment-gateways-query',
'woocommerce/customers-query',
'woocommerce/customer-update',
@@ -378,6 +380,16 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'idempotent' => true,
'destructive' => false,
),
+ 'woocommerce/order-refunds-query' => array(
+ 'readonly' => true,
+ 'idempotent' => true,
+ 'destructive' => false,
+ ),
+ 'woocommerce/order-refund-create' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => true,
+ ),
'woocommerce/payment-gateways-query' => array(
'readonly' => true,
'idempotent' => true,
@@ -1222,6 +1234,19 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'id' => 1,
),
),
+ 'order-refunds-query' => array(
+ 'woocommerce/order-refunds-query',
+ array(
+ 'id' => 1,
+ ),
+ ),
+ 'order-refund-create' => array(
+ 'woocommerce/order-refund-create',
+ array(
+ 'id' => 1,
+ 'amount' => '1',
+ ),
+ ),
'payment-gateways-query' => array(
'woocommerce/payment-gateways-query',
array(),
@@ -2027,6 +2052,17 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/order-notes-query',
array( 'id' => -123 ),
),
+ 'order-refunds-query' => array(
+ 'woocommerce/order-refunds-query',
+ array( 'id' => -123 ),
+ ),
+ 'order-refund-create' => array(
+ 'woocommerce/order-refund-create',
+ array(
+ 'id' => -123,
+ 'amount' => '1',
+ ),
+ ),
);
}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderRefundAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderRefundAbilitiesTest.php
new file mode 100644
index 00000000000..f6c76f5275e
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderRefundAbilitiesTest.php
@@ -0,0 +1,1984 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\Jetpack\Constants;
+use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\Enums\PaymentGatewayFeature;
+use Automattic\WooCommerce\Internal\Abilities\Domain\OrderRefundCreate;
+use Automattic\WooCommerce\Internal\RestApi\Refunds\DataUtils;
+use Automattic\WooCommerce\Internal\Utilities\DatabaseTransaction;
+use WC_Helper_Order;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for the order-refund-create and order-refunds-query abilities.
+ */
+class OrderRefundAbilitiesTest extends WC_Unit_Test_Case {
+
+ /**
+ * Hooks of a refund, in the order they fire.
+ */
+ private const REFUND_HOOKS = array(
+ 'woocommerce_create_refund',
+ 'woocommerce_order_partially_refunded',
+ 'woocommerce_order_fully_refunded',
+ 'woocommerce_refund_created',
+ 'woocommerce_order_refunded',
+ );
+
+ /**
+ * Gateway that can refund, and records its refunds.
+ *
+ * @var \WC_Payment_Gateway
+ */
+ private $gateway;
+
+ /**
+ * Gateways registered before the test.
+ *
+ * @var array
+ */
+ private $original_gateways;
+
+ /**
+ * Hooks fired during the test, by name.
+ *
+ * @var string[]
+ */
+ private $fired = array();
+
+ /**
+ * A shop manager that every test acts as.
+ *
+ * @var int
+ */
+ private static $user_id;
+
+ /**
+ * Create the fixtures that no test changes beyond its own transaction.
+ *
+ * @param \WP_UnitTest_Factory $factory WordPress unit test factory.
+ */
+ public static function wpSetUpBeforeClass( $factory ): void {
+ self::$user_id = $factory->user->create( array( 'role' => 'shop_manager' ) );
+ }
+
+ /**
+ * Log in as a shop manager and register a gateway that supports refunds.
+ */
+ public function setUp(): void {
+ parent::setUp();
+
+ wp_set_current_user( self::$user_id );
+
+ $this->gateway = new class() extends \WC_Payment_Gateway {
+ /**
+ * Result that process_refund() returns.
+ *
+ * @var bool|\WP_Error
+ */
+ public $refund_result = true;
+
+ /**
+ * Amounts that process_refund() was called with.
+ *
+ * @var array
+ */
+ public $refunded = array();
+
+ /**
+ * Order IDs that process_refund() was called with.
+ *
+ * @var int[]
+ */
+ public $refunded_orders = array();
+
+ /**
+ * Set the ID and the refund support.
+ */
+ public function __construct() {
+ $this->id = 'refunding_gateway';
+ $this->enabled = 'yes';
+ $this->supports = array( PaymentGatewayFeature::PRODUCTS, PaymentGatewayFeature::REFUNDS );
+ }
+
+ /**
+ * Record the refund.
+ *
+ * @param int $order_id Order ID.
+ * @param float|null $amount Amount.
+ * @param string $reason Reason.
+ * @return bool|\WP_Error
+ */
+ public function process_refund( $order_id, $amount = null, $reason = '' ) {
+ $this->refunded[] = (string) $amount;
+ $this->refunded_orders[] = (int) $order_id;
+ return $this->refund_result;
+ }
+ };
+
+ $gateways = WC()->payment_gateways();
+ $this->original_gateways = $gateways->payment_gateways;
+ $gateways->payment_gateways['refunding_gateway'] = $this->gateway;
+
+ foreach ( self::REFUND_HOOKS as $hook ) {
+ add_action(
+ $hook,
+ function () use ( $hook ) {
+ $this->fired[] = $hook;
+ }
+ );
+ }
+ }
+
+ /**
+ * Restore the registered gateways.
+ */
+ public function tearDown(): void {
+ WC()->payment_gateways()->payment_gateways = $this->original_gateways;
+ parent::tearDown();
+ }
+
+ /**
+ * @testdox Should record a manual partial refund without calling the gateway.
+ */
+ public function test_records_manual_partial_refund(): void {
+ $order = $this->create_order();
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'reason' => 'Damaged box',
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( '10', $result['refund']['amount'] );
+ $this->assertSame( 'Damaged box', $result['refund']['reason'] );
+ $this->assertFalse( $result['refund']['refunded_payment'] );
+ $this->assertSame( array(), $this->gateway->refunded, 'A manual refund should not reach the gateway.' );
+
+ $order = wc_get_order( $order->get_id() );
+ $this->assertCount( 1, $order->get_refunds() );
+ $this->assertSame( $result['refund']['id'], $order->get_refunds()[0]->get_id() );
+ $this->assertSame( OrderStatus::PROCESSING, $order->get_status() );
+ }
+
+ /**
+ * @testdox Should refund a line through the gateway and mark the refund as paid back.
+ */
+ public function test_refunds_line_through_gateway(): void {
+ $order = $this->create_order();
+ $line_id = $this->get_product_line_id( $order );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'quantity' => 1,
+ ),
+ ),
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( array( 10.0 ), array_map( 'floatval', $this->gateway->refunded ) );
+ $this->assertTrue( $result['refund']['refunded_payment'] );
+ $this->assertSame( $line_id, $result['refund']['line_items'][0]['refunded_item_id'] );
+ $this->assertSame( 1.0, (float) $result['refund']['line_items'][0]['quantity'] );
+ $this->assertTrue( wc_get_order( $result['refund']['id'] )->get_refunded_payment() );
+ }
+
+ /**
+ * @testdox Should report a refunded credit line with a negative total.
+ */
+ public function test_reports_credit_line_as_negative(): void {
+ $order = $this->create_order();
+ $credit = new \WC_Order_Item_Fee();
+ $credit->set_name( 'Store credit' );
+ $credit->set_total( '-5' );
+ $order->add_item( $credit );
+ $order->calculate_totals( false );
+ $order->save();
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $this->get_product_line_id( $order ),
+ 'quantity' => 1,
+ ),
+ array(
+ 'line_item_id' => $credit->get_id(),
+ 'refund_total' => -5,
+ ),
+ ),
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $lines = array_column( $result['refund']['line_items'], 'total', 'refunded_item_id' );
+ $this->assertSame( -5.0, (float) $lines[ $credit->get_id() ] );
+ $this->assertSame( 10.0, (float) $lines[ $this->get_product_line_id( $order ) ] );
+ }
+
+ /**
+ * @testdox Should pass woocommerce_create_refund callbacks a refund that already has its ID, as wc_create_refund() does.
+ */
+ public function test_create_refund_hook_gets_refund_id(): void {
+ $order = $this->create_order_without_lines();
+ $hook_id = null;
+ add_action(
+ 'woocommerce_create_refund',
+ static function ( $refund ) use ( &$hook_id ) {
+ $hook_id = $refund->get_id();
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( $result['refund']['id'], $hook_id );
+ }
+
+ /**
+ * @testdox Should return the message of an extension that declines the refund by throwing, and save nothing.
+ */
+ public function test_returns_declined_refund_message(): void {
+ $order = $this->create_order_without_lines();
+ $declined = null;
+ add_action(
+ 'woocommerce_create_refund',
+ static function ( $refund ) use ( &$declined ) {
+ $declined = $refund;
+ throw new \Exception( 'Team seats are still in use.' );
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_declined', $result->get_error_code() );
+ $this->assertSame( 'Team seats are still in use.', $result->get_error_message() );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ $this->assertInstanceOf( \WC_Order_Refund::class, $declined );
+ $this->assertSame( 0, $declined->get_id(), 'The refund should be deleted, not only rolled back, for tables without transactions.' );
+ }
+
+ /**
+ * @testdox Should refuse a repeat of a refund it just made, and return that refund, so a retried call cannot refund twice.
+ */
+ public function test_refuses_repeated_refund(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ );
+ $first = $this->refund( $input );
+
+ $second = $this->refund( $input );
+
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertSame( 409, $second->get_error_data()['status'] );
+ $this->assertSame( $first['refund']['id'], $second->get_error_data()['refund']['id'] );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse a retry that lists the same lines in another order as a repeat of the refund.
+ */
+ public function test_refuses_repeated_refund_with_lines_reordered(): void {
+ $order = $this->create_order();
+ $product = array(
+ 'line_item_id' => $this->get_product_line_id( $order ),
+ 'quantity' => 1,
+ );
+ $shipping = array(
+ 'line_item_id' => array_key_first( $order->get_items( 'shipping' ) ),
+ 'refund_total' => 5,
+ );
+ $first = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array( $product, $shipping ),
+ )
+ );
+
+ $second = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array( $shipping, $product ),
+ )
+ );
+
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertSame( $first['refund']['id'], $second->get_error_data()['refund']['id'] );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse a retry of a full refund as a repeat with that refund, not as an order that cannot be refunded.
+ */
+ public function test_refuses_repeated_full_refund_as_duplicate(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '50',
+ );
+ $first = $this->refund( $input );
+
+ $second = $this->refund( $input );
+
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertSame( 409, $second->get_error_data()['status'] );
+ $this->assertSame( $first['refund']['id'], $second->get_error_data()['refund']['id'] );
+ }
+
+ /**
+ * @testdox Should allow a different refund of the same order right after another one.
+ */
+ public function test_allows_different_refund_right_after(): void {
+ $order = $this->create_order_without_lines();
+ $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertCount( 2, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should allow the same refund again once the duplicate window has passed.
+ */
+ public function test_allows_same_refund_after_window(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ );
+ $first = $this->refund( $input );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $refund = wc_get_order( $first['refund']['id'] );
+ $refund->set_date_created( time() - 11 * MINUTE_IN_SECONDS );
+ $refund->save();
+
+ $result = $this->refund( $input );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertCount( 2, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should make the same refund again when allow_duplicate_of names the refund it repeats, and refuse a retry of that call.
+ */
+ public function test_allow_duplicate_of_makes_the_same_refund_again(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ );
+ $first = $this->refund( $input );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $refused = $this->refund( $input );
+ $this->assertStringContainsString( 'allow_duplicate_of set to ' . $first['refund']['id'], $refused->get_error_message() );
+
+ $repeat = $this->refund( array_merge( $input, array( 'allow_duplicate_of' => $first['refund']['id'] ) ) );
+ $retry = $this->refund( array_merge( $input, array( 'allow_duplicate_of' => $first['refund']['id'] ) ) );
+
+ $this->assertIsArray( $repeat, is_wp_error( $repeat ) ? $repeat->get_error_message() : '' );
+ $this->assertNotSame( $first['refund']['id'], $repeat['refund']['id'] );
+ $this->assertWPError( $retry );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $retry->get_error_code() );
+ $this->assertSame( $repeat['refund']['id'], $retry->get_error_data()['refund']['id'] );
+ $this->assertCount( 2, wc_get_order( $order->get_id() )->get_refunds() );
+
+ $third = $this->refund( array_merge( $input, array( 'allow_duplicate_of' => $repeat['refund']['id'] ) ) );
+ $stale = $this->refund( array_merge( $input, array( 'allow_duplicate_of' => $first['refund']['id'] ) ) );
+
+ $this->assertIsArray( $third, is_wp_error( $third ) ? $third->get_error_message() : '' );
+ $this->assertWPError( $stale );
+ $this->assertSame( $third['refund']['id'], $stale->get_error_data()['refund']['id'] );
+ $this->assertCount( 3, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should accept allow_duplicate_of for the refund that a duplicate error named after the window has passed.
+ */
+ public function test_allow_duplicate_of_accepts_the_named_refund_after_the_window(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ );
+ $first = $this->refund( $input );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $this->assertWPError( $this->refund( $input ) );
+ $refund = wc_get_order( $first['refund']['id'] );
+ $refund->set_date_created( time() - 15 * MINUTE_IN_SECONDS );
+ $refund->save();
+
+ $result = $this->refund( array_merge( $input, array( 'allow_duplicate_of' => $first['refund']['id'] ) ) );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertCount( 2, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse allow_duplicate_of past the window for a refund of another order or a refund the call does not repeat.
+ * @testWith [true, "10"]
+ * [false, "5"]
+ *
+ * @param bool $other_order Whether the named refund belongs to another order.
+ * @param string $amount Amount of the call that names the refund.
+ */
+ public function test_allow_duplicate_of_refuses_an_older_refund_it_does_not_repeat( bool $other_order, string $amount ): void {
+ $named_order = $this->create_order_without_lines();
+ $order = $other_order ? $this->create_order_without_lines() : $named_order;
+ $named = $this->refund(
+ array(
+ 'id' => $named_order->get_id(),
+ 'amount' => '10',
+ )
+ );
+ $this->assertIsArray( $named, is_wp_error( $named ) ? $named->get_error_message() : '' );
+ $refund = wc_get_order( $named['refund']['id'] );
+ $refund->set_date_created( time() - 15 * MINUTE_IN_SECONDS );
+ $refund->save();
+ $count = count( wc_get_order( $order->get_id() )->get_refunds() );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => $amount,
+ 'allow_duplicate_of' => $named['refund']['id'],
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate_mismatch', $result->get_error_code() );
+ $this->assertStringStartsWith( 'Refund ' . $named['refund']['id'] . ' is not a refund of this order with the same amount and lines,', $result->get_error_message() );
+ $this->assertCount( $count, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should name an engine error code that has no mapping as invalid_request, keeping its message, status and code in the data.
+ */
+ public function test_names_unmapped_engine_error_as_invalid_request(): void {
+ $order = $this->create_order_without_lines();
+ $engine = $this->createMock( DataUtils::class );
+ $engine->method( 'prepare_refund_creation_or_error' )->willReturn( new \WP_Error( 'new_engine_check', 'Engine refused.', array( 'status' => 422 ) ) );
+ wc_get_container()->replace( DataUtils::class, $engine );
+
+ try {
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+ } finally {
+ wc_get_container()->reset_replacement( DataUtils::class );
+ }
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_invalid_request', $result->get_error_code() );
+ $this->assertSame( 'Engine refused.', $result->get_error_message() );
+ $this->assertSame( 422, $result->get_error_data()['status'] );
+ $this->assertSame( 'new_engine_check', $result->get_error_data()['engine_code'] );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should name the missing fields when the call sends neither amount nor line_items, before it locks the order.
+ */
+ public function test_refuses_refund_without_amount_or_lines(): void {
+ global $wpdb;
+ $order = $this->create_order_without_lines();
+
+ $result = $this->refund( array( 'id' => $order->get_id() ) );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_missing_amount', $result->get_error_code() );
+ $this->assertSame( 400, $result->get_error_data()['status'] );
+ $this->assertStringContainsString( 'Send amount, line_items, or both.', $result->get_error_message() );
+ $this->assertNull( $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", 'woocommerce_ability_order_refund_lock_' . $order->get_id() ) ) );
+ }
+
+ /**
+ * @testdox Should keep the field name refund_total in the error code of a line refund above the line.
+ */
+ public function test_names_refund_total_in_line_error_code(): void {
+ $order = $this->create_order();
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $this->get_product_line_id( $order ),
+ 'refund_total' => 9999,
+ ),
+ ),
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_refund_total_exceeds_line', $result->get_error_code() );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse allow_duplicate_of when the input does not repeat that refund, and not copy the refund from its ID.
+ * @testWith [{"amount":"5"}, 0, "woocommerce_ability_order_refund_duplicate_mismatch"]
+ * [{"amount":"10"}, 99999999, "woocommerce_ability_order_refund_duplicate_mismatch"]
+ * [{}, 0, "woocommerce_ability_order_refund_missing_amount"]
+ *
+ * @param array $input Input sent with allow_duplicate_of.
+ * @param int $allowed_id Refund ID to send, or 0 for the ID of the refund made first.
+ * @param string $error_code Expected error code.
+ */
+ public function test_allow_duplicate_of_refuses_refund_it_does_not_repeat( array $input, int $allowed_id, string $error_code ): void {
+ $order = $this->create_order_without_lines();
+ $first = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+
+ $result = $this->refund(
+ array_merge(
+ $input,
+ array(
+ 'id' => $order->get_id(),
+ 'allow_duplicate_of' => $allowed_id ? $allowed_id : $first['refund']['id'],
+ )
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( $error_code, $result->get_error_code() );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should allow a retry after the gateway refused, since no refund was made.
+ */
+ public function test_allows_retry_after_gateway_refusal(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ );
+ $this->gateway->refund_result = new \WP_Error( 'declined', 'Card issuer declined the refund.' );
+ $refused = $this->refund( $input );
+
+ $this->assertWPError( $refused );
+ $this->assertSame( 'woocommerce_ability_order_refund_gateway_failed', $refused->get_error_code() );
+ $this->assertCount( 1, $this->gateway->refunded );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+
+ $this->gateway->refund_result = true;
+ $result = $this->refund( $input );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertCount( 2, $this->gateway->refunded );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse a refund while another refund of the order holds its lock.
+ */
+ public function test_refuses_refund_while_order_is_locked(): void {
+ $order = $this->create_order_without_lines();
+ add_option( 'woocommerce_ability_order_refund_lock_' . $order->get_id(), time() + MINUTE_IN_SECONDS, '', false );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_in_progress', $result->get_error_code() );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should release the lock of the order after a refund, so the next refund can run.
+ */
+ public function test_releases_order_lock(): void {
+ $order = $this->create_order_without_lines();
+
+ $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+
+ wp_cache_delete( 'notoptions', 'options' );
+ $this->assertFalse( get_option( 'woocommerce_ability_order_refund_lock_' . $order->get_id() ) );
+ }
+
+ /**
+ * @testdox Should save nothing when another call took over the lock of the order while the refund was checked.
+ */
+ public function test_refuses_refund_when_lock_was_taken_over(): void {
+ global $wpdb;
+
+ $order = $this->create_order_without_lines();
+ $lock_name = 'woocommerce_ability_order_refund_lock_' . $order->get_id();
+ $taken = (string) ( time() + HOUR_IN_SECONDS );
+ $hook = null;
+ $hook = static function ( $results ) use ( $wpdb, $lock_name, $taken, &$hook ) {
+ remove_filter( 'woocommerce_order_query', $hook );
+ $wpdb->update( $wpdb->options, array( 'option_value' => $taken ), array( 'option_name' => $lock_name ) );
+ return $results;
+ };
+ add_filter( 'woocommerce_order_query', $hook );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_lock_lost', $result->get_error_code() );
+ $this->assertSame( 409, $result->get_error_data()['status'] );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ $this->assertSame( array(), $this->gateway->refunded );
+ $this->assertSame( $taken, $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $lock_name ) ), 'The lock of the other call should be kept.' );
+ }
+
+ /**
+ * @testdox Should finish the outer refund against its own order when a woocommerce_create_refund callback refunds another order without transactions.
+ */
+ public function test_nested_refund_keeps_outer_refund_state(): void {
+ Constants::set_constant( 'WC_USE_TRANSACTIONS', false );
+ $order = $this->create_order_without_lines();
+ $other = $this->create_order_without_lines();
+ $started = false;
+ $nested = null;
+ add_action(
+ 'woocommerce_create_refund',
+ function () use ( $other, &$started, &$nested ) {
+ if ( ! $started ) {
+ $started = true;
+ $nested = $this->refund(
+ array(
+ 'id' => $other->get_id(),
+ 'amount' => '5',
+ 'refund_payment' => true,
+ )
+ );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertIsArray( $nested, is_wp_error( $nested ) ? $nested->get_error_message() : '' );
+ $this->assertSame( $other->get_id(), $nested['refund']['order_id'] );
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( '10', $result['refund']['amount'] );
+ $this->assertSame( $order->get_id(), $result['refund']['order_id'] );
+ $this->assertSame( array( '5', '10' ), $this->gateway->refunded, 'Each order should reach the gateway once, with its own amount.' );
+ $this->assertSame( array( $other->get_id(), $order->get_id() ), $this->gateway->refunded_orders );
+
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertSame( 10.0, (float) $refunds[0]->get_amount() );
+ $this->assertCount( 1, wc_get_order( $other->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should say not to refund again when a hook fails after the gateway refunded and wc_create_refund() deletes the refund.
+ */
+ public function test_reports_lost_refund_when_a_hook_fails_after_the_gateway(): void {
+ $order = $this->create_order_without_lines();
+ add_action(
+ 'woocommerce_order_partially_refunded',
+ static function () {
+ throw new \Exception( 'Loyalty points service is down.' );
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_lost', $result->get_error_code() );
+ $this->assertStringContainsString( 'The payment gateway refunded the payment', $result->get_error_message() );
+ $this->assertStringContainsString( 'Do not refund again.', $result->get_error_message() );
+ $this->assertStringContainsString( 'Loyalty points service is down.', $result->get_error_message() );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should report an incomplete refund, and say not to refund again, when the save after woocommerce_create_refund fails, as wc_create_refund() goes on to the gateway.
+ */
+ public function test_reports_incomplete_when_the_save_after_the_create_hook_fails(): void {
+ $order = $this->create_order_without_lines();
+ $hook_ran = false;
+ add_action(
+ 'woocommerce_create_refund',
+ static function () use ( &$hook_ran ) {
+ $hook_ran = true;
+ }
+ );
+ add_action(
+ 'woocommerce_before_order_refund_object_save',
+ static function () use ( &$hook_ran ) {
+ if ( $hook_ran ) {
+ throw new \Exception( 'Refund table is read-only.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_incomplete', $result->get_error_code() );
+ $this->assertStringContainsString( 'Refund table is read-only.', $result->get_error_message() );
+ $this->assertStringContainsString( 'Do not refund again.', $result->get_error_message() );
+ $this->assertTrue( $result->get_error_data()['refunded_payment'] );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should refuse a retry of a refund whose paid flag was not saved, even after the duplicate window, and also with allow_duplicate_of.
+ */
+ public function test_refuses_retry_of_unpaid_refund_after_window(): void {
+ $order = $this->create_order_without_lines();
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ );
+ $first = $this->refund( $input );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $refund = wc_get_order( $first['refund']['id'] );
+ $refund->set_refunded_payment( false );
+ $refund->set_date_created( time() - 11 * MINUTE_IN_SECONDS );
+ $refund->save();
+
+ $retry = $this->refund( $input );
+ $override = $this->refund( array_merge( $input, array( 'allow_duplicate_of' => $first['refund']['id'] ) ) );
+
+ $this->assertWPError( $retry );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $retry->get_error_code() );
+ $this->assertStringContainsString( 'may have refunded the payment', $retry->get_error_message() );
+ $this->assertWPError( $override );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $override->get_error_code() );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse the same refund sent again with its line total filled in, as a repeat of the refund.
+ */
+ public function test_refuses_same_refund_sent_in_another_form(): void {
+ $order = $this->create_order();
+ $line_id = $this->get_product_line_id( $order );
+ $first = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'quantity' => 1,
+ ),
+ ),
+ )
+ );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+
+ $second = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'quantity' => 1,
+ 'refund_total' => (float) $first['refund']['amount'],
+ ),
+ ),
+ )
+ );
+
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should round the amount to the store decimals before the gateway gets it.
+ */
+ public function test_rounds_amount_to_store_decimals(): void {
+ $order = $this->create_order_without_lines();
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10.004',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should refuse to refund more than the order can still refund, and save nothing.
+ */
+ public function test_refuses_more_than_refundable(): void {
+ $order = $this->create_order_without_lines();
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '60',
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_exceeds_remaining', $result->get_error_code() );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ $this->assertSame( array(), $this->fired );
+ }
+
+ /**
+ * @testdox Should refuse a gateway refund when the gateway of the order cannot refund.
+ */
+ public function test_refuses_gateway_refund_without_support(): void {
+ $order = $this->create_order_without_lines( 'bacs' );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_gateway_unsupported', $result->get_error_code() );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should delete the refund and fail when the gateway refuses.
+ */
+ public function test_gateway_refusal_leaves_no_refund(): void {
+ $order = $this->create_order_without_lines();
+ $this->gateway->refund_result = new \WP_Error( 'declined', 'Card issuer declined the refund.' );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_gateway_failed', $result->get_error_code() );
+ $this->assertStringContainsString( 'Card issuer declined the refund.', $result->get_error_message() );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ $this->assertNotContains( 'woocommerce_order_refunded', $this->fired );
+ }
+
+ /**
+ * @testdox Should mark the order refunded when the refund covers the rest of it.
+ */
+ public function test_full_refund_marks_order_refunded(): void {
+ $order = $this->create_order();
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '50',
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( OrderStatus::REFUNDED, wc_get_order( $order->get_id() )->get_status() );
+ $this->assertContains( 'woocommerce_order_fully_refunded', $this->fired );
+ }
+
+ /**
+ * @testdox Should return the refunded quantity to stock when asked.
+ */
+ public function test_restocks_refunded_quantity(): void {
+ $order = $this->create_order();
+ $product = wc_get_product( $order->get_items()[ $this->get_product_line_id( $order ) ]->get_product_id() );
+ $product->set_manage_stock( true );
+ $product->set_stock_quantity( 10 );
+ $product->save();
+ wc_reduce_stock_levels( $order->get_id() );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $this->get_product_line_id( $order ),
+ 'quantity' => 2,
+ ),
+ ),
+ 'restock_items' => true,
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( 8, wc_get_product( $product->get_id() )->get_stock_quantity(), 'Four units were sold from 10, and two came back.' );
+ }
+
+ /**
+ * @testdox Should create the same refund and fire the same hooks as wc_create_refund().
+ */
+ public function test_matches_wc_create_refund(): void {
+ $args = array();
+ foreach ( array( 'woocommerce_create_refund', 'woocommerce_refund_created' ) as $hook ) {
+ add_action(
+ $hook,
+ static function ( $refund, $hook_args ) use ( $hook, &$args ) {
+ unset( $refund ); // Avoid parameter not used PHPCS errors.
+ $args[ $hook ][] = $hook_args;
+ },
+ 10,
+ 2
+ );
+ }
+
+ $legacy_order = $this->create_order();
+ $legacy = wc_create_refund(
+ array(
+ 'order_id' => $legacy_order->get_id(),
+ 'amount' => 10,
+ 'reason' => 'Parity',
+ 'line_items' => wc_get_container()->get( \Automattic\WooCommerce\Internal\RestApi\Refunds\DataUtils::class )->prepare_refund_creation_or_error(
+ $legacy_order,
+ array(
+ array(
+ 'line_item_id' => $this->get_product_line_id( $legacy_order ),
+ 'quantity' => 1,
+ ),
+ ),
+ false,
+ null,
+ 'test'
+ )['line_items'],
+ )
+ );
+ $legacy_hooks = $this->fired;
+ $this->fired = array();
+
+ $order = $this->create_order();
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'reason' => 'Parity',
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $this->get_product_line_id( $order ),
+ 'quantity' => 1,
+ ),
+ ),
+ )
+ );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( $legacy_hooks, $this->fired, 'The hooks should fire in the same order.' );
+ foreach ( $args as $hook => $calls ) {
+ $this->assertCount( 2, $calls, $hook );
+ $this->assertSame( array_merge( array_keys( $calls[0] ), array( OrderRefundCreate::CALL_ARG ) ), array_keys( $calls[1] ), "$hook should get the arguments of wc_create_refund() and the call marker." );
+ $this->assertSame( $legacy_order->get_id(), $calls[0]['order_id'], $hook );
+ $this->assertSame( $order->get_id(), $calls[1]['order_id'], $hook );
+ $this->assertSame( $calls[0]['refund_id'], $calls[1]['refund_id'], $hook );
+ }
+
+ $this->assertInstanceOf( \WC_Order_Refund::class, $legacy );
+ $legacy = wc_get_order( $legacy->get_id() );
+ $refund = wc_get_order( $result['refund']['id'] );
+ $this->assertInstanceOf( \WC_Order_Refund::class, $legacy );
+ $this->assertInstanceOf( \WC_Order_Refund::class, $refund );
+ $this->assertSame( $legacy->get_amount(), $refund->get_amount() );
+ $this->assertSame( $legacy->get_total(), $refund->get_total() );
+ $this->assertSame( $legacy->get_total_tax(), $refund->get_total_tax() );
+ $this->assertSame(
+ $this->describe_lines( $legacy, $legacy_order ),
+ $this->describe_lines( $refund, $order )
+ );
+ $this->assertSame( wc_get_order( $legacy_order->get_id() )->get_status(), wc_get_order( $order->get_id() )->get_status() );
+ }
+
+ /**
+ * @testdox Should list the refunds of an order newest first, and only those in include when it is sent.
+ */
+ public function test_query_lists_refunds(): void {
+ $order = $this->create_order_without_lines();
+ $first = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 5,
+ 'date_created' => '2026-01-01 10:00:00',
+ )
+ );
+ $second = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 7,
+ 'reason' => 'Late delivery',
+ 'date_created' => '2026-01-02 10:00:00',
+ )
+ );
+ $query = wp_get_ability( 'woocommerce/order-refunds-query' );
+
+ $all = $query->execute( array( 'id' => $order->get_id() ) );
+ $included = $query->execute(
+ array(
+ 'id' => $order->get_id(),
+ 'include' => array( $first->get_id() ),
+ )
+ );
+
+ $this->assertIsArray( $all, is_wp_error( $all ) ? $all->get_error_message() : '' );
+ $this->assertSame( 2, $all['total'] );
+ $this->assertSame( array( $second->get_id(), $first->get_id() ), array_column( $all['refunds'], 'id' ) );
+ $this->assertSame( 'Late delivery', $all['refunds'][0]['reason'] );
+ $this->assertArrayNotHasKey( 'reason', $all['refunds'][1], 'A refund without a reason should omit the field.' );
+ $this->assertSame( array( $first->get_id() ), array_column( $included['refunds'], 'id' ) );
+ $this->assertSame( 1, $included['total'] );
+ }
+
+ /**
+ * @testdox Should list refunds made in the same second newest first, by ID, and still put an older refund last.
+ */
+ public function test_query_orders_refunds_of_the_same_second_by_id(): void {
+ $order = $this->create_order_without_lines();
+ $ids = array();
+ foreach ( array( '2026-01-02 10:00:00', '2026-01-02 10:00:00', '2026-01-02 10:00:00', '2026-01-01 10:00:00' ) as $date ) {
+ $ids[] = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 1,
+ 'date_created' => $date,
+ )
+ )->get_id();
+ }
+
+ $result = wp_get_ability( 'woocommerce/order-refunds-query' )->execute( array( 'id' => $order->get_id() ) );
+
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( array( $ids[2], $ids[1], $ids[0], $ids[3] ), array_column( $result['refunds'], 'id' ) );
+ }
+
+ /**
+ * @testdox Should refuse the same line refund sent again with only its total, as a repeat of the refund.
+ */
+ public function test_refuses_same_line_refund_sent_as_total_only(): void {
+ $order = $this->create_order();
+ $line_id = $this->get_product_line_id( $order );
+ $first = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'quantity' => 1,
+ ),
+ ),
+ )
+ );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+
+ $second = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'refund_total' => (float) $first['refund']['amount'],
+ ),
+ ),
+ )
+ );
+
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should name the newest refund that the call repeats, so one allow_duplicate_of is enough when the same refund was made in two forms.
+ */
+ public function test_duplicate_error_names_the_newest_refund_the_call_repeats(): void {
+ $order = $this->create_order();
+ $line_id = $this->get_product_line_id( $order );
+ $quantity = array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'quantity' => 1,
+ ),
+ ),
+ );
+ $first = $this->refund( $quantity );
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $second = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'line_items' => array(
+ array(
+ 'line_item_id' => $line_id,
+ 'refund_total' => 10,
+ ),
+ ),
+ 'allow_duplicate_of' => $first['refund']['id'],
+ )
+ );
+ $this->assertIsArray( $second, is_wp_error( $second ) ? $second->get_error_message() : '' );
+
+ $repeat = $this->refund( $quantity );
+
+ $this->assertWPError( $repeat );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $repeat->get_error_code() );
+ $this->assertStringContainsString( 'allow_duplicate_of set to ' . $second['refund']['id'] . '.', $repeat->get_error_message() );
+ $confirmed = $this->refund( $quantity + array( 'allow_duplicate_of' => $second['refund']['id'] ) );
+ $this->assertIsArray( $confirmed, is_wp_error( $confirmed ) ? $confirmed->get_error_message() : '' );
+ $this->assertCount( 3, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should refuse a refund to a user who can edit the order but may not create refunds, as the refunds REST endpoint does.
+ */
+ public function test_refuses_refund_without_refund_create_permission(): void {
+ $order = $this->create_order_without_lines();
+ add_filter(
+ 'woocommerce_rest_check_permissions',
+ static function ( $permission, $context, $object_id, $post_type ) {
+ unset( $object_id );
+ return 'shop_order_refund' === $post_type && 'create' === $context ? false : $permission;
+ },
+ 10,
+ 4
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code() );
+ $this->assertSame( array(), $this->gateway->refunded );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should name the refund that is still on the order, and not ask to record it manually, when an extension stops its deletion after a failure.
+ *
+ * @testWith ["woocommerce_order_partially_refunded", true]
+ * ["woocommerce_after_order_refund_object_save", false]
+ *
+ * @param string $hook Hook that fails.
+ * @param bool $refund_payment Whether the call refunds the payment.
+ */
+ public function test_names_the_kept_refund_when_its_deletion_is_stopped( string $hook, bool $refund_payment ): void {
+ $order = $this->create_order_without_lines();
+ add_filter( 'woocommerce_pre_delete_order_refund', '__return_false' );
+ add_action(
+ $hook,
+ static function () use ( $hook ) {
+ if ( 'woocommerce_order_partially_refunded' === $hook ) {
+ throw new \Exception( 'Loyalty points service is down.' );
+ }
+ throw new \Error( 'Loyalty points service is down.' );
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => $refund_payment,
+ )
+ );
+
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_incomplete', $result->get_error_code() );
+ $this->assertSame( $refunds[0]->get_id(), $result->get_error_data()['refund_id'] );
+ $this->assertStringContainsString( 'Refund ' . $refunds[0]->get_id() . ' is still on the order', $result->get_error_message() );
+ $this->assertStringContainsString( 'Loyalty points service is down.', $result->get_error_message() );
+ $this->assertStringNotContainsString( 'manually', $result->get_error_message() );
+ }
+
+ /**
+ * @testdox Should report a lock that fails with a database error as such, not as a refund in progress.
+ */
+ public function test_reports_lock_database_error(): void {
+ global $wpdb;
+ $order = $this->create_order_without_lines();
+ $break = static function ( string $query ) use ( $wpdb ): string {
+ return 0 === strpos( $query, "INSERT IGNORE INTO {$wpdb->options}" ) && false !== strpos( $query, 'woocommerce_ability_order_refund_lock_' )
+ ? "INSERT IGNORE INTO {$wpdb->prefix}no_such_table (a) VALUES (1)"
+ : $query;
+ };
+ $errors = $wpdb->suppress_errors( true );
+ add_filter( 'query', $break );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+
+ remove_filter( 'query', $break );
+ $wpdb->suppress_errors( $errors );
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_lock_failed', $result->get_error_code() );
+ $this->assertSame( 500, $result->get_error_data()['status'] );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should report a database error while the refund checks its lock as such, not as a lock taken over, and refund nothing.
+ */
+ public function test_reports_lock_check_database_error(): void {
+ global $wpdb;
+ $order = $this->create_order_without_lines();
+ $break = static function ( string $query ) use ( $wpdb ): string {
+ return 0 === strpos( $query, "SELECT option_value FROM {$wpdb->options}" ) && false !== strpos( $query, 'woocommerce_ability_order_refund_lock_' )
+ ? "SELECT option_value FROM {$wpdb->prefix}no_such_table"
+ : $query;
+ };
+ $errors = $wpdb->suppress_errors( true );
+ add_filter( 'query', $break );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ remove_filter( 'query', $break );
+ $wpdb->suppress_errors( $errors );
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_lock_failed', $result->get_error_code() );
+ $this->assertSame( array(), $this->gateway->refunded );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should delete the refund and say nothing was refunded when an Error is thrown while the refund is saved before woocommerce_create_refund.
+ */
+ public function test_reports_failed_refund_when_a_save_before_the_create_hook_crashes(): void {
+ $order = $this->create_order_without_lines();
+ $hook_ran = false;
+ add_action(
+ 'woocommerce_after_order_refund_object_save',
+ static function () {
+ throw new \Error( 'Extension save hook crashed.' );
+ }
+ );
+ add_action(
+ 'woocommerce_create_refund',
+ static function () use ( &$hook_ran ) {
+ $hook_ran = true;
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_failed', $result->get_error_code() );
+ $this->assertStringContainsString( 'before it was sent to the payment gateway, so no refund was created and no money was returned', $result->get_error_message() );
+ $this->assertStringContainsString( 'ask the merchant to check it before you refund again', $result->get_error_message() );
+ $this->assertStringContainsString( 'Extension save hook crashed.', $result->get_error_message() );
+ $this->assertFalse( $hook_ran );
+ $this->assertSame( array(), $this->gateway->refunded );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * @testdox Should delete only the new refund, not an older one that a callback saved during the call, when an Error is thrown before woocommerce_create_refund.
+ */
+ public function test_crash_before_the_create_hook_keeps_an_older_refund_saved_during_the_call(): void {
+ $order = $this->create_order_without_lines();
+ $older = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+ $this->assertIsArray( $older, is_wp_error( $older ) ? $older->get_error_message() : '' );
+ $older_id = $older['refund']['id'];
+ $resaved = false;
+ add_filter(
+ 'woocommerce_order_get_items',
+ static function ( $items, $refund ) use ( $order, $older_id, &$resaved ) {
+ if ( ! $resaved && $refund instanceof \WC_Order_Refund && 0 === $refund->get_id() && $refund->get_parent_id() === $order->get_id() ) {
+ $resaved = true;
+ $saved = wc_get_order( $older_id );
+ $saved->set_reason( 'Touched by an extension.' );
+ $saved->save();
+ }
+ return $items;
+ },
+ 10,
+ 2
+ );
+ add_action(
+ 'woocommerce_after_order_refund_object_save',
+ static function ( $refund ) use ( $older_id ) {
+ if ( $refund->get_id() !== $older_id ) {
+ throw new \Error( 'Extension save hook crashed.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ )
+ );
+
+ $this->assertTrue( $resaved );
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_failed', $result->get_error_code() );
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertSame( $older_id, $refunds[0]->get_id() );
+ }
+
+ /**
+ * @testdox Should tag and delete only its own refund, not a gateway refund of the same order that a callback makes during the call, when an Error follows.
+ */
+ public function test_crash_keeps_a_gateway_refund_that_a_callback_made_during_the_call(): void {
+ $order = $this->create_order_without_lines();
+ $nested = null;
+ $crashed = false;
+ $hooked = false;
+ add_action(
+ 'woocommerce_create_refund',
+ static function ( $refund ) use ( &$hooked ) {
+ $hooked = $hooked || '5' === (string) $refund->get_amount();
+ }
+ );
+ add_action(
+ 'woocommerce_after_order_refund_object_save',
+ static function ( $refund ) use ( $order, &$nested, &$crashed, &$hooked ) {
+ if ( null === $nested && '5' === (string) $refund->get_amount() ) {
+ $nested = wc_create_refund(
+ array(
+ 'amount' => '2',
+ 'order_id' => $order->get_id(),
+ 'refund_payment' => true,
+ )
+ );
+ return;
+ }
+ if ( ! $crashed && $hooked && '5' === (string) $refund->get_amount() ) {
+ $crashed = true;
+ throw new \Error( 'Extension save hook crashed.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assertInstanceOf( \WC_Order_Refund::class, $nested );
+ $this->assertTrue( $crashed );
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_lost', $result->get_error_code() );
+ $this->assertSame( array( '2' ), $this->gateway->refunded );
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertSame( $nested->get_id(), $refunds[0]->get_id() );
+ $this->assertTrue( $refunds[0]->get_refunded_payment() );
+ $this->assertSame( '', (string) $refunds[0]->get_meta( '_woocommerce_ability_refund_fingerprint' ) );
+ }
+
+ /**
+ * @testdox Should keep a gateway refund of the same amount and user that a callback makes before the call's refund is first saved, without the call's fingerprints.
+ *
+ * @testWith [false]
+ * [true]
+ *
+ * @param bool $crash Whether an Error follows before woocommerce_create_refund of the call's refund.
+ */
+ public function test_keeps_a_same_amount_refund_made_before_the_first_save( bool $crash ): void {
+ $order = $this->create_order_without_lines();
+ $nested = null;
+ $inside = false;
+ $crashed = false;
+ add_filter(
+ 'woocommerce_order_get_items',
+ static function ( $items, $refund ) use ( $order, &$nested, &$inside ) {
+ if ( ! $inside && null === $nested && $refund instanceof \WC_Order_Refund && 0 === $refund->get_id() ) {
+ $inside = true;
+ $nested = wc_create_refund(
+ array(
+ 'amount' => '5',
+ 'order_id' => $order->get_id(),
+ 'refund_payment' => true,
+ )
+ );
+ $inside = false;
+ }
+ return $items;
+ },
+ 10,
+ 2
+ );
+ add_action(
+ 'woocommerce_after_order_refund_object_save',
+ static function ( $refund ) use ( $crash, &$nested, &$inside, &$crashed ) {
+ if ( $crash && ! $crashed && ! $inside && null !== $nested && $refund !== $nested ) {
+ $crashed = true;
+ throw new \Error( 'Extension save hook crashed.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assertInstanceOf( \WC_Order_Refund::class, $nested );
+ $this->assertSame( $crash, $crashed );
+ $this->assertSame( array( '5' ), $this->gateway->refunded );
+ $kept = wc_get_order( $nested->get_id() );
+ $this->assertInstanceOf( \WC_Order_Refund::class, $kept );
+ $this->assertTrue( $kept->get_refunded_payment() );
+ $this->assertSame( '', (string) $kept->get_meta( '_woocommerce_ability_refund_fingerprint' ) );
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ if ( $crash ) {
+ $this->assertWPError( $result );
+ $this->assertCount( 1, $refunds );
+ return;
+ }
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertCount( 2, $refunds );
+ $this->assertNotSame( '', (string) wc_get_order( $result['refund']['id'] )->get_meta( '_woocommerce_ability_refund_fingerprint' ) );
+ }
+
+ /**
+ * @testdox Should leave a paid refund that it cannot tell for its own alone, and say to check the refunds before a retry, when an Error follows.
+ */
+ public function test_leaves_an_unconfirmed_paid_refund_alone_after_an_error(): void {
+ $order = $this->create_order_without_lines();
+ $built = null;
+ add_filter(
+ 'woocommerce_order_get_items',
+ static function ( $items, $refund ) use ( $order, &$built ) {
+ if ( null === $built && $refund instanceof \WC_Order_Refund && 0 === $refund->get_id() ) {
+ $built = new \WC_Order_Refund();
+ $built->set_parent_id( $order->get_id() );
+ $built->set_amount( '3' );
+ $built->set_refunded_payment( true );
+ $built->save();
+ }
+ return $items;
+ },
+ 10,
+ 2
+ );
+ add_action(
+ 'woocommerce_after_order_refund_object_save',
+ static function ( $refund ) use ( &$built ) {
+ if ( null !== $built && $refund !== $built ) {
+ throw new \Error( 'Extension save hook crashed.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_failed', $result->get_error_code() );
+ $this->assertSame( $built->get_id(), $result->get_error_data()['refund_id'] );
+ $this->assertStringContainsString( 'could not confirm that it made it', $result->get_error_message() );
+ $this->assertStringNotContainsString( 'no money was returned', $result->get_error_message() );
+ $this->assertInstanceOf( \WC_Order_Refund::class, wc_get_order( $built->get_id() ) );
+ $this->assertSame( array(), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should keep a paid refund, and refuse the retry, when an extension changes its reason before its first save and an Error follows the gateway.
+ */
+ public function test_keeps_a_paid_refund_and_refuses_retry_when_an_error_follows_the_gateway(): void {
+ $order = $this->create_order_without_lines();
+ $thrown = false;
+ add_filter(
+ 'woocommerce_order_get_items',
+ static function ( $items, $refund ) {
+ if ( $refund instanceof \WC_Order_Refund && 0 === $refund->get_id() ) {
+ $refund->set_reason( 'Normalized by an extension.' );
+ }
+ return $items;
+ },
+ 10,
+ 2
+ );
+ add_action(
+ 'woocommerce_order_partially_refunded',
+ static function () use ( &$thrown ) {
+ if ( ! $thrown ) {
+ $thrown = true;
+ throw new \Error( 'Notification service crashed.' );
+ }
+ }
+ );
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ 'reason' => 'Damaged parcel',
+ 'refund_payment' => true,
+ );
+
+ $first = $this->refund( $input );
+ $second = $this->refund( $input );
+
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertTrue( $refunds[0]->get_refunded_payment() );
+ $this->assertWPError( $first );
+ $this->assertSame( 'woocommerce_ability_order_refund_incomplete', $first->get_error_code() );
+ $this->assertSame( $refunds[0]->get_id(), $first->get_error_data()['refund_id'] );
+ $this->assertStringNotContainsString( 'no money was returned', $first->get_error_message() );
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertSame( array( '5' ), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should refuse the retry of a gateway refund when a filter changes what the refund getters return.
+ *
+ * @testWith ["woocommerce_order_refund_get_reason", "Redacted"]
+ * ["woocommerce_order_refund_get_refunded_by", 0]
+ *
+ * @param string $hook Getter filter.
+ * @param int|string $value Value the filter returns.
+ */
+ public function test_refuses_retry_when_a_filter_changes_the_refund_getters( string $hook, $value ): void {
+ $order = $this->create_order_without_lines();
+ add_filter( $hook, static fn() => $value );
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ 'reason' => 'Damaged parcel',
+ 'refund_payment' => true,
+ );
+
+ $first = $this->refund( $input );
+ $second = $this->refund( $input );
+
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertSame( array( '5' ), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should still refuse the retry when an extension changes the refund before its first save, so it no longer matches the call.
+ */
+ public function test_refuses_retry_when_an_extension_changes_the_refund_before_its_first_save(): void {
+ $order = $this->create_order_without_lines();
+ add_filter(
+ 'woocommerce_order_get_items',
+ static function ( $items, $refund ) {
+ if ( $refund instanceof \WC_Order_Refund && 0 === $refund->get_id() ) {
+ $refund->set_reason( 'Normalized by an extension.' );
+ }
+ return $items;
+ },
+ 10,
+ 2
+ );
+ $input = array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ 'reason' => 'Damaged parcel',
+ 'refund_payment' => true,
+ );
+
+ $first = $this->refund( $input );
+ $second = $this->refund( $input );
+
+ $this->assertIsArray( $first, is_wp_error( $first ) ? $first->get_error_message() : '' );
+ $this->assertWPError( $second );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $second->get_error_code() );
+ $this->assertSame( array( '5' ), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should tell the client not to refund again when the call fails after woocommerce_create_refund ran and the refund is rolled back.
+ */
+ public function test_reports_lost_refund_when_the_call_fails_after_the_create_hook(): void {
+ $order = $this->create_order_without_lines();
+ add_action(
+ 'woocommerce_create_refund',
+ static function () {
+ throw new \Error( 'Payment provider SDK crashed.' );
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_lost', $result->get_error_code() );
+ $this->assertStringContainsString( 'Do not refund again.', $result->get_error_message() );
+ $this->assertStringContainsString( 'Payment provider SDK crashed.', $result->get_error_message() );
+ $this->assertSame( array(), $this->gateway->refunded );
+ $this->assertCount( 0, wc_get_order( $order->get_id() )->get_refunds() );
+ }
+
+ /**
+ * Run the refund ability.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ */
+ private function refund( array $input ) {
+ return wp_get_ability( 'woocommerce/order-refund-create' )->execute( $input );
+ }
+
+ /**
+ * @testdox Should tell a caller that passes a refund ID as the order ID which order the refund belongs to.
+ *
+ * @testWith ["woocommerce/order-refund-create", {"amount": "1"}]
+ * ["woocommerce/order-refunds-query", {}]
+ *
+ * @param string $ability_name Ability that gets the refund ID.
+ * @param array $input Rest of the ability input.
+ */
+ public function test_refund_id_as_order_id_names_the_order( string $ability_name, array $input ): void {
+ $order = $this->create_order();
+ $refund = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 5,
+ )
+ );
+
+ $result = wp_get_ability( $ability_name )->execute( array( 'id' => $refund->get_id() ) + $input );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_order_not_found', $result->get_error_code() );
+ $this->assertStringContainsString( 'Use order ID ' . $order->get_id() . '.', $result->get_error_message() );
+ $this->assertCount( 1, wc_get_order( $order->get_id() )->get_refunds() );
+ $this->assertInstanceOf( \WC_Order_Refund::class, wc_get_order( $refund->get_id() ) );
+ }
+
+ /**
+ * @testdox Should still refuse a refund ID to a user who cannot act on any order.
+ */
+ public function test_refund_id_as_order_id_is_refused_without_order_access(): void {
+ $order = $this->create_order();
+ $refund = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 5,
+ )
+ );
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'customer' ) ) );
+
+ $inputs = array(
+ 'woocommerce/order-refunds-query' => array(),
+ 'woocommerce/order-refund-create' => array( 'amount' => '1' ),
+ );
+
+ foreach ( $inputs as $ability_name => $input ) {
+ $result = wp_get_ability( $ability_name )->execute( array( 'id' => $refund->get_id() ) + $input );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), $ability_name );
+ }
+ }
+
+ /**
+ * @testdox Should not name the order of a refund to a user who cannot act on that order, even if they can act on others.
+ *
+ * @testWith ["woocommerce/order-refund-create", {"amount": "1"}]
+ * ["woocommerce/order-refunds-query", {}]
+ *
+ * @param string $ability_name Ability that gets the refund ID.
+ * @param array $input Rest of the ability input.
+ */
+ public function test_refund_id_as_order_id_is_refused_without_access_to_its_order( string $ability_name, array $input ): void {
+ $order = $this->create_order();
+ $refund = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 5,
+ )
+ );
+ add_filter(
+ 'woocommerce_rest_check_permissions',
+ static function ( $permission, $context, $object_id ) use ( $order ) {
+ unset( $context );
+ return $order->get_id() === (int) $object_id ? false : $permission;
+ },
+ 10,
+ 3
+ );
+
+ $result = wp_get_ability( $ability_name )->execute( array( 'id' => $refund->get_id() ) + $input );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code() );
+ }
+
+ /**
+ * Create a processing order of 4 units at 10 plus 10 shipping, a total of 50.
+ *
+ * @param string $payment_method Payment gateway ID.
+ * @return \WC_Order
+ */
+ private function create_order( string $payment_method = 'refunding_gateway' ): \WC_Order {
+ $order = WC_Helper_Order::create_order();
+ $order->set_payment_method( $payment_method );
+ $order->set_status( OrderStatus::PROCESSING );
+ $order->save();
+
+ return $order;
+ }
+
+ /**
+ * Create a processing order with a total of 50 and no lines, for refunds of an amount only.
+ *
+ * @param string $payment_method Payment gateway ID.
+ * @return \WC_Order
+ */
+ private function create_order_without_lines( string $payment_method = 'refunding_gateway' ): \WC_Order {
+ $order = wc_create_order();
+ $order->set_payment_method( $payment_method );
+ $order->set_total( '50' );
+ $order->set_status( OrderStatus::PROCESSING );
+ $order->save();
+
+ return $order;
+ }
+
+ /**
+ * Get the ID of the product line of an order from create_order().
+ *
+ * @param \WC_Order $order Order.
+ * @return int
+ */
+ private function get_product_line_id( \WC_Order $order ): int {
+ return array_key_first( $order->get_items() );
+ }
+
+ /**
+ * Describe the lines of a refund by what both refund paths must agree on. The refunded line is named by
+ * its position in the order, since the two refunds belong to different orders.
+ *
+ * @param \WC_Order_Refund $refund Refund, loaded from the database.
+ * @param \WC_Order $order Order the refund belongs to.
+ * @return array
+ */
+ private function describe_lines( \WC_Order_Refund $refund, \WC_Order $order ): array {
+ $order_line_ids = array_keys( $order->get_items( array( 'line_item', 'fee', 'shipping' ) ) );
+
+ return array_map(
+ static fn( \WC_Order_Item $item ): array => array(
+ $item->get_type(),
+ $item->get_name(),
+ array_search( absint( $item->get_meta( '_refunded_item_id' ) ), $order_line_ids, true ),
+ is_callable( array( $item, 'get_quantity' ) ) ? $item->get_quantity() : null,
+ is_callable( array( $item, 'get_total' ) ) ? $item->get_total() : null,
+ is_callable( array( $item, 'get_total_tax' ) ) ? $item->get_total_tax() : null,
+ ),
+ array_values( $refund->get_items() )
+ );
+ }
+
+ /**
+ * @testdox Should omit the reason when a filter turns it into null.
+ */
+ public function test_query_omits_reason_filtered_to_null(): void {
+ $order = $this->create_order_without_lines();
+ wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 5,
+ 'reason' => 'Late delivery',
+ )
+ );
+ add_filter( 'woocommerce_order_refund_get_reason', '__return_null' );
+
+ $result = wp_get_ability( 'woocommerce/order-refunds-query' )->execute( array( 'id' => $order->get_id() ) );
+
+ remove_filter( 'woocommerce_order_refund_get_reason', '__return_null' );
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertArrayNotHasKey( 'reason', $result['refunds'][0] );
+ }
+
+ /**
+ * @testdox Should report an incomplete refund when it cannot be saved as paid after the gateway refunded, and refuse a retry.
+ */
+ public function test_reports_incomplete_when_paid_refund_save_fails(): void {
+ $order = $this->create_order_without_lines();
+ add_action(
+ 'woocommerce_before_order_refund_object_save',
+ static function ( $refund ) {
+ if ( $refund->get_refunded_payment() ) {
+ throw new \Exception( 'Refund storage is read-only.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_order_refund_incomplete', $result->get_error_code() );
+ $this->assertStringContainsString( 'The payment gateway refunded the payment', $result->get_error_message() );
+ $this->assertStringContainsString( 'Refund storage is read-only.', $result->get_error_message() );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+
+ $retry = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '10',
+ 'refund_payment' => true,
+ )
+ );
+ $this->assertWPError( $retry );
+ $this->assertSame( 'woocommerce_ability_order_refund_duplicate', $retry->get_error_code() );
+ $this->assertStringContainsString( 'may have refunded the payment', $retry->get_error_message() );
+ $this->assertSame( array( '10' ), $this->gateway->refunded );
+ }
+
+ /**
+ * @testdox Should report success when the status change fails once and the final save of the order stores the status.
+ */
+ public function test_succeeds_when_final_save_stores_the_status(): void {
+ $order = $this->create_order_without_lines();
+ $thrown = false;
+ add_action(
+ 'woocommerce_before_order_object_save',
+ static function ( $saved ) use ( $order, &$thrown ) {
+ if ( ! $thrown && $saved->get_id() === $order->get_id() && OrderStatus::REFUNDED === $saved->get_status() ) {
+ $thrown = true;
+ throw new \Exception( 'Order storage is busy.' );
+ }
+ }
+ );
+
+ $result = $this->refund(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '50',
+ )
+ );
+
+ $this->assertTrue( $thrown, 'The order save during update_status() should have failed.' );
+ $this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+ $this->assertSame( OrderStatus::REFUNDED, wc_get_order( $order->get_id() )->get_status() );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index 817192d1898..3caca2837b4 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -10,6 +10,7 @@ namespace Automattic\WooCommerce\Tests\Internal\AbilitiesApi;
use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
use Automattic\WooCommerce\Abilities\ActionableAbility;
use Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore as CustomersDataStore;
+use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Enums\ProductStatus;
use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
use Automattic\WooCommerce\Internal\DataStores\Orders\DataSynchronizer;
@@ -1130,6 +1131,25 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
return array( 'product_ids' => array( $product ) );
},
),
+ 'order_refund' => array(
+ 'order_refund',
+ 'woocommerce/order-refunds-query',
+ 'refunds',
+ static function (): array {
+ $order = wc_create_order();
+ $order->set_total( '50' );
+ $order->save();
+ foreach ( array( 5, 7 ) as $amount ) {
+ wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => $amount,
+ )
+ );
+ }
+ return array( 'id' => $order->get_id() );
+ },
+ ),
);
}
@@ -1394,9 +1414,7 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
ExtensibleAbilities::register_resource( 'late_resource' );
- $resources = new \ReflectionProperty( ExtensibleAbilities::class, 'resources' );
- $resources->setAccessible( true );
- $this->assertSame( array( 'product', 'order', 'order_item', 'product_term', 'product_review', 'customer' ), array_keys( $resources->getValue() ) );
+ $this->assertFalse( ExtensibleAbilities::is_resource_registered( 'late_resource' ) );
}
/**
@@ -2818,6 +2836,109 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertSame( 'Packed.', $note->content );
}
+ /**
+ * @testdox Should name the saved refund in the error when order-refund-create refunds and a refund field value then fails its schema.
+ */
+ public function test_a_refund_that_saves_before_a_field_fails_names_the_saved_refund(): void {
+ $this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_field' );
+ $this->register_invalid_field( 'order_refund', array( 'type' => 'integer' ), 'many' );
+ $order = \WC_Helper_Order::create_order();
+ $order->set_status( OrderStatus::PROCESSING );
+ $order->save();
+
+ $result = wp_get_ability( 'woocommerce/order-refund-create' )->execute(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ )
+ );
+
+ $this->assert_field_output_invalid( $result, 'order_refund' );
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertStringContainsString( 'do not send it again', $result->get_error_message() );
+ $this->assertTrue( $result->get_error_data()['saved'] );
+ $this->assertSame( $refunds[0]->get_id(), $result->get_error_data()['id'] );
+ $this->assertFalse( $result->get_error_data()['refunded_payment'] );
+ }
+
+ /**
+ * @testdox Should name the saved refund and say the gateway refunded it when a refund field callback throws after a gateway refund.
+ */
+ public function test_a_gateway_refund_whose_field_callback_throws_names_the_saved_refund(): void {
+ $this->setExpectedIncorrectUsage( ExtensibleAbilities::class . '::register_field' );
+ $this->add_test_action(
+ 'woocommerce_extensible_abilities_init',
+ static function () {
+ ExtensibleAbilities::register_field(
+ array(
+ 'resource' => 'order_refund',
+ 'namespace' => 'invalid-ext',
+ 'field' => 'bad',
+ 'output_schema' => array( 'type' => 'string' ),
+ 'get_callback' => static function () {
+ throw new \RuntimeException( 'Secret failure' );
+ },
+ )
+ );
+ }
+ );
+ $gateway = new class() extends \WC_Payment_Gateway {
+ /**
+ * Set the ID and the refund support.
+ */
+ public function __construct() {
+ $this->id = 'field_test_gateway';
+ $this->enabled = 'yes';
+ $this->supports = array( 'products', 'refunds' );
+ }
+
+ /**
+ * Refund the payment.
+ *
+ * @param int $order_id Order ID.
+ * @param float|null $amount Amount.
+ * @param string $reason Reason.
+ * @return bool
+ */
+ public function process_refund( $order_id, $amount = null, $reason = '' ) {
+ unset( $order_id, $amount, $reason );
+ return true;
+ }
+ };
+ $gateways = WC()->payment_gateways();
+ $original_gateways = $gateways->payment_gateways;
+ $gateways->payment_gateways['field_test_gateway'] = $gateway;
+ $order = \WC_Helper_Order::create_order();
+ $order->set_payment_method( 'field_test_gateway' );
+ $order->set_status( OrderStatus::PROCESSING );
+ $order->save();
+
+ try {
+ $result = wp_get_ability( 'woocommerce/order-refund-create' )->execute(
+ array(
+ 'id' => $order->get_id(),
+ 'amount' => '5',
+ 'refund_payment' => true,
+ )
+ );
+ } finally {
+ $gateways->payment_gateways = $original_gateways;
+ }
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_extension_failed', $result->get_error_code(), $result->get_error_message() );
+ $this->assertStringNotContainsString( 'Secret failure', $result->get_error_message() );
+ $refunds = wc_get_order( $order->get_id() )->get_refunds();
+ $this->assertCount( 1, $refunds );
+ $this->assertTrue( $refunds[0]->get_refunded_payment() );
+ $this->assertStringContainsString( 'do not send it again', $result->get_error_message() );
+ $this->assertSame( 500, $result->get_error_data()['status'] );
+ $this->assertTrue( $result->get_error_data()['saved'] );
+ $this->assertSame( $refunds[0]->get_id(), $result->get_error_data()['id'] );
+ $this->assertTrue( $result->get_error_data()['refunded_payment'] );
+ }
+
/**
* @testdox Should name the saved order in the error when order-update-status saves and an order field value then fails its schema.
*/