Skip to content

Commit

Permalink
Handle item limit for custom coupon types
Browse files Browse the repository at this point in the history
Fixes #20455
  • Loading branch information
JPry committed Jun 8, 2018
1 parent a2d3313 commit 01e1ef7
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions includes/class-wc-discounts.php
Expand Up @@ -499,11 +499,28 @@ protected function apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount =
* @return int Total discounted.
*/
protected function apply_coupon_custom( $coupon, $items_to_apply ) {
$limit_usage_qty = 0;
$applied_count = 0;

if ( null !== $coupon->get_limit_usage_to_x_items() ) {
$limit_usage_qty = $coupon->get_limit_usage_to_x_items();
}

// Apply the coupon to each item.
foreach ( $items_to_apply as $item ) {
$discounted_price = $this->get_discounted_price_in_cents( $item );
// 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 = wc_remove_number_precision( ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $discounted_price : $item->price );
$discount = wc_add_number_precision( $coupon->get_discount_amount( $price_to_discount / $item->quantity, $item->object, true ) ) * $item->quantity;
$discount = min( $discounted_price, $discount );

// See how many and what price to apply to.
$apply_quantity = $limit_usage_qty && ( $limit_usage_qty - $applied_count ) < $item->quantity ? $limit_usage_qty - $applied_count : $item->quantity;
$apply_quantity = max( 0, apply_filters( 'woocommerce_coupon_get_apply_quantity', $apply_quantity, $item, $coupon, $this ) );

// Run coupon calculations.
$discount = wc_add_number_precision( $coupon->get_discount_amount( $price_to_discount / $item->quantity, $item->object, true ) ) * $apply_quantity;
$discount = wc_round_discount( min( $discounted_price, $discount ), 0 );

// Store code and discount amount per item.
$this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
Expand Down

0 comments on commit 01e1ef7

Please sign in to comment.