401 invalid_signature * replay -> 200 {status: duplicate} * safe mode check -> 409 site_identity_mismatch * payload validation -> 400 invalid_payload * order not found -> 202 {status: not_found} * refund / status -> 200 {status: applied, woo_status} * * The event id is remembered only after the apply, so a 202 can succeed on a retry. * * @package Aha_Is_Woocommerce */ defined( 'ABSPATH' ) || exit; /** * Handles order refund and cancel requests. */ final class Aha_Is_Woocommerce_Order_Refund_Cancel_Controller { const SCHEMA_FILE = 'order-refund-cancel.request.schema.json'; /** Seconds after which a lock row is treated as stale. */ const LOCK_TTL = 60; /** Order meta: credit memo ids already turned into a Woo refund. */ const META_CREDIT_MEMOS = '_aha_is_woocommerce_credit_memo_ids'; /** Order item meta: qty put back in stock by a zero-amount memo (Woo does not count it as refunded). */ const META_RESTOCKED_QTY = '_aha_is_woocommerce_restocked_qty'; /** Seconds to wait for a busy lock before answering 409 (Aha never retries). */ const LOCK_WAIT = 3; /** Test hook: callable( microseconds ) replacing usleep. */ public static $pause = null; /** * Handle the request. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function handle( $request ) { $verdict = Aha_Is_Woocommerce_Rest_Auth::verify_request( $request ); if ( ! $verdict['ok'] ) { return Aha_Is_Woocommerce_Rest_Response::invalid_signature(); } if ( Aha_Is_Woocommerce_Rest_Auth::is_replay( $verdict['event_id'] ) ) { return new WP_REST_Response( array( 'status' => 'duplicate' ), 200 ); } if ( Aha_Is_Woocommerce_Site_Identity::is_safe_mode() ) { $reason = Aha_Is_Woocommerce_Site_Identity::safe_mode_reason(); Aha_Is_Woocommerce_Logger::warning( 'order_refund_cancel_rejected_safe_mode', array( 'reason' => $reason ) ); return Aha_Is_Woocommerce_Rest_Response::site_identity_mismatch( $reason ); } $raw_body = (string) $request->get_body(); $as_object = json_decode( $raw_body ); $schema = Aha_Is_Woocommerce_Contract::schema( self::SCHEMA_FILE ); if ( ! $schema ) { return Aha_Is_Woocommerce_Rest_Response::error( 'invalid_payload', 'The plugin could not load its contract schema.', 400 ); } if ( ! $schema->is_valid( $as_object ) ) { $error = ( null === $as_object && JSON_ERROR_NONE !== json_last_error() ) ? 'The body is not valid JSON.' : $schema->get_first_error(); return Aha_Is_Woocommerce_Rest_Response::error( 'invalid_payload', $error, 400 ); } $data = json_decode( $raw_body, true ); // The validator has no if/then: a refund must name its credit memo (the idempotency key). if ( 'refund' === $data['action'] && ( ! is_string( $data['credit_memo_id'] ) || '' === trim( $data['credit_memo_id'] ) ) ) { return Aha_Is_Woocommerce_Rest_Response::error( 'invalid_payload', 'credit_memo_id is required for a refund.', 400 ); } $order = $this->find_order( (string) $data['aha_order_id'] ); if ( ! $order ) { Aha_Is_Woocommerce_Logger::info( 'order_refund_cancel_order_not_found', array( 'aha_order_id' => $data['aha_order_id'], 'action' => $data['action'] ) ); return new WP_REST_Response( array( 'status' => 'not_found' ), 202 ); } // One apply at a time per order: the refund delta is read and written under this lock. $lock = 'aha_is_woocommerce_refund_lock_' . $order->get_id(); $token = time() . ':' . wp_generate_uuid4(); if ( ! $this->wait_for_lock( $lock, $token ) ) { return Aha_Is_Woocommerce_Rest_Response::error( 'order_busy', 'Another refund or cancel is being applied to this order.', 409 ); } Aha_Is_Woocommerce_Echo_Guard::suppress(); try { // Re-check under the lock: a concurrent twin may have finished since the first check. if ( Aha_Is_Woocommerce_Rest_Auth::is_replay( $verdict['event_id'] ) ) { return new WP_REST_Response( array( 'status' => 'duplicate' ), 200 ); } $fresh = wc_get_order( $order->get_id() ); $order = $this->apply( $fresh ? $fresh : $order, $data ); } catch ( Throwable $e ) { // Not remembered: a retry can still apply it. Aha_Is_Woocommerce_Logger::error( 'order_refund_cancel_failed', array( 'aha_order_id' => $data['aha_order_id'], 'action' => $data['action'], 'error' => get_class( $e ) . ': ' . $e->getMessage(), ) ); return Aha_Is_Woocommerce_Rest_Response::error( 'refund_failed', 'The plugin could not apply the refund or cancel.', 500 ); } finally { Aha_Is_Woocommerce_Echo_Guard::release(); // Only our own lock: a stale takeover may have handed it to another request. $this->release_lock( $lock, $token ); } Aha_Is_Woocommerce_Rest_Auth::remember_event( $verdict['event_id'] ); Aha_Is_Woocommerce_Logger::info( 'order_refund_cancel_applied', array( 'aha_order_id' => $data['aha_order_id'], 'action' => $data['action'], 'woo_status' => $order->get_status(), ) ); return new WP_REST_Response( array( 'status' => 'applied', 'woo_status' => $order->get_status() ), 200 ); } /** * Retry the lock every 250 ms for up to LOCK_WAIT seconds. * * @param string $name Option name. * @param string $token Our unique lock value. * @return bool */ private function wait_for_lock( $name, $token ) { $deadline = microtime( true ) + self::LOCK_WAIT; while ( ! $this->take_lock( $name, $token ) ) { if ( microtime( true ) >= $deadline ) { return false; } is_callable( self::$pause ) ? call_user_func( self::$pause, 250000 ) : usleep( 250000 ); } return true; } /** * Atomic lock row ("time:uuid"); a row older than LOCK_TTL is a crashed request. * The takeover is a compare-and-swap on the old value, so only one request wins it. * * @param string $name Option name. * @param string $token Our unique lock value. * @return bool */ private function take_lock( $name, $token ) { global $wpdb; // Raw SQL on purpose: add_option/get_option cache a failed insert and hide a released lock. // phpcs:disable WordPress.DB.DirectDatabaseQuery $won = 1 === (int) $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $name, $token ) ); if ( ! $won ) { $current = (string) $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $name ) ); $won = '' !== $current && time() - (int) $current >= self::LOCK_TTL && 1 === (int) $wpdb->update( $wpdb->options, array( 'option_value' => $token ), array( 'option_name' => $name, 'option_value' => $current ) ); } // phpcs:enable WordPress.DB.DirectDatabaseQuery wp_cache_delete( $name, 'options' ); return $won; } /** * Delete the lock row only while it still holds our token. * * @param string $name Option name. * @param string $token Our unique lock value. */ private function release_lock( $name, $token ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", $name, $token ) ); wp_cache_delete( $name, 'options' ); } /** * Refund, note and status change. Runs inside the echo guard. * * @param WC_Order $order Order. * @param array $data Validated body. * @return WC_Order The order after the apply (Woo may reload it). */ private function apply( $order, array $data ) { $memo_id = isset( $data['credit_memo_id'] ) ? (string) $data['credit_memo_id'] : ''; if ( 'refund' === $data['action'] ) { $decimals = wc_get_price_decimals(); $amount = round( (float) $data['refunded_total'] - (float) $order->get_total_refunded(), $decimals ); $known = array_values( array_filter( (array) $order->get_meta( self::META_CREDIT_MEMOS ), 'strlen' ) ); if ( '' === $memo_id || ! in_array( $memo_id, $known, true ) ) { $clamped = false; if ( $amount > 0 ) { $remaining = round( (float) $order->get_remaining_refund_amount(), $decimals ); $clamped = $amount > $remaining; $amount = $clamped ? $remaining : $amount; } $lines = $this->restock_lines( $order, $data['restock_items'] ); $applied = false; if ( $amount > 0 ) { $refund = wc_create_refund( array( 'order_id' => $order->get_id(), 'amount' => $amount, /* translators: %s: Aha credit memo id. */ 'reason' => sprintf( __( 'Aha credit memo %s', 'aha-is-for-woocommerce' ), $memo_id ), 'refund_payment' => false, 'restock_items' => ! empty( $lines ), 'line_items' => $lines, ) ); if ( is_wp_error( $refund ) ) { throw new RuntimeException( 'refund_failed' ); } /* translators: 1: refund amount, 2: Aha credit memo id. */ $order->add_order_note( sprintf( __( 'Aha refund %1$s (credit memo %2$s)', 'aha-is-for-woocommerce' ), $amount, $memo_id ), 0, false ); if ( $clamped ) { $order->add_order_note( __( 'Aha refund was larger than the remaining refundable amount and was reduced.', 'aha-is-for-woocommerce' ), 0, false ); } $applied = true; } elseif ( ! empty( $lines ) ) { // No money moves (store credit or items-only memo): no Woo refund record, so track the qty // on the item and save it with the memo id BEFORE the stock change (a retry never double restocks). $items = $order->get_items(); $restock = array(); foreach ( $lines as $item_id => $line ) { if ( ! isset( $items[ $item_id ] ) ) { continue; } $qty = (float) $line['qty']; // Like wc_restock_refunded_items: never put back more than Woo reduced (a cancel may have done it). // Absent or empty meta means Woo reduced nothing, so nothing goes back. $reduced = max( 0, (float) $items[ $item_id ]->get_meta( '_reduced_stock' ) ); $qty = min( $qty, $reduced ); if ( $qty > 0 ) { $items[ $item_id ]->update_meta_data( '_reduced_stock', $reduced - $qty ); } if ( $qty > 0 ) { $restock[ $item_id ] = $qty; $items[ $item_id ]->update_meta_data( self::META_RESTOCKED_QTY, (float) $items[ $item_id ]->get_meta( self::META_RESTOCKED_QTY ) + $qty ); } } if ( '' !== $memo_id ) { $known[] = $memo_id; $order->update_meta_data( self::META_CREDIT_MEMOS, array_values( array_unique( $known ) ) ); } // Deliberate: a failure after this save loses the remaining restock rather than repeating it. $order->save(); foreach ( $restock as $item_id => $qty ) { $product = $items[ $item_id ]->get_product(); if ( $product ) { wc_update_product_stock( $product, $qty, 'increase' ); } } /* translators: %s: Aha credit memo id. */ $order->add_order_note( sprintf( __( 'Aha credit memo %s restocked items (no refund amount)', 'aha-is-for-woocommerce' ), $memo_id ), 0, false ); $applied = true; } if ( $applied ) { if ( '' !== $memo_id ) { $known[] = $memo_id; $order->update_meta_data( self::META_CREDIT_MEMOS, array_values( array_unique( $known ) ) ); $order->save(); } // Woo may have moved the order to refunded on another instance. $fresh = wc_get_order( $order->get_id() ); $order = $fresh ? $fresh : $order; } } } else { $order->add_order_note( __( 'Aha order canceled', 'aha-is-for-woocommerce' ), 0, false ); } $target = isset( $data['status'] ) ? $data['status'] : null; $current = $order->get_status(); if ( $target && $current !== $target ) { $final = in_array( $current, Aha_Is_Woocommerce_Order_Status_Controller::FINAL_STATUSES, true ); // A delivered order can still be fully refunded. if ( ! $final || ( 'refunded' === $target && 'completed' === $current ) ) { if ( 'refunded' === $target ) { // Create the remainder refund here so it reads "Fully refunded by Aha." instead of Woo's own text. $remaining = round( (float) $order->get_remaining_refund_amount(), wc_get_price_decimals() ); if ( $remaining > 0 ) { $refund = wc_create_refund( array( 'order_id' => $order->get_id(), 'amount' => $remaining, 'reason' => __( 'Fully refunded by Aha.', 'aha-is-for-woocommerce' ), 'refund_payment' => false, 'restock_items' => false, 'line_items' => array(), ) ); if ( is_wp_error( $refund ) ) { throw new RuntimeException( 'refund_failed' ); } // wc_create_refund may already have moved the order to refunded. $fresh = wc_get_order( $order->get_id() ); $order = $fresh ? $fresh : $order; } } if ( $order->get_status() !== $target ) { $order->set_status( $target ); $order->save(); } } } return $order; } /** * Woo refund line_items (order item id => qty) for the restock lines. * * Matches product_id + variation_id and caps qty by what is not refunded yet. * ponytail: item refund_total stays 0, the refund amount carries the money. * * @param WC_Order $order Order. * @param array $restock Restock items from the body. * @return array */ private function restock_lines( $order, array $restock ) { $lines = array(); foreach ( $restock as $want ) { $left = (float) $want['qty']; foreach ( $order->get_items() as $item_id => $item ) { if ( $left <= 0 ) { break; } if ( (int) $item->get_product_id() !== (int) $want['product_id'] ) { continue; } if ( isset( $want['variation_id'] ) && (int) $want['variation_id'] > 0 && (int) $item->get_variation_id() !== (int) $want['variation_id'] ) { continue; } $already = isset( $lines[ $item_id ] ) ? $lines[ $item_id ]['qty'] : 0; $room = (float) $item->get_quantity() - abs( (float) $order->get_qty_refunded_for_item( $item_id ) ) - (float) $item->get_meta( self::META_RESTOCKED_QTY ) - $already; $take = min( $left, $room ); if ( $take > 0 ) { $lines[ $item_id ] = array( 'qty' => $already + $take, 'refund_total' => 0, 'refund_tax' => array() ); $left -= $take; } } } return $lines; } /** * The Woo order for an aha_order_id: the order map first, then the order meta. * * @param string $aha_is_woocommerce_order_id Aha order id. * @return WC_Order|null */ private function find_order( $aha_is_woocommerce_order_id ) { $row = Aha_Is_Woocommerce_Order_Map::get( $aha_is_woocommerce_order_id ); $order_id = ( $row && $row['wc_order_id'] ) ? (int) $row['wc_order_id'] : Aha_Is_Woocommerce_Order_Map::find_order_id_by_meta( $aha_is_woocommerce_order_id ); $order = $order_id > 0 ? wc_get_order( $order_id ) : false; return $order ? $order : null; } }