From ed550348675ce5ab57871b5f0137449873afc38a Mon Sep 17 00:00:00 2001 From: Christopher Allford Date: Mon, 16 Mar 2020 21:32:25 -0700 Subject: [PATCH] Added a check to prevent coupon cent remainders from decreasing the item cost below zero --- includes/class-wc-discounts.php | 5 +--- tests/unit-tests/coupon/coupon.php | 38 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/includes/class-wc-discounts.php b/includes/class-wc-discounts.php index 95e3b44994f..2a11b517510 100644 --- a/includes/class-wc-discounts.php +++ b/includes/class-wc-discounts.php @@ -549,10 +549,7 @@ class WC_Discounts { foreach ( $items_to_apply as $item ) { for ( $i = 0; $i < $item->quantity; $i ++ ) { // Find out how much price is available to discount for the item. - $discounted_price = $this->get_discounted_price_in_cents( $item ); - - // Get the price we actually want to discount, based on settings. - $price_to_discount = ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price; + $price_to_discount = $this->get_discounted_price_in_cents( $item ); // Run coupon calculations. $discount = min( $price_to_discount, 1 ); diff --git a/tests/unit-tests/coupon/coupon.php b/tests/unit-tests/coupon/coupon.php index e5a2dda5ec4..35b9b5d4ac4 100644 --- a/tests/unit-tests/coupon/coupon.php +++ b/tests/unit-tests/coupon/coupon.php @@ -223,6 +223,44 @@ class WC_Tests_Coupon extends WC_Unit_Test_Case { $this->assertEquals( 29.5, WC()->cart->total ); } + /** + * Tests that the remainder is handled correctly and does not turn the total negative. + * + * @since 4.1 + */ + public function test_percent_discount_handles_remainder_correctly() { + + // Create product. + $product = WC_Helper_Product::create_simple_product(); + $product->set_regular_price( 18 ); + $product->save(); + + // Create coupon. + $coupon = WC_Helper_Coupon::create_coupon( '20off' ); + update_post_meta( $coupon->get_id(), 'discount_type', 'percent' ); + update_post_meta( $coupon->get_id(), 'coupon_amount', '20' ); + $coupon_2 = WC_Helper_Coupon::create_coupon( '100off' ); + update_post_meta( $coupon_2->get_id(), 'discount_type', 'percent' ); + update_post_meta( $coupon_2->get_id(), 'coupon_amount', '100' ); + + // Create a flat rate method. + WC_Helper_Shipping::create_simple_flat_rate(); + + // Add product to cart. + WC()->cart->add_to_cart( $product->get_id(), 4 ); + + // Add coupon. + WC()->cart->add_discount( $coupon->get_code() ); + WC()->cart->add_discount( $coupon_2->get_code() ); + + // Set the flat_rate shipping method. + WC()->session->set( 'chosen_shipping_methods', array( 'flat_rate' ) ); + WC()->cart->calculate_totals(); + + // Test if the cart total amount is equal 29.5. + $this->assertEquals( 10, WC()->cart->total ); + } + /** * Test date setters/getters. *