Commit 14e48266c73 for woocommerce

commit 14e48266c7300c3d17a33f7c4b11a74c3a14de23
Author: iris-woocommerce[bot] <282076412+iris-woocommerce[bot]@users.noreply.github.com>
Date:   Wed Nov 25 10:06:39 2026 -0800

    Abilities: Return extension fields on shipping, fee and coupon lines of an order (#71351)

    * Return extension fields on shipping, fee, coupon and tax lines of an order

    Co-authored-by: matticbot <matticbot@users.noreply.github.com>

    * Keep tax lines of an order without extension fields

    Co-authored-by: matticbot <matticbot@users.noreply.github.com>

    * Test the prime call for shipping, fee and coupon lines and state the field contract

    An order_item field without object_types is read on product, shipping, fee and
    coupon lines. The object_types docblock now says so, and the order prime test
    covers the lines that include_lines adds.

    Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

    * Prime shipping, fee and coupon lines with the items the formatter reads

    The prime read the three item types in one get_items() call, but the
    formatter reads them with get_shipping_methods(), get_fees() and
    get_coupons(). A woocommerce_order_get_items filter that checks the
    requested types could then add an item that the formatter outputs and
    the prime callback never receives. The prime now makes the same three
    calls.

    Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

    ---------

    Co-authored-by: zaguiini <luis.felipe.zaguini@automattic.com>
    Co-authored-by: matticbot <matticbot@users.noreply.github.com>
    Co-authored-by: Luis Felipe Zaguini <luisfelipezaguini@gmail.com>
    Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

diff --git a/plugins/woocommerce/changelog/add-order-line-extension-fields b/plugins/woocommerce/changelog/add-order-line-extension-fields
new file mode 100644
index 00000000000..02ee83d701c
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-order-line-extension-fields
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Extensible abilities: return order item fields on shipping, fee and coupon lines; experimental.
+
diff --git a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
index e37d9291103..8ea110c39d1 100644
--- a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
+++ b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
@@ -157,9 +157,12 @@ class ExtensibleAbilities {
 	 *                                  WooCommerce also reads, because some clients refuse it.
 	 *     @type string[] $object_types Optional. The object types the field applies to, as `get_type()` of the
 	 *                                  object returns them, such as `simple` and `subscription` for a product or
-	 *                                  `line_item` for an order item. The object must have a `get_type()` method.
-	 *                                  The abilities leave the field out of the other objects and refuse a write
-	 *                                  to them. Omit it for every type.
+	 *                                  `line_item`, `shipping`, `fee` and `coupon` for an order item. The object
+	 *                                  must have a `get_type()` method.
+	 *                                  The abilities leave the field out of the other objects, and an ability
+	 *                                  that writes the resource refuses a write to them. Omit it for every type:
+	 *                                  an `order_item` field without it is then read on product, shipping, fee
+	 *                                  and coupon lines, so its `get_callback` must accept each of them.
 	 *     @type callable $get_callback Optional. Receives the object and returns the value. A field without it
 	 *                                  is not in the output. Required with `output_schema`. Return null when the
 	 *                                  object has no value, and the field is left out with no error. Any other
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
index fabb079c62c..156a59420af 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
@@ -231,7 +231,8 @@ trait OrderAbilityTrait {
 							),
 							'additionalProperties' => false,
 						),
-						'order_item'
+						'order_item',
+						self::order_item_field_filter( 'line_item' )
 					),
 				),
 				'shipping'             => array(
@@ -248,7 +249,8 @@ trait OrderAbilityTrait {
 						'instance_id'  => array( 'type' => 'string' ),
 						'total'        => array( 'type' => 'string' ),
 						'total_tax'    => array( 'type' => 'string' ),
-					)
+					),
+					'shipping'
 				),
 				'fee_lines'            => self::get_order_lines_schema(
 					array(
@@ -261,7 +263,8 @@ trait OrderAbilityTrait {
 						),
 						'total'      => array( 'type' => 'string' ),
 						'total_tax'  => array( 'type' => 'string' ),
-					)
+					),
+					'fee'
 				),
 				'coupon_lines'         => self::get_order_lines_schema(
 					array(
@@ -269,7 +272,8 @@ trait OrderAbilityTrait {
 						'code'         => array( 'type' => 'string' ),
 						'discount'     => array( 'type' => 'string' ),
 						'discount_tax' => array( 'type' => 'string' ),
-					)
+					),
+					'coupon'
 				),
 				'tax_lines'            => self::get_order_lines_schema(
 					array(
@@ -291,20 +295,34 @@ trait OrderAbilityTrait {
 	/**
 	 * Schema of one kind of order line other than line items. The include_lines input describes when they are present.
 	 *
-	 * @param array $properties Properties of one line.
+	 * @param array       $properties Properties of one line.
+	 * @param string|null $item_type  Order item type of the line, such as `fee`, to list the extension fields that apply to it. Null lists none.
 	 * @return array
 	 */
-	private static function get_order_lines_schema( array $properties ): array {
+	private static function get_order_lines_schema( array $properties, ?string $item_type = null ): array {
+		$schema = array(
+			'type'                 => 'object',
+			'properties'           => $properties,
+			'additionalProperties' => false,
+		);
 		return array(
 			'type'  => 'array',
-			'items' => array(
-				'type'                 => 'object',
-				'properties'           => $properties,
-				'additionalProperties' => false,
-			),
+			'items' => null === $item_type ? $schema : ExtensibleAbilities::add_fields_schema( $schema, 'order_item', self::order_item_field_filter( $item_type ) ),
 		);
 	}

+	/**
+	 * Field filter for add_fields_schema() that keeps the order item fields whose `object_types` include an item type.
+	 *
+	 * @param string $item_type Order item type, such as `line_item` or `fee`.
+	 * @return callable
+	 */
+	private static function order_item_field_filter( string $item_type ): callable {
+		return static function ( array $args ) use ( $item_type ): bool {
+			return empty( $args['object_types'] ) || in_array( $item_type, $args['object_types'], true );
+		};
+	}
+
 	/**
 	 * Get an order from ability input.
 	 *
@@ -438,9 +456,9 @@ trait OrderAbilityTrait {
 	 */
 	protected static function format_orders_for_response( array $orders, array $includes ) {
 		ExtensibleAbilities::prime( 'order', $orders );
+		$items = array();
 		if ( in_array( 'line_items', $includes, true ) ) {
 			$product_ids = array();
-			$items       = array();
 			foreach ( $orders as $order ) {
 				foreach ( $order->get_items() as $item ) {
 					if ( $item instanceof \WC_Order_Item_Product ) {
@@ -455,8 +473,13 @@ trait OrderAbilityTrait {
 				// Prime caches to reduce future queries.
 				_prime_post_caches( $product_ids );
 			}
-			ExtensibleAbilities::prime( 'order_item', $items );
 		}
+		if ( in_array( 'lines', $includes, true ) ) {
+			foreach ( $orders as $order ) {
+				array_push( $items, ...array_values( $order->get_shipping_methods() ), ...array_values( $order->get_fees() ), ...array_values( $order->get_coupons() ) );
+			}
+		}
+		ExtensibleAbilities::prime( 'order_item', $items );

 		$formatted = array();
 		foreach ( $orders as $order ) {
@@ -484,7 +507,7 @@ trait OrderAbilityTrait {
 	 *
 	 * @param \WC_Order $order    Order object.
 	 * @param string[]  $includes Optional parts: `line_items`, and `lines` for the shipping, fee, coupon and tax lines.
-	 * @return array|\WP_Error A WP_Error when an extension field value does not match its schema.
+	 * @return array|\WP_Error A WP_Error when an extension field fails or returns a value its schema does not allow.
 	 */
 	protected static function format_order_for_response( \WC_Order $order, array $includes ) {
 		$billing_email = $order->get_billing_email();
@@ -531,7 +554,11 @@ trait OrderAbilityTrait {
 		}

 		if ( in_array( 'lines', $includes, true ) ) {
-			$data += self::format_order_lines_for_response( $order );
+			$lines = self::format_order_lines_for_response( $order );
+			if ( is_wp_error( $lines ) ) {
+				return $lines;
+			}
+			$data += $lines;
 		}

 		if ( '' !== $billing_email ) {
@@ -586,72 +613,80 @@ trait OrderAbilityTrait {
 	}

 	/**
-	 * Format the shipping, fee, coupon and tax lines of an order, with the keys of wc/v3/orders.
+	 * Format the shipping, fee, coupon and tax lines of an order, with the keys of wc/v3/orders. Tax lines have no extension fields.
 	 *
 	 * @param \WC_Order $order Order object.
-	 * @return array
+	 * @return array|\WP_Error A WP_Error when an extension field fails or returns a value its schema does not allow.
 	 */
-	private static function format_order_lines_for_response( \WC_Order $order ): array {
-		return array(
-			'shipping_lines' => array_values(
-				array_map(
-					static function ( \WC_Order_Item_Shipping $item ): array {
-						return array(
-							'id'           => $item->get_id(),
-							'method_title' => $item->get_method_title(),
-							'method_id'    => $item->get_method_id(),
-							'instance_id'  => (string) $item->get_instance_id(),
-							'total'        => self::format_amount_for_response( $item->get_total() ),
-							'total_tax'    => self::format_amount_for_response( $item->get_total_tax() ),
-						);
-					},
-					$order->get_shipping_methods()
-				)
+	private static function format_order_lines_for_response( \WC_Order $order ) {
+		$lines = array(
+			'shipping_lines' => array(
+				$order->get_shipping_methods(),
+				static function ( \WC_Order_Item_Shipping $item ): array {
+					return array(
+						'id'           => $item->get_id(),
+						'method_title' => $item->get_method_title(),
+						'method_id'    => $item->get_method_id(),
+						'instance_id'  => (string) $item->get_instance_id(),
+						'total'        => self::format_amount_for_response( $item->get_total() ),
+						'total_tax'    => self::format_amount_for_response( $item->get_total_tax() ),
+					);
+				},
 			),
-			'fee_lines'      => array_values(
-				array_map(
-					static function ( \WC_Order_Item_Fee $item ): array {
-						return array(
-							'id'         => $item->get_id(),
-							'name'       => $item->get_name(),
-							'tax_class'  => $item->get_tax_class(),
-							'tax_status' => $item->get_tax_status(),
-							'total'      => self::format_amount_for_response( $item->get_total() ),
-							'total_tax'  => self::format_amount_for_response( $item->get_total_tax() ),
-						);
-					},
-					$order->get_fees()
-				)
+			'fee_lines'      => array(
+				$order->get_fees(),
+				static function ( \WC_Order_Item_Fee $item ): array {
+					return array(
+						'id'         => $item->get_id(),
+						'name'       => $item->get_name(),
+						'tax_class'  => $item->get_tax_class(),
+						'tax_status' => $item->get_tax_status(),
+						'total'      => self::format_amount_for_response( $item->get_total() ),
+						'total_tax'  => self::format_amount_for_response( $item->get_total_tax() ),
+					);
+				},
 			),
-			'coupon_lines'   => array_values(
-				array_map(
-					static function ( \WC_Order_Item_Coupon $item ): array {
-						return array(
-							'id'           => $item->get_id(),
-							'code'         => $item->get_code(),
-							'discount'     => self::format_amount_for_response( $item->get_discount() ),
-							'discount_tax' => self::format_amount_for_response( $item->get_discount_tax() ),
-						);
-					},
-					$order->get_coupons()
-				)
-			),
-			'tax_lines'      => array_values(
-				array_map(
-					static function ( \WC_Order_Item_Tax $item ): array {
-						return array(
-							'id'                 => $item->get_id(),
-							'rate_code'          => $item->get_rate_code(),
-							'rate_id'            => $item->get_rate_id(),
-							'label'              => $item->get_label(),
-							'compound'           => $item->is_compound(),
-							'tax_total'          => self::format_amount_for_response( $item->get_tax_total() ),
-							'shipping_tax_total' => self::format_amount_for_response( $item->get_shipping_tax_total() ),
-						);
-					},
-					$order->get_taxes()
-				)
+			'coupon_lines'   => array(
+				$order->get_coupons(),
+				static function ( \WC_Order_Item_Coupon $item ): array {
+					return array(
+						'id'           => $item->get_id(),
+						'code'         => $item->get_code(),
+						'discount'     => self::format_amount_for_response( $item->get_discount() ),
+						'discount_tax' => self::format_amount_for_response( $item->get_discount_tax() ),
+					);
+				},
 			),
 		);
+
+		$data = array();
+		foreach ( $lines as $key => list( $items, $format ) ) {
+			$data[ $key ] = array();
+			foreach ( $items as $item ) {
+				$line = ExtensibleAbilities::add_fields_to_object( $format( $item ), 'order_item', $item );
+				if ( is_wp_error( $line ) ) {
+					return $line;
+				}
+				$data[ $key ][] = $line;
+			}
+		}
+
+		$data['tax_lines'] = array_values(
+			array_map(
+				static function ( \WC_Order_Item_Tax $item ): array {
+					return array(
+						'id'                 => $item->get_id(),
+						'rate_code'          => $item->get_rate_code(),
+						'rate_id'            => $item->get_rate_id(),
+						'label'              => $item->get_label(),
+						'compound'           => $item->is_compound(),
+						'tax_total'          => self::format_amount_for_response( $item->get_tax_total() ),
+						'shipping_tax_total' => self::format_amount_for_response( $item->get_shipping_tax_total() ),
+					);
+				},
+				$order->get_taxes()
+			)
+		);
+		return $data;
 	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index 6335d0208f5..8d9478a149f 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -1018,6 +1018,73 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 		$this->assertSame( array( 'test-ext' => array( 'note' => 'order-' . $order->get_id() ) ), $noted['order']['extensions'] );
 	}

+	/**
+	 * @testdox Should return order item fields on shipping, fee and coupon lines, and list a field with object_types only on its kind of line.
+	 */
+	public function test_order_item_fields_are_returned_on_every_kind_of_line(): void {
+		$this->add_test_action(
+			'woocommerce_extensible_abilities_init',
+			static function () {
+				ExtensibleAbilities::register_field(
+					array(
+						'resource'      => 'order_item',
+						'namespace'     => 'test-ext',
+						'field'         => 'fee_reason',
+						'output_schema' => array( 'type' => 'string' ),
+						'object_types'  => array( 'fee' ),
+						'get_callback'  => static fn() => 'packaging',
+					)
+				);
+			}
+		);
+		$order    = \WC_Helper_Order::create_order();
+		$fee      = new \WC_Order_Item_Fee();
+		$shipping = new \WC_Order_Item_Shipping();
+		$coupon   = new \WC_Order_Item_Coupon();
+		$fee->set_props(
+			array(
+				'name'  => 'Packaging',
+				'total' => '2',
+			)
+		);
+		$shipping->set_method_title( 'Courier' );
+		$coupon->set_code( 'save5' );
+		foreach ( array( $fee, $shipping, $coupon ) as $item ) {
+			$order->add_item( $item );
+		}
+		$order->save();
+
+		$listed = $this->run_ability(
+			'woocommerce/orders-query',
+			array(
+				'id'                 => $order->get_id(),
+				'include_line_items' => true,
+				'include_lines'      => true,
+			)
+		)['orders'][0];
+		$schema = $this->get_output_schema( 'woocommerce/orders-query' )['properties']['orders']['items']['properties'];
+
+		$this->assertSame(
+			array(
+				'test-ext' => array(
+					'gift'       => 'item-' . $fee->get_id(),
+					'fee_reason' => 'packaging',
+				),
+			),
+			$listed['fee_lines'][0]['extensions']
+		);
+		$shipping_line = current( wp_list_filter( $listed['shipping_lines'], array( 'id' => $shipping->get_id() ) ) );
+		$this->assertSame( array( 'test-ext' => array( 'gift' => 'item-' . $shipping->get_id() ) ), $shipping_line['extensions'] );
+		$this->assertSame( array( 'test-ext' => array( 'gift' => 'item-' . $coupon->get_id() ) ), $listed['coupon_lines'][0]['extensions'] );
+		$this->assertArrayNotHasKey( 'fee_reason', $listed['line_items'][0]['extensions']['test-ext'] );
+		$this->assertArrayHasKey( 'fee_reason', $schema['fee_lines']['items']['properties']['extensions']['properties']['test-ext']['properties'] );
+		foreach ( array( 'line_items', 'shipping_lines', 'coupon_lines' ) as $key ) {
+			$this->assertArrayNotHasKey( 'fee_reason', $schema[ $key ]['items']['properties']['extensions']['properties']['test-ext']['properties'], $key );
+			$this->assertArrayHasKey( 'gift', $schema[ $key ]['items']['properties']['extensions']['properties']['test-ext']['properties'], $key );
+		}
+		$this->assertArrayNotHasKey( 'extensions', $schema['tax_lines']['items']['properties'], 'Tax lines have no extension fields.' );
+	}
+
 	/**
 	 * @testdox Should call the $resource_name prime callbacks of each extension once with the full list, in registration order.
 	 * @dataProvider provide_list_abilities
@@ -1183,15 +1250,32 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 	}

 	/**
-	 * @testdox Should call the order and order item prime callbacks once with every order and every product line.
+	 * @testdox Should call the order and order item prime callbacks once with every order and every product, shipping, fee and coupon line, including a fee a filter adds.
 	 */
 	public function test_prime_callbacks_get_orders_and_line_items(): void {
 		$product = \WC_Helper_Product::create_simple_product();
 		$orders  = array( wc_create_order(), wc_create_order() );
 		foreach ( $orders as $order ) {
 			$order->add_product( $product );
+			$order->add_item( new \WC_Order_Item_Fee() );
+			$order->add_item( new \WC_Order_Item_Shipping() );
+			$order->add_item( new \WC_Order_Item_Coupon() );
+			$order->add_item( new \WC_Order_Item_Tax() );
 			$order->save();
 		}
+		$added_fee = new \WC_Order_Item_Fee();
+		$added_fee->save();
+		$this->add_test_filter(
+			'woocommerce_order_get_items',
+			static function ( $items, $order, $types ) use ( $added_fee, $orders ) {
+				if ( array( 'fee' ) === $types && $order->get_id() === $orders[0]->get_id() ) {
+					$items[ $added_fee->get_id() ] = $added_fee;
+				}
+				return $items;
+			},
+			10,
+			3
+		);
 		$calls = array();
 		foreach ( array( 'order', 'order_item' ) as $resource_name ) {
 			$this->register_prime(
@@ -1208,11 +1292,13 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 			array(
 				'per_page'           => 2,
 				'include_line_items' => true,
+				'include_lines'      => true,
 			)
 		);

-		$item_ids = array_merge( ...array_map( static fn( \WC_Order $order ) => array_keys( $order->get_items() ), $orders ) );
-		$this->assertCount( 2, $item_ids );
+		$item_ids   = array_merge( ...array_map( static fn( \WC_Order $order ) => array_keys( $order->get_items( array( 'line_item', 'shipping', 'fee', 'coupon' ) ) ), $orders ) );
+		$item_ids[] = $added_fee->get_id();
+		$this->assertCount( 9, $item_ids );
 		$this->assertCount( 1, $calls['order'] );
 		$this->assertEqualsCanonicalizing( array_map( static fn( \WC_Order $order ) => $order->get_id(), $orders ), $calls['order'][0] );
 		$this->assertCount( 1, $calls['order_item'] );