Commit 4337e57a69e for woocommerce

commit 4337e57a69e11fd246db392621037fadf924c2c7
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Mon Nov 23 17:36:15 2026 +0100

    Keep coupon discounts within the price of the items they apply to (#71234)

    (cherry picked from commit 183418dda7c048edc7432335a3e41713f2d0900f)

    Co-authored-by: Rostislav Wolny <rosta.wolny@automattic.com>

diff --git a/plugins/woocommerce/includes/class-wc-cart-totals.php b/plugins/woocommerce/includes/class-wc-cart-totals.php
index e5613588797..ed90e5a5b5d 100644
--- a/plugins/woocommerce/includes/class-wc-cart-totals.php
+++ b/plugins/woocommerce/includes/class-wc-cart-totals.php
@@ -499,12 +499,17 @@ final class WC_Cart_Totals {
 	 *
 	 * @since  3.2.0
 	 * @param  object $item_key Item to get the price of.
-	 * @return int
+	 * @return int|float
 	 */
 	protected function get_discounted_price_in_cents( $item_key ) {
-		$item  = $this->items[ $item_key ];
-		$price = isset( $this->coupon_discount_totals[ $item_key ] ) ? $item->price - $this->coupon_discount_totals[ $item_key ] : $item->price;
-		return $price;
+		$item = $this->items[ $item_key ];
+
+		if ( ! isset( $this->coupon_discount_totals[ $item_key ] ) ) {
+			return $item->price;
+		}
+
+		// A coupon can't push a line below zero, but a line with a negative price keeps that price.
+		return max( min( 0, $item->price ), $item->price - $this->coupon_discount_totals[ $item_key ] );
 	}

 	/**
diff --git a/plugins/woocommerce/includes/class-wc-discounts.php b/plugins/woocommerce/includes/class-wc-discounts.php
index b6f3a15af81..e710fd46d72 100644
--- a/plugins/woocommerce/includes/class-wc-discounts.php
+++ b/plugins/woocommerce/includes/class-wc-discounts.php
@@ -234,7 +234,7 @@ class WC_Discounts {
 	 * @return int
 	 */
 	public function get_discounted_price_in_cents( $item ) {
-		return absint( NumberUtil::round( $item->price - $this->get_discount( $item->key, true ) ) );
+		return (int) max( 0, NumberUtil::round( $item->price - $this->get_discount( $item->key, true ) ) );
 	}

 	/**
diff --git a/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php b/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php
index 2e7e71604e9..79d4601c716 100644
--- a/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php
+++ b/plugins/woocommerce/tests/php/includes/abstracts/class-wc-abstract-order-test.php
@@ -9,6 +9,7 @@ use Automattic\WooCommerce\Internal\CostOfGoodsSold\CogsAwareUnitTestSuiteTrait;
 use Automattic\WooCommerce\Testing\Tools\CodeHacking\Hacks\FunctionsMockerHack;
 use Automattic\WooCommerce\Enums\OrderStatus;
 use Automattic\WooCommerce\Enums\ProductTaxStatus;
+use Automattic\WooCommerce\Enums\TaxBasedOn;

 // phpcs:disable Squiz.Classes.ClassFileName.NoMatch, Squiz.Classes.ValidClassName.NotCamelCaps -- Backward compatibility.
 /**
@@ -521,6 +522,55 @@ class WC_Abstract_Order_Test extends WC_Unit_Test_Case {
 		$this->assertEquals( 2, $order->get_discount_tax() );
 	}

+	/**
+	 * @testdox A fixed cart coupon applied to an order records no more than the line price when removing the base tax leaves half a cent.
+	 */
+	public function test_apply_fixed_cart_coupon_records_line_price_with_half_cent_price(): void {
+		update_option( 'woocommerce_default_country', 'US:CA' );
+		update_option( 'woocommerce_tax_based_on', TaxBasedOn::SHIPPING );
+		update_option( 'woocommerce_prices_include_tax', 'yes' );
+		update_option( 'woocommerce_calc_taxes', 'yes' );
+		update_option( 'woocommerce_tax_round_at_subtotal', 'no' );
+		WC_Tax::_insert_tax_rate(
+			array(
+				'tax_rate_country' => 'US',
+				'tax_rate_state'   => '',
+				'tax_rate'         => '20.0000',
+				'tax_rate_name'    => 'VAT',
+				'tax_rate_order'   => '1',
+				'tax_rate_class'   => '',
+			)
+		);
+		$product = WC_Helper_Product::create_simple_product(
+			true,
+			array(
+				'regular_price' => 9.99,
+				'price'         => 9.99,
+			)
+		);
+		WC_Helper_Coupon::create_coupon(
+			'fixed-cart-25',
+			array(
+				'discount_type' => 'fixed_cart',
+				'coupon_amount' => '25',
+			)
+		);
+
+		$order = wc_create_order();
+		$order->set_billing_country( 'FR' );
+		$order->set_shipping_country( 'FR' );
+		$order->add_product( $product, 1 );
+		$shipping = new WC_Order_Item_Shipping();
+		$shipping->set_total( 10 );
+		$order->add_item( $shipping );
+		$order->calculate_totals();
+
+		$this->assertTrue( $order->apply_coupon( 'fixed-cart-25' ), 'The coupon should apply to the order' );
+		$coupon_items = array_values( $order->get_items( 'coupon' ) );
+		$this->assertEquals( 8.33, $coupon_items[0]->get_discount(), 'The coupon should record no more than the line price' );
+		$this->assertEquals( 10, $order->get_total(), 'Only shipping should remain to pay' );
+	}
+
 	/**
 	 * @testdox 'add_product' passes the order supplied in '$args' to 'wc_get_price_excluding_tax', and uses the obtained price as total and subtotal for the line item.
 	 */
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-cart-totals-test.php b/plugins/woocommerce/tests/php/includes/class-wc-cart-totals-test.php
index 5b39baec208..4da4b3ba8dd 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-cart-totals-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-cart-totals-test.php
@@ -1,6 +1,8 @@
 <?php
 declare( strict_types = 1 );

+use Automattic\WooCommerce\Enums\TaxBasedOn;
+
 /**
  * Class WC_Cart_Totals_Tests. Tests for WC_Cart_Total class.
  */
@@ -580,4 +582,104 @@ class WC_Cart_Totals_Tests extends WC_Unit_Test_Case {
 		$product->delete( true );
 		$coupon->delete( true );
 	}
+
+	/**
+	 * @testdox A fixed cart coupon larger than the cart stops at the line price when removing the base tax leaves half a cent.
+	 */
+	public function test_fixed_cart_coupon_stops_at_line_price_with_half_cent_price(): void {
+		update_option( 'woocommerce_default_country', 'US:CA' );
+		update_option( 'woocommerce_tax_based_on', TaxBasedOn::SHIPPING );
+		update_option( 'woocommerce_prices_include_tax', 'yes' );
+		update_option( 'woocommerce_calc_taxes', 'yes' );
+		update_option( 'woocommerce_tax_round_at_subtotal', 'no' );
+		WC_Tax::_insert_tax_rate(
+			array(
+				'tax_rate_country'  => 'US',
+				'tax_rate_state'    => '',
+				'tax_rate'          => '20.0000',
+				'tax_rate_name'     => 'VAT',
+				'tax_rate_priority' => '1',
+				'tax_rate_compound' => '0',
+				'tax_rate_shipping' => '0',
+				'tax_rate_order'    => '1',
+			)
+		);
+		add_filter( 'woocommerce_customer_taxable_address', fn() => array( 'FR', '', '75001', 'Paris' ) );
+		// The fee keeps the cart total above zero, where it is floored, so line totals show in it.
+		add_action( 'woocommerce_cart_calculate_fees', fn( $cart ) => $cart->add_fee( 'Handling', 10 ) );
+
+		$product = WC_Helper_Product::create_simple_product(
+			true,
+			array(
+				'regular_price' => 9.99,
+				'price'         => 9.99,
+			)
+		);
+		$coupon  = WC_Helper_Coupon::create_coupon(
+			'fixed-cart-25',
+			array(
+				'discount_type' => 'fixed_cart',
+				'coupon_amount' => '25',
+			)
+		);
+
+		WC()->cart->empty_cart();
+		$item_key = WC()->cart->add_to_cart( $product->get_id(), 1 );
+		WC()->cart->apply_coupon( $coupon->get_code() );
+		WC()->cart->calculate_totals();
+
+		$this->assertNotEmpty( WC_Tax::get_base_tax_rates(), 'The base country should have a tax rate' );
+		$this->assertEmpty( WC_Tax::get_rates( '', WC()->customer ), 'The customer location should have no tax rate' );
+		$this->assertEquals( '8.33', wc_format_decimal( WC()->cart->get_discount_total(), 2 ), 'The discount should stop at the line price' );
+		$this->assertEqualsWithDelta( 0.0, WC()->cart->get_cart()[ $item_key ]['line_total'], 0.001, 'The line total should not go below zero' );
+		$this->assertEquals( '10.00', wc_format_decimal( WC()->cart->get_total( 'edit' ), 2 ), 'Only the fee should remain to pay' );
+	}
+
+	/**
+	 * @testdox A $discount_type coupon of $amount discounts only the positive line and leaves the negative-priced line at its price.
+	 * @testWith ["fixed_cart", "1", "24.00"]
+	 *           ["fixed_cart", "100", "5.00"]
+	 *           ["percent", "10", "23.00"]
+	 *           ["fixed_product", "1", "24.00"]
+	 *
+	 * @param string $discount_type  Coupon discount type.
+	 * @param string $amount         Coupon amount.
+	 * @param string $expected_total Expected cart total.
+	 */
+	public function test_coupon_leaves_negative_priced_line_at_its_price( string $discount_type, string $amount, string $expected_total ): void {
+		update_option( 'woocommerce_calc_taxes', 'no' );
+		// The fee keeps the cart total above zero, where it is floored, so line totals show in it.
+		add_action( 'woocommerce_cart_calculate_fees', fn( $cart ) => $cart->add_fee( 'Handling', 10 ) );
+
+		$product          = WC_Helper_Product::create_simple_product(
+			true,
+			array(
+				'regular_price' => 20,
+				'price'         => 20,
+			)
+		);
+		$negative_product = WC_Helper_Product::create_simple_product(
+			true,
+			array(
+				'regular_price' => -5,
+				'price'         => -5,
+			)
+		);
+		$coupon           = WC_Helper_Coupon::create_coupon(
+			'negative-line-coupon',
+			array(
+				'discount_type' => $discount_type,
+				'coupon_amount' => $amount,
+			)
+		);
+
+		WC()->cart->empty_cart();
+		WC()->cart->add_to_cart( $product->get_id(), 1 );
+		$negative_item_key = WC()->cart->add_to_cart( $negative_product->get_id(), 1 );
+		WC()->cart->apply_coupon( $coupon->get_code() );
+		WC()->cart->calculate_totals();
+
+		$this->assertEqualsWithDelta( -5.0, WC()->cart->get_cart()[ $negative_item_key ]['line_total'], 0.001, 'The negative-priced line should keep its price' );
+		$this->assertEquals( $expected_total, wc_format_decimal( WC()->cart->get_total( 'edit' ), 2 ), 'The coupon should discount only the positive line' );
+	}
 }
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-discounts-tests.php b/plugins/woocommerce/tests/php/includes/class-wc-discounts-tests.php
index 1d3e479a084..5a939c7bc87 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-discounts-tests.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-discounts-tests.php
@@ -616,4 +616,32 @@ class WC_Discounts_Tests extends WC_Unit_Test_Case {
 		$this->assertWPError( $result, 'Returning false should reject even when no excluded category is in the cart.' );
 		$this->assertStringContainsString( 'is not applicable to selected products', $result->get_error_message(), 'With no matched categories the generic message is used.' );
 	}
+
+	/**
+	 * @testdox A fixed cart coupon larger than the item stops at the item price when the price ends in half a cent.
+	 */
+	public function test_fixed_cart_coupon_stops_at_half_cent_item_price(): void {
+		update_option( 'woocommerce_calc_taxes', 'no' );
+		$product = WC_Helper_Product::create_simple_product(
+			true,
+			array(
+				'regular_price' => 9.995,
+				'price'         => 9.995,
+			)
+		);
+		$coupon  = WC_Helper_Coupon::create_coupon(
+			'fixed-cart-25',
+			array(
+				'discount_type' => 'fixed_cart',
+				'coupon_amount' => '25',
+			)
+		);
+		WC()->cart->add_to_cart( $product->get_id(), 1 );
+
+		$discounts = new WC_Discounts( WC()->cart );
+		$discounts->apply_coupon( $coupon );
+
+		$this->assertEquals( 1000, $discounts->get_discounts_by_coupon( true )[ $coupon->get_code() ], 'The discount should stop at the rounded item price' );
+		$this->assertSame( 0, $discounts->get_discounted_price_in_cents( current( $discounts->get_items() ) ), 'A used-up item should have nothing left to discount' );
+	}
 }