Merge pull request #16162 from woocommerce/feature/discounts-class

Cart Total and Discounts classes
This commit is contained in:
Mike Jolley 2017-08-08 15:58:32 +01:00 committed by GitHub
commit a661feccba
22 changed files with 3051 additions and 1178 deletions

View File

@ -1001,22 +1001,20 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
}
/**
* Calculate taxes for all line items and shipping, and store the totals and tax rows.
* Get tax location for this order.
*
* If by default the taxes are based on the shipping address and the current order doesn't
* have any, it would use the billing address rather than using the Shopping base location.
*
* Will use the base country unless customer addresses are set.
* @param $args array Added in 3.0.0 to pass things like location.
* @since 3.2.0
* @param $args array Override the location.
* @return array
*/
public function calculate_taxes( $args = array() ) {
protected function get_tax_location( $args = array() ) {
$tax_based_on = get_option( 'woocommerce_tax_based_on' );
if ( 'shipping' === $tax_based_on && ! $this->get_shipping_country() ) {
$tax_based_on = 'billing';
}
$args = wp_parse_args( $args, array(
$args = wp_parse_args( $args, array(
'country' => 'billing' === $tax_based_on ? $this->get_billing_country() : $this->get_shipping_country(),
'state' => 'billing' === $tax_based_on ? $this->get_billing_state() : $this->get_shipping_state(),
'postcode' => 'billing' === $tax_based_on ? $this->get_billing_postcode() : $this->get_shipping_postcode(),
@ -1032,75 +1030,38 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
$args['city'] = '';
}
// Calc taxes for line items
return $args;
}
/**
* Calculate taxes for all line items and shipping, and store the totals and tax rows.
*
* If by default the taxes are based on the shipping address and the current order doesn't
* have any, it would use the billing address rather than using the Shopping base location.
*
* Will use the base country unless customer addresses are set.
*
* @param array $args Added in 3.0.0 to pass things like location.
*/
public function calculate_taxes( $args = array() ) {
$calculate_tax_for = $this->get_tax_location( $args );
$shipping_tax_class = get_option( 'woocommerce_shipping_tax_class' );
if ( 'inherit' === $shipping_tax_class ) {
$shipping_tax_class = current( array_intersect( array_merge( array( '' ), WC_Tax::get_tax_class_slugs() ), $this->get_items_tax_classes() ) );
}
// Trigger tax recalculation for all items.
foreach ( $this->get_items( array( 'line_item', 'fee' ) ) as $item_id => $item ) {
$tax_class = $item->get_tax_class();
$tax_status = $item->get_tax_status();
if ( '0' !== $tax_class && 'taxable' === $tax_status && wc_tax_enabled() ) {
$tax_rates = WC_Tax::find_rates( array(
'country' => $args['country'],
'state' => $args['state'],
'postcode' => $args['postcode'],
'city' => $args['city'],
'tax_class' => $tax_class,
) );
$total = $item->get_total();
$taxes = WC_Tax::calc_tax( $total, $tax_rates, false );
if ( $item->is_type( 'line_item' ) ) {
$subtotal = $item->get_subtotal();
$subtotal_taxes = WC_Tax::calc_tax( $subtotal, $tax_rates, false );
$item->set_taxes( array( 'total' => $taxes, 'subtotal' => $subtotal_taxes ) );
} else {
$item->set_taxes( array( 'total' => $taxes ) );
}
} else {
$item->set_taxes( false );
}
$item->calculate_taxes( $calculate_tax_for );
$item->save();
}
// Calc taxes for shipping
foreach ( $this->get_shipping_methods() as $item_id => $item ) {
if ( wc_tax_enabled() ) {
$shipping_tax_class = get_option( 'woocommerce_shipping_tax_class' );
// Inherit tax class from items
if ( 'inherit' === $shipping_tax_class ) {
$tax_rates = array();
$tax_classes = array_merge( array( '' ), WC_Tax::get_tax_class_slugs() );
$found_tax_classes = $this->get_items_tax_classes();
foreach ( $tax_classes as $tax_class ) {
if ( in_array( $tax_class, $found_tax_classes ) ) {
$tax_rates = WC_Tax::find_shipping_rates( array(
'country' => $args['country'],
'state' => $args['state'],
'postcode' => $args['postcode'],
'city' => $args['city'],
'tax_class' => $tax_class,
) );
break;
}
}
} else {
$tax_rates = WC_Tax::find_shipping_rates( array(
'country' => $args['country'],
'state' => $args['state'],
'postcode' => $args['postcode'],
'city' => $args['city'],
'tax_class' => $shipping_tax_class,
) );
}
$item->set_taxes( array( 'total' => WC_Tax::calc_tax( $item->get_total(), $tax_rates, false ) ) );
} else {
$item->set_taxes( false );
}
$item->calculate_taxes( array_merge( $calculate_tax_for, array( 'tax_class' => $shipping_tax_class ) ) );
$item->save();
}
$this->update_taxes();
}
@ -1150,7 +1111,7 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
$this->add_item( $item );
}
// Save tax totals
// Save tax totals.
$this->set_shipping_tax( WC_Tax::round( array_sum( $shipping_taxes ) ) );
$this->set_cart_tax( WC_Tax::round( array_sum( $cart_taxes ) ) );
$this->save();
@ -1174,7 +1135,6 @@ abstract class WC_Abstract_Order extends WC_Abstract_Legacy_Order {
$this->calculate_taxes();
}
// line items
foreach ( $this->get_items() as $item ) {
$cart_subtotal += $item->get_subtotal();
$cart_total += $item->get_total();

View File

@ -0,0 +1,616 @@
<?php
/**
* Cart totals calculation class.
*
* Methods are protected and class is final to keep this as an internal API.
* May be opened in the future once structure is stable.
*
* @author Automattic
* @package WooCommerce/Classes
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WC_Cart_Totals class.
*
* @since 3.2.0
*/
final class WC_Cart_Totals {
/**
* Reference to cart object.
*
* @since 3.2.0
* @var array
*/
protected $object;
/**
* Reference to customer object.
*
* @since 3.2.0
* @var array
*/
protected $customer;
/**
* Line items to calculate.
*
* @since 3.2.0
* @var array
*/
protected $items = array();
/**
* Fees to calculate.
*
* @since 3.2.0
* @var array
*/
protected $fees = array();
/**
* Shipping costs.
*
* @since 3.2.0
* @var array
*/
protected $shipping = array();
/**
* Applied coupon objects.
*
* @since 3.2.0
* @var array
*/
protected $coupons = array();
/**
* Discount amounts in cents after calculation for the cart.
*
* @since 3.2.0
* @var array
*/
protected $discount_totals = array();
/**
* Should taxes be calculated?
*
* @var boolean
*/
protected $calculate_tax = true;
/**
* Stores totals.
*
* @since 3.2.0
* @var array
*/
protected $totals = array(
'fees_total' => 0,
'fees_total_tax' => 0,
'items_subtotal' => 0,
'items_subtotal_tax' => 0,
'items_total' => 0,
'items_total_tax' => 0,
'total' => 0,
'taxes' => array(),
'tax_total' => 0,
'shipping_total' => 0,
'shipping_tax_total' => 0,
'discounts_total' => 0,
'discounts_tax_total' => 0,
);
/**
* Sets up the items provided, and calculate totals.
*
* @since 3.2.0
* @param object $cart Cart object to calculate totals for.
*/
public function __construct( &$cart = null ) {
if ( is_a( $cart, 'WC_Cart' ) ) {
$this->object = $cart;
$this->calculate_tax = wc_tax_enabled() && ! $cart->get_customer()->get_is_vat_exempt();
$this->calculate();
}
}
/**
* Run all calculations methods on the given items in sequence.
*
* @since 3.2.0
*/
protected function calculate() {
$this->calculate_item_totals();
$this->calculate_fee_totals();
$this->calculate_shipping_totals();
$this->calculate_totals();
}
/**
* Get default blank set of props used per item.
*
* @since 3.2.0
* @return array
*/
protected function get_default_item_props() {
return (object) array(
'object' => null,
'quantity' => 0,
'product' => false,
'price_includes_tax' => false,
'subtotal' => 0,
'subtotal_tax' => 0,
'total' => 0,
'total_tax' => 0,
'taxes' => array(),
);
}
/**
* Get default blank set of props used per fee.
*
* @since 3.2.0
* @return array
*/
protected function get_default_fee_props() {
return (object) array(
'total_tax' => 0,
'taxes' => array(),
);
}
/**
* Get default blank set of props used per shipping row.
*
* @since 3.2.0
* @return array
*/
protected function get_default_shipping_props() {
return (object) array(
'total' => 0,
'total_tax' => 0,
'taxes' => array(),
);
}
/**
* Should we round at subtotal level only?
*
* @return bool
*/
protected function round_at_subtotal() {
return 'yes' === get_option( 'woocommerce_tax_round_at_subtotal' );
}
/**
* Handles a cart or order object passed in for calculation. Normalises data
* into the same format for use by this class.
*
* Each item is made up of the following props, in addition to those returned by get_default_item_props() for totals.
* - key: An identifier for the item (cart item key or line item ID).
* - cart_item: For carts, the cart item from the cart which may include custom data.
* - quantity: The qty for this line.
* - price: The line price in cents.
* - product: The product object this cart item is for.
*
* @since 3.2.0
*/
protected function set_items() {
$this->items = array();
foreach ( $this->object->get_cart() as $cart_item_key => $cart_item ) {
$item = $this->get_default_item_props();
$item->object = $cart_item;
$item->price_includes_tax = wc_prices_include_tax();
$item->quantity = $cart_item['quantity'];
$item->subtotal = wc_add_number_precision_deep( $cart_item['data']->get_price() ) * $cart_item['quantity'];
$item->product = $cart_item['data'];
$item->tax_rates = $this->get_item_tax_rates( $item );
$this->items[ $cart_item_key ] = $item;
}
}
/**
* Get fee objects from the cart. Normalises data
* into the same format for use by this class.
*
* @since 3.2.0
*/
protected function set_fees() {
$this->fees = array();
$this->object->calculate_fees();
foreach ( $this->object->get_fees() as $fee_key => $fee_object ) {
$fee = $this->get_default_fee_props();
$fee->object = $fee_object;
$fee->total = wc_add_number_precision_deep( $fee->object->amount );
if ( $this->calculate_tax && $fee->object->taxable ) {
$fee->taxes = WC_Tax::calc_tax( $fee->total, WC_Tax::get_rates( $fee->object->tax_class, $this->object->get_customer() ), false );
$fee->total_tax = array_sum( $fee->taxes );
if ( ! $this->round_at_subtotal() ) {
$fee->total_tax = wc_round_tax_total( $fee->total_tax, wc_get_rounding_precision() );
}
}
$this->fees[ $fee_key ] = $fee;
}
}
/**
* Get shipping methods from the cart and normalise.
*
* @since 3.2.0
*/
protected function set_shipping() {
$this->shipping = array();
foreach ( $this->object->calculate_shipping() as $key => $shipping_object ) {
$shipping_line = $this->get_default_shipping_props();
$shipping_line->object = $shipping_object;
$shipping_line->total = wc_add_number_precision_deep( $shipping_object->cost );
$shipping_line->taxes = wc_add_number_precision_deep( $shipping_object->taxes );
$shipping_line->total_tax = wc_add_number_precision_deep( array_sum( $shipping_object->taxes ) );
if ( ! $this->round_at_subtotal() ) {
$shipping_line->total_tax = wc_round_tax_total( $shipping_line->total_tax, wc_get_rounding_precision() );
}
$this->shipping[ $key ] = $shipping_line;
}
}
/**
* Return array of coupon objects from the cart. Normalises data
* into the same format for use by this class.
*
* @since 3.2.0
*/
protected function set_coupons() {
$this->coupons = $this->object->get_coupons();
}
/**
* Only ran if woocommerce_adjust_non_base_location_prices is true.
*
* If the customer is outside of the base location, this removes the base
* taxes. This is off by default unless the filter is used.
*
* Uses edit context so unfiltered tax class is returned.
*
* @since 3.2.0
* @param object $item Item to adjust the prices of.
* @return object
*/
protected function adjust_non_base_location_price( $item ) {
$base_tax_rates = WC_Tax::get_base_tax_rates( $item->product->get_tax_class( 'edit' ) );
if ( $item->tax_rates !== $base_tax_rates ) {
// Work out a new base price without the shop's base tax.
$taxes = WC_Tax::calc_tax( $item->subtotal, $base_tax_rates, true, true );
// Now we have a new item price (excluding TAX).
$item->subtotal = $item->subtotal - array_sum( $taxes );
$item->price_includes_tax = false;
}
return $item;
}
/**
* Get discounted price of an item with precision (in cents).
*
* @since 3.2.0
* @param object $item_key Item to get the price of.
* @return int
*/
protected function get_discounted_price_in_cents( $item_key ) {
$item = $this->items[ $item_key ];
$price = $item->subtotal - $this->discount_totals[ $item_key ];
if ( $item->price_includes_tax ) {
$price += $item->subtotal_tax;
}
return $price;
}
/**
* Get tax rates for an item. Caches rates in class to avoid multiple look ups.
*
* @param object $item Item to get tax rates for.
* @return array of taxes
*/
protected function get_item_tax_rates( $item ) {
$tax_class = $item->product->get_tax_class();
return isset( $this->item_tax_rates[ $tax_class ] ) ? $this->item_tax_rates[ $tax_class ] : $this->item_tax_rates[ $tax_class ] = WC_Tax::get_rates( $item->product->get_tax_class(), $this->object->get_customer() );
}
/**
* Get a single total with or without precision (in cents).
*
* @since 3.2.0
* @param string $key Total to get.
* @param bool $in_cents Should the totals be returned in cents, or without precision.
* @return int|float
*/
public function get_total( $key = 'total', $in_cents = false ) {
$totals = $this->get_totals( $in_cents );
return isset( $totals[ $key ] ) ? $totals[ $key ] : 0;
}
/**
* Set a single total.
*
* @since 3.2.0
* @param string $key Total name you want to set.
* @param int $total Total to set.
*/
protected function set_total( $key = 'total', $total ) {
$this->totals[ $key ] = $total;
}
/**
* Get all totals with or without precision (in cents).
*
* @since 3.2.0
* @param bool $in_cents Should the totals be returned in cents, or without precision.
* @return array.
*/
public function get_totals( $in_cents = false ) {
return $in_cents ? $this->totals : wc_remove_number_precision_deep( $this->totals );
}
/**
* Get all tax rows from items (including shipping and product line items).
*
* @since 3.2.0
* @return array
*/
protected function get_merged_taxes() {
$taxes = array();
foreach ( array_merge( $this->items, $this->fees, $this->shipping ) as $item ) {
foreach ( $item->taxes as $rate_id => $rate ) {
$taxes[ $rate_id ] = array( 'tax_total' => 0, 'shipping_tax_total' => 0 );
}
}
foreach ( $this->items + $this->fees as $item ) {
foreach ( $item->taxes as $rate_id => $rate ) {
$taxes[ $rate_id ]['tax_total'] = $taxes[ $rate_id ]['tax_total'] + $rate;
}
}
foreach ( $this->shipping as $item ) {
foreach ( $item->taxes as $rate_id => $rate ) {
$taxes[ $rate_id ]['shipping_tax_total'] = $taxes[ $rate_id ]['shipping_tax_total'] + $rate;
}
}
return $taxes;
}
/*
|--------------------------------------------------------------------------
| Calculation methods.
|--------------------------------------------------------------------------
*/
/**
* Calculate item totals.
*
* @since 3.2.0
*/
protected function calculate_item_totals() {
$this->set_items();
$this->calculate_item_subtotals();
$this->calculate_discounts();
foreach ( $this->items as $item_key => $item ) {
$item->total = $this->get_discounted_price_in_cents( $item_key );
$item->total_tax = 0;
if ( has_filter( 'woocommerce_get_discounted_price' ) ) {
/**
* Allow plugins to filter this price like in the legacy cart class.
*
* This is legacy and should probably be deprecated in the future.
* $item->object is the cart item object.
* $this->object is the cart object.
*/
$item->total = wc_add_number_precision(
apply_filters( 'woocommerce_get_discounted_price', wc_remove_number_precision( $item->total ), $item->object, $this->object )
);
}
if ( $this->calculate_tax && $item->product->is_taxable() ) {
$item->taxes = WC_Tax::calc_tax( $item->total, $item->tax_rates, $item->price_includes_tax );
$item->total_tax = array_sum( $item->taxes );
if ( ! $this->round_at_subtotal() ) {
$item->total_tax = wc_round_tax_total( $item->total_tax, wc_get_rounding_precision() );
}
if ( $item->price_includes_tax ) {
$item->total = $item->total - $item->total_tax;
} else {
$item->total = $item->total;
}
}
$this->object->cart_contents[ $item_key ]['line_total'] = wc_remove_number_precision( $item->total );
$this->object->cart_contents[ $item_key ]['line_tax'] = wc_remove_number_precision( $item->total_tax );
}
$this->set_total( 'items_total', array_sum( array_values( wp_list_pluck( $this->items, 'total' ) ) ) );
$this->set_total( 'items_total_tax', array_sum( array_values( wp_list_pluck( $this->items, 'total_tax' ) ) ) );
}
/**
* Subtotals are costs before discounts.
*
* To prevent rounding issues we need to work with the inclusive price where possible.
* otherwise we'll see errors such as when working with a 9.99 inc price, 20% VAT which would.
* be 8.325 leading to totals being 1p off.
*
* Pre tax coupons come off the price the customer thinks they are paying - tax is calculated.
* afterwards.
*
* e.g. $100 bike with $10 coupon = customer pays $90 and tax worked backwards from that.
*
* @since 3.2.0
*/
protected function calculate_item_subtotals() {
foreach ( $this->items as $item_key => $item ) {
if ( $item->price_includes_tax && apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ) {
$item = $this->adjust_non_base_location_price( $item );
}
if ( $this->calculate_tax && $item->product->is_taxable() ) {
$subtotal_taxes = WC_Tax::calc_tax( $item->subtotal, $item->tax_rates, $item->price_includes_tax );
$item->subtotal_tax = array_sum( $subtotal_taxes );
if ( ! $this->round_at_subtotal() ) {
$item->subtotal_tax = wc_round_tax_total( $item->subtotal_tax, wc_get_rounding_precision() );
}
if ( $item->price_includes_tax ) {
$item->subtotal = $item->subtotal - $item->subtotal_tax;
}
}
$this->object->cart_contents[ $item_key ]['line_subtotal'] = wc_remove_number_precision( $item->subtotal );
$this->object->cart_contents[ $item_key ]['line_subtotal_tax'] = wc_remove_number_precision( $item->subtotal_tax );
}
$this->set_total( 'items_subtotal', array_sum( array_values( wp_list_pluck( $this->items, 'subtotal' ) ) ) );
$this->set_total( 'items_subtotal_tax', array_sum( array_values( wp_list_pluck( $this->items, 'subtotal_tax' ) ) ) );
$this->object->subtotal = $this->get_total( 'items_subtotal' ) + $this->get_total( 'items_subtotal_tax' );
$this->object->subtotal_ex_tax = $this->get_total( 'items_subtotal' );
}
/**
* Calculate all discount and coupon amounts.
*
* @since 3.2.0
* @uses WC_Discounts class.
*/
protected function calculate_discounts() {
$this->set_coupons();
$discounts = new WC_Discounts( $this->object );
foreach ( $this->coupons as $coupon ) {
$discounts->apply_discount( $coupon );
}
$coupon_discount_amounts = $discounts->get_discounts_by_coupon( true );
$coupon_discount_tax_amounts = array();
// See how much tax was 'discounted' per item and per coupon.
if ( $this->calculate_tax ) {
foreach ( $discounts->get_discounts( true ) as $coupon_code => $coupon_discounts ) {
$coupon_discount_tax_amounts[ $coupon_code ] = 0;
foreach ( $coupon_discounts as $item_key => $item_discount ) {
$item = $this->items[ $item_key ];
if ( $item->product->is_taxable() ) {
$item_tax = array_sum( WC_Tax::calc_tax( $item_discount, $item->tax_rates, $item->price_includes_tax ) );
$coupon_discount_tax_amounts[ $coupon_code ] += $item_tax;
}
}
$coupon_discount_amounts[ $coupon_code ] -= $coupon_discount_tax_amounts[ $coupon_code ];
}
}
$this->discount_totals = $discounts->get_discounts_by_item( true );
$this->object->coupon_discount_amounts = wc_remove_number_precision_deep( $coupon_discount_amounts );
$this->object->coupon_discount_tax_amounts = wc_remove_number_precision_deep( $coupon_discount_tax_amounts );
$this->set_total( 'discounts_total', ! empty( $this->discount_totals ) ? array_sum( $this->discount_totals ) : 0 );
$this->set_total( 'discounts_tax_total', array_sum( $coupon_discount_tax_amounts ) );
}
/**
* Return discounted tax amount for an item.
*
* @param object $item
* @param int $discount_amount
* @return int
*/
protected function get_item_discount_tax( $item, $discount_amount ) {
if ( $item->product->is_taxable() ) {
$taxes = WC_Tax::calc_tax( $discount_amount, $item->tax_rates, false );
return array_sum( $taxes );
}
return 0;
}
/**
* Triggers the cart fees API, grabs the list of fees, and calculates taxes.
*
* Note: This class sets the totals for the 'object' as they are calculated. This is so that APIs like the fees API can see these totals if needed.
*
* @since 3.2.0
*/
protected function calculate_fee_totals() {
$this->set_fees();
$this->set_total( 'fees_total', array_sum( wp_list_pluck( $this->fees, 'total' ) ) );
$this->set_total( 'fees_total_tax', array_sum( wp_list_pluck( $this->fees, 'total_tax' ) ) );
foreach ( $this->fees as $fee_key => $fee ) {
$this->object->fees[ $fee_key ]->tax = wc_remove_number_precision_deep( $fee->total_tax );
$this->object->fees[ $fee_key ]->tax_data = wc_remove_number_precision_deep( $fee->taxes );
}
$this->object->fee_total = wc_remove_number_precision_deep( array_sum( wp_list_pluck( $this->fees, 'total' ) ) );
}
/**
* Calculate any shipping taxes.
*
* @since 3.2.0
*/
protected function calculate_shipping_totals() {
$this->set_shipping();
$this->set_total( 'shipping_total', array_sum( wp_list_pluck( $this->shipping, 'total' ) ) );
$this->set_total( 'shipping_tax_total', array_sum( wp_list_pluck( $this->shipping, 'total_tax' ) ) );
$this->object->shipping_total = $this->get_total( 'shipping_total' );
$this->object->shipping_tax_total = $this->get_total( 'shipping_tax_total' );
}
/**
* Main cart totals.
*
* @since 3.2.0
*/
protected function calculate_totals() {
$this->set_total( 'taxes', $this->get_merged_taxes() );
$this->set_total( 'tax_total', array_sum( wp_list_pluck( $this->get_total( 'taxes', true ), 'tax_total' ) ) );
$this->set_total( 'total', round( $this->get_total( 'items_total', true ) + $this->get_total( 'fees_total', true ) + $this->get_total( 'shipping_total', true ) + $this->get_total( 'tax_total', true ) + $this->get_total( 'shipping_tax_total', true ) ) );
// Add totals to cart object.
$this->object->taxes = wp_list_pluck( $this->get_total( 'taxes' ), 'shipping_tax_total' );
$this->object->shipping_taxes = wp_list_pluck( $this->get_total( 'taxes' ), 'tax_total' );
$this->object->cart_contents_total = $this->get_total( 'items_total' );
$this->object->tax_total = $this->get_total( 'tax_total' );
$this->object->total = $this->get_total( 'total' );
$this->object->discount_cart = $this->get_total( 'discounts_total' ) - $this->get_total( 'discounts_tax_total' );
$this->object->discount_cart_tax = $this->get_total( 'discounts_tax_total' );
// Allow plugins to hook and alter totals before final total is calculated.
if ( has_action( 'woocommerce_calculate_totals' ) ) {
do_action( 'woocommerce_calculate_totals', $this->object );
}
// Allow plugins to filter the grand total, and sum the cart totals in case of modifications.
$totals_to_sum = wc_add_number_precision_deep( array( $this->object->cart_contents_total, $this->object->tax_total, $this->object->shipping_tax_total, $this->object->shipping_total, $this->object->fee_total ) );
$this->object->total = max( 0, apply_filters( 'woocommerce_calculated_total', wc_remove_number_precision( round( array_sum( $totals_to_sum ) ) ), $this->object ) );
}
}

File diff suppressed because it is too large Load Diff

View File

@ -390,29 +390,7 @@ class WC_Coupon extends WC_Legacy_Coupon {
$discount = $single ? $discount : $discount * $cart_item_qty;
}
$discount = (float) min( $discount, $discounting_amount );
// Handle the limit_usage_to_x_items option
if ( ! $this->is_type( array( 'fixed_cart' ) ) ) {
if ( $discounting_amount ) {
if ( null === $this->get_limit_usage_to_x_items() ) {
$limit_usage_qty = $cart_item_qty;
} else {
$limit_usage_qty = min( $this->get_limit_usage_to_x_items(), $cart_item_qty );
$this->set_limit_usage_to_x_items( max( 0, ( $this->get_limit_usage_to_x_items() - $limit_usage_qty ) ) );
}
if ( $single ) {
$discount = ( $discount * $limit_usage_qty ) / $cart_item_qty;
} else {
$discount = ( $discount / $cart_item_qty ) * $limit_usage_qty;
}
}
}
$discount = round( $discount, wc_get_rounding_precision() );
return apply_filters( 'woocommerce_coupon_get_discount_amount', $discount, $discounting_amount, $cart_item, $single, $this );
return apply_filters( 'woocommerce_coupon_get_discount_amount', round( min( $discount, $discounting_amount ), wc_get_rounding_precision() ), $discounting_amount, $cart_item, $single, $this );
}
/*
@ -761,260 +739,22 @@ class WC_Coupon extends WC_Legacy_Coupon {
}
/**
* Ensure coupon exists or throw exception.
* Check if a coupon is valid for the cart.
*
* @deprecated 3.2.0 In favor of WC_Discounts->is_coupon_valid.
* @throws Exception
*/
private function validate_exists() {
if ( ! $this->get_id() ) {
throw new Exception( self::E_WC_COUPON_NOT_EXIST );
}
}
/**
* Ensure coupon usage limit is valid or throw exception.
*
* @throws Exception
*/
private function validate_usage_limit() {
if ( $this->get_usage_limit() > 0 && $this->get_usage_count() >= $this->get_usage_limit() ) {
throw new Exception( self::E_WC_COUPON_USAGE_LIMIT_REACHED );
}
}
/**
* Ensure coupon user usage limit is valid or throw exception.
*
* Per user usage limit - check here if user is logged in (against user IDs).
* Checked again for emails later on in WC_Cart::check_customer_coupons().
*
* @param int $user_id
* @throws Exception
*/
private function validate_user_usage_limit( $user_id = 0 ) {
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
if ( $this->get_usage_limit_per_user() > 0 && is_user_logged_in() && $this->get_id() && $this->data_store ) {
$usage_count = $this->data_store->get_usage_by_user_id( $this, $user_id );
if ( $usage_count >= $this->get_usage_limit_per_user() ) {
throw new Exception( self::E_WC_COUPON_USAGE_LIMIT_REACHED );
}
}
}
/**
* Ensure coupon date is valid or throw exception.
*
* @throws Exception
*/
private function validate_expiry_date() {
if ( $this->get_date_expires() && current_time( 'timestamp', true ) > $this->get_date_expires()->getTimestamp() ) {
throw new Exception( $error_code = self::E_WC_COUPON_EXPIRED );
}
}
/**
* Ensure coupon amount is valid or throw exception.
*
* @throws Exception
*/
private function validate_minimum_amount() {
if ( $this->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $this->get_minimum_amount() > WC()->cart->get_displayed_subtotal(), $this ) ) {
throw new Exception( self::E_WC_COUPON_MIN_SPEND_LIMIT_NOT_MET );
}
}
/**
* Ensure coupon amount is valid or throw exception.
*
* @throws Exception
*/
private function validate_maximum_amount() {
if ( $this->get_maximum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_maximum_amount', $this->get_maximum_amount() < WC()->cart->get_displayed_subtotal(), $this ) ) {
throw new Exception( self::E_WC_COUPON_MAX_SPEND_LIMIT_MET );
}
}
/**
* Ensure coupon is valid for products in the cart is valid or throw exception.
*
* @throws Exception
*/
private function validate_product_ids() {
if ( sizeof( $this->get_product_ids() ) > 0 ) {
$valid_for_cart = false;
if ( ! WC()->cart->is_empty() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( in_array( $cart_item['product_id'], $this->get_product_ids() ) || in_array( $cart_item['variation_id'], $this->get_product_ids() ) || in_array( $cart_item['data']->get_parent_id(), $this->get_product_ids() ) ) {
$valid_for_cart = true;
}
}
}
if ( ! $valid_for_cart ) {
throw new Exception( self::E_WC_COUPON_NOT_APPLICABLE );
}
}
}
/**
* Ensure coupon is valid for product categories in the cart is valid or throw exception.
*
* @throws Exception
*/
private function validate_product_categories() {
if ( sizeof( $this->get_product_categories() ) > 0 ) {
$valid_for_cart = false;
if ( ! WC()->cart->is_empty() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $this->get_exclude_sale_items() && $cart_item['data'] && $cart_item['data']->is_on_sale() ) {
continue;
}
$product_cats = wc_get_product_cat_ids( $cart_item['product_id'] );
// If we find an item with a cat in our allowed cat list, the coupon is valid
if ( sizeof( array_intersect( $product_cats, $this->get_product_categories() ) ) > 0 ) {
$valid_for_cart = true;
}
}
}
if ( ! $valid_for_cart ) {
throw new Exception( self::E_WC_COUPON_NOT_APPLICABLE );
}
}
}
/**
* Ensure coupon is valid for sale items in the cart is valid or throw exception.
*
* @throws Exception
*/
private function validate_sale_items() {
if ( $this->get_exclude_sale_items() ) {
$valid_for_cart = false;
if ( ! WC()->cart->is_empty() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( ! $product->is_on_sale() ) {
$valid_for_cart = true;
}
}
}
if ( ! $valid_for_cart ) {
throw new Exception( self::E_WC_COUPON_NOT_VALID_SALE_ITEMS );
}
}
}
/**
* All exclusion rules must pass at the same time for a product coupon to be valid.
*/
private function validate_excluded_items() {
if ( ! WC()->cart->is_empty() && $this->is_type( wc_get_product_coupon_types() ) ) {
$valid = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $this->is_valid_for_product( $cart_item['data'], $cart_item ) ) {
$valid = true;
break;
}
}
if ( ! $valid ) {
throw new Exception( self::E_WC_COUPON_NOT_APPLICABLE );
}
}
}
/**
* Cart discounts cannot be added if non-eligible product is found in cart.
*/
private function validate_cart_excluded_items() {
if ( ! $this->is_type( wc_get_product_coupon_types() ) ) {
$this->validate_cart_excluded_product_ids();
$this->validate_cart_excluded_product_categories();
}
}
/**
* Exclude products from cart.
*
* @throws Exception
*/
private function validate_cart_excluded_product_ids() {
// Exclude Products
if ( sizeof( $this->get_excluded_product_ids() ) > 0 ) {
$valid_for_cart = true;
if ( ! WC()->cart->is_empty() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( in_array( $cart_item['product_id'], $this->get_excluded_product_ids() ) || in_array( $cart_item['variation_id'], $this->get_excluded_product_ids() ) || in_array( $cart_item['data']->get_parent_id(), $this->get_excluded_product_ids() ) ) {
$valid_for_cart = false;
}
}
}
if ( ! $valid_for_cart ) {
throw new Exception( self::E_WC_COUPON_EXCLUDED_PRODUCTS );
}
}
}
/**
* Exclude categories from cart.
*
* @throws Exception
*/
private function validate_cart_excluded_product_categories() {
if ( sizeof( $this->get_excluded_product_categories() ) > 0 ) {
$valid_for_cart = true;
if ( ! WC()->cart->is_empty() ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $this->get_exclude_sale_items() && $cart_item['data'] && $cart_item['data']->is_on_sale() ) {
continue;
}
$product_cats = wc_get_product_cat_ids( $cart_item['product_id'] );
if ( sizeof( array_intersect( $product_cats, $this->get_excluded_product_categories() ) ) > 0 ) {
$valid_for_cart = false;
}
}
}
if ( ! $valid_for_cart ) {
throw new Exception( self::E_WC_COUPON_EXCLUDED_CATEGORIES );
}
}
}
/**
* Check if a coupon is valid.
*
* @return boolean validity
* @throws Exception
* @return bool Validity.
*/
public function is_valid() {
try {
$this->validate_exists();
$this->validate_usage_limit();
$this->validate_user_usage_limit();
$this->validate_expiry_date();
$this->validate_minimum_amount();
$this->validate_maximum_amount();
$this->validate_product_ids();
$this->validate_product_categories();
$this->validate_sale_items();
$this->validate_excluded_items();
$this->validate_cart_excluded_items();
$discounts = new WC_Discounts( WC()->cart );
$valid = $discounts->is_coupon_valid( $this );
if ( ! apply_filters( 'woocommerce_coupon_is_valid', true, $this ) ) {
throw new Exception( self::E_WC_COUPON_INVALID_FILTERED );
}
} catch ( Exception $e ) {
$this->error_message = $this->get_coupon_error( $e->getMessage() );
if ( is_wp_error( $valid ) ) {
$this->error_message = $valid->get_error_message();
return false;
}
return true;
return $valid;
}
/**

View File

@ -0,0 +1,82 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* A discount.
*
* Represents a fixed, percent or coupon based discount calculated by WC_Discounts class.
*
* @author Automattic
* @package WooCommerce/Classes
* @version 3.2.0
* @since 3.2.0
*/
class WC_Discount {
/**
* Data array, with defaults.
*
* @var array
*/
protected $data = array(
'amount' => 0, // Discount amount.
'discount_type' => 'fixed', // Fixed, percent, or coupon.
'discount_total' => 0,
);
/**
* Get discount amount.
*
* @return int
*/
public function get_amount() {
return $this->data['amount'];
}
/**
* Discount amount - either fixed or percentage.
*
* @param string $raw_amount Amount discount gives.
*/
public function set_amount( $raw_amount ) {
$this->data['amount'] = wc_format_decimal( $raw_amount );
}
/**
* Get discount type.
*
* @return string
*/
public function get_discount_type() {
return $this->data['discount_type'];
}
/**
* Set discount type.
*
* @param string $discount_type Type of discount.
*/
public function set_discount_type( $discount_type ) {
$this->data['discount_type'] = $discount_type;
}
/**
* Get discount total.
*
* @return int
*/
public function get_discount_total() {
return $this->data['discount_total'];
}
/**
* Discount total.
*
* @param string $total Total discount applied.
*/
public function set_discount_total( $total ) {
$this->data['discount_total'] = wc_format_decimal( $total );
}
}

View File

@ -0,0 +1,902 @@
<?php
/**
* Discount calculation
*
* @author Automattic
* @package WooCommerce/Classes
* @version 3.2.0
* @since 3.2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Discounts class.
*/
class WC_Discounts {
/**
* An array of items to discount.
*
* @var array
*/
protected $items = array();
/**
* An array of discounts which have been applied to items.
*
* @var array[] Code => Item Key => Value
*/
protected $discounts = array();
/**
* An array of applied WC_Discount objects.
*
* @var array
*/
protected $manual_discounts = array();
/**
* Constructor. @todo accept order objects.
*
* @param array $object Cart or order object.
*/
public function __construct( $object = array() ) {
if ( is_a( $object, 'WC_Cart' ) ) {
$this->set_items_from_cart( $object );
}
}
/**
* Normalise cart/order items which will be discounted.
*
* @since 3.2.0
* @param array $cart Cart object.
*/
public function set_items_from_cart( $cart ) {
$this->items = $this->discounts = $this->manual_discounts = array();
if ( ! is_a( $cart, 'WC_Cart' ) ) {
return;
}
foreach ( $cart->get_cart() as $key => $cart_item ) {
$item = new stdClass();
$item->key = $key;
$item->object = $cart_item;
$item->product = $cart_item['data'];
$item->quantity = $cart_item['quantity'];
$item->price = wc_add_number_precision_deep( $item->product->get_price() ) * $item->quantity;
$this->items[ $key ] = $item;
}
uasort( $this->items, array( $this, 'sort_by_price' ) );
}
/**
* Get items.
*
* @since 3.2.0
* @return object[]
*/
public function get_items() {
return $this->items;
}
/**
* Get discount by key with or without precision.
*
* @since 3.2.0
* @param string $key name of discount row to return.
* @param bool $in_cents Should the totals be returned in cents, or without precision.
* @return array
*/
public function get_discount( $key, $in_cents = false ) {
$item_discount_totals = $this->get_discounts_by_item( $in_cents );
return isset( $item_discount_totals[ $key ] ) ? ( $in_cents ? $item_discount_totals[ $key ] : wc_remove_number_precision( $item_discount_totals[ $key ] ) ) : 0;
}
/**
* Get all discount totals.
*
* @since 3.2.0
* @param bool $in_cents Should the totals be returned in cents, or without precision.
* @return array
*/
public function get_discounts( $in_cents = false ) {
$discounts = $this->discounts;
foreach ( $this->get_manual_discounts() as $manual_discount_key => $manual_discount ) {
$discounts[ $manual_discount_key ] = $manual_discount->get_discount_total();
}
return $in_cents ? $discounts : wc_remove_number_precision_deep( $discounts );
}
/**
* Get all discount totals per item.
*
* @since 3.2.0
* @param bool $in_cents Should the totals be returned in cents, or without precision.
* @return array
*/
public function get_discounts_by_item( $in_cents = false ) {
$discounts = $this->discounts;
$item_discount_totals = array_shift( $discounts );
foreach ( $discounts as $item_discounts ) {
foreach ( $item_discounts as $item_key => $item_discount ) {
$item_discount_totals[ $item_key ] += $item_discount;
}
}
return $in_cents ? $item_discount_totals : wc_remove_number_precision_deep( $item_discount_totals );
}
/**
* Get all discount totals per coupon.
*
* @since 3.2.0
* @param bool $in_cents Should the totals be returned in cents, or without precision.
* @return array
*/
public function get_discounts_by_coupon( $in_cents = false ) {
$coupon_discount_totals = array_map( 'array_sum', $this->discounts );
return $in_cents ? $coupon_discount_totals : wc_remove_number_precision_deep( $coupon_discount_totals );
}
/**
* Get an array of manual discounts which have been applied.
*
* @since 3.2.0
* @return WC_Discount[]
*/
public function get_manual_discounts() {
return $this->manual_discounts;
}
/**
* Get discounted price of an item without precision.
*
* @since 3.2.0
* @param object $item Get data for this item.
* @return float
*/
public function get_discounted_price( $item ) {
return wc_remove_number_precision_deep( $this->get_discounted_price_in_cents( $item ) );
}
/**
* Get discounted price of an item to precision (in cents).
*
* @since 3.2.0
* @param object $item Get data for this item.
* @return int
*/
public function get_discounted_price_in_cents( $item ) {
return absint( $item->price - $this->get_discount( $item->key, true ) );
}
/**
* Get total remaining after discounts.
*
* @since 3.2.0
* @return int
*/
protected function get_total_after_discounts() {
$total_to_discount = 0;
foreach ( $this->items as $item ) {
$total_to_discount += $this->get_discounted_price_in_cents( $item );
}
foreach ( $this->manual_discounts as $key => $value ) {
$total_to_discount = $total_to_discount - $value->get_discount_total();
}
return $total_to_discount;
}
/**
* Generate a unique ID for a discount.
*
* @param WC_Discount $discount Discount object.
* @return string
*/
protected function generate_discount_id( $discount ) {
$discount_id = '';
$index = 1;
while ( ! $discount_id ) {
$discount_id = 'discount-' . $discount->get_amount() . ( 'percent' === $discount->get_discount_type() ? '%' : '' );
if ( 1 < $index ) {
$discount_id .= '-' . $index;
}
if ( isset( $this->manual_discounts[ $discount_id ] ) ) {
$index ++;
$discount_id = '';
}
}
return $discount_id;
}
/**
* Apply a discount to all items.
*
* @param string|object $raw_discount Accepts a string (fixed or percent discounts), or WC_Coupon object.
* @return bool|WP_Error True if applied or WP_Error instance in failure.
*/
public function apply_discount( $raw_discount ) {
if ( is_a( $raw_discount, 'WC_Coupon' ) ) {
return $this->apply_coupon( $raw_discount );
}
$discount = new WC_Discount;
if ( strstr( $raw_discount, '%' ) ) {
$discount->set_discount_type( 'percent' );
$discount->set_amount( trim( $raw_discount, '%' ) );
} elseif ( 0 < absint( $raw_discount ) ) {
$discount->set_discount_type( 'fixed' );
$discount->set_amount( wc_add_number_precision( absint( $raw_discount ) ) );
}
if ( ! $discount->get_amount() ) {
return new WP_Error( 'invalid_coupon', __( 'Invalid discount', 'woocommerce' ) );
}
$total_to_discount = $this->get_total_after_discounts();
if ( 'percent' === $discount->get_discount_type() ) {
$discount->set_discount_total( $discount->get_amount() * ( $total_to_discount / 100 ) );
} else {
$discount->set_discount_total( min( $discount->get_amount(), $total_to_discount ) );
}
$this->manual_discounts[ $this->generate_discount_id( $discount ) ] = $discount;
return true;
}
/**
* Apply a discount to all items using a coupon.
*
* @since 3.2.0
* @param WC_Coupon $coupon Coupon object being applied to the items.
* @return bool|WP_Error True if applied or WP_Error instance in failure.
*/
protected function apply_coupon( $coupon ) {
$is_coupon_valid = $this->is_coupon_valid( $coupon );
if ( is_wp_error( $is_coupon_valid ) ) {
return $is_coupon_valid;
}
if ( ! isset( $this->discounts[ $coupon->get_code() ] ) ) {
$this->discounts[ $coupon->get_code() ] = array_fill_keys( array_keys( $this->items ), 0 );
}
$items_to_apply = $this->get_items_to_apply_coupon( $coupon );
$coupon_type = $coupon->get_discount_type();
// Core discounts are handled here as of 3.2.
switch ( $coupon->get_discount_type() ) {
case 'percent' :
$this->apply_coupon_percent( $coupon, $items_to_apply );
break;
case 'fixed_product' :
$this->apply_coupon_fixed_product( $coupon, $items_to_apply );
break;
case 'fixed_cart' :
$this->apply_coupon_fixed_cart( $coupon, $items_to_apply );
break;
default :
foreach ( $items_to_apply as $item ) {
$discounted_price = $this->get_discounted_price_in_cents( $item );
$price_to_discount = wc_remove_number_precision( ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $item->price : $discounted_price );
$discount = min( $discounted_price, wc_add_number_precision( $coupon->get_discount_amount( $price_to_discount ), $item->object ) );
// Store code and discount amount per item.
$this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
}
break;
}
return true;
}
/**
* Sort by price.
*
* @since 3.2.0
* @param array $a First element.
* @param array $b Second element.
* @return int
*/
protected function sort_by_price( $a, $b ) {
$price_1 = $a->price * $a->quantity;
$price_2 = $b->price * $b->quantity;
if ( $price_1 === $price_2 ) {
return 0;
}
return ( $price_1 < $price_2 ) ? 1 : -1;
}
/**
* Filter out all products which have been fully discounted to 0.
* Used as array_filter callback.
*
* @since 3.2.0
* @param object $item Get data for this item.
* @return bool
*/
protected function filter_products_with_price( $item ) {
return $this->get_discounted_price_in_cents( $item ) > 0;
}
/**
* Get items which the coupon should be applied to.
*
* @since 3.2.0
* @param object $coupon Coupon object.
* @return array
*/
protected function get_items_to_apply_coupon( $coupon ) {
$items_to_apply = array();
$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();
}
foreach ( $this->items as $item ) {
if ( 0 === $this->get_discounted_price_in_cents( $item ) ) {
continue;
}
if ( ! $coupon->is_valid_for_product( $item->product, $item->object ) && ! $coupon->is_valid_for_cart() ) {
continue;
}
if ( $limit_usage_qty && $applied_count > $limit_usage_qty ) {
break;
}
if ( $limit_usage_qty && $item->quantity > ( $limit_usage_qty - $applied_count ) ) {
$limit_to_qty = absint( $limit_usage_qty - $applied_count );
$item->price = ( $item->price / $item->quantity ) * $limit_to_qty;
$item->quantity = $limit_to_qty; // Lower the qty so the discount is applied less.
}
if ( 0 >= $item->quantity ) {
continue;
}
$items_to_apply[] = $item;
$applied_count += $item->quantity;
}
return $items_to_apply;
}
/**
* Apply percent discount to items and return an array of discounts granted.
*
* @since 3.2.0
* @param WC_Coupon $coupon Coupon object. Passed through filters.
* @param array $items_to_apply Array of items to apply the coupon to.
* @return int Total discounted.
*/
protected function apply_coupon_percent( $coupon, $items_to_apply ) {
$total_discount = 0;
$cart_total = 0;
foreach ( $items_to_apply as $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 = ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $item->price: $discounted_price;
// Total up.
$cart_total += $price_to_discount;
// Run coupon calculations.
$discount = floor( $price_to_discount * ( $coupon->get_amount() / 100 ) );
$discount = min( $discounted_price, apply_filters( 'woocommerce_coupon_get_discount_amount', $discount, $price_to_discount, $item->object, false, $coupon ) );
$total_discount += $discount;
// Store code and discount amount per item.
$this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
}
// Work out how much discount would have been given to the cart has a whole and compare to what was discounted on all line items.
$cart_total_discount = wc_cart_round_discount( $cart_total * ( $coupon->get_amount() / 100 ), 0 );
if ( $total_discount < $cart_total_discount ) {
$total_discount += $this->apply_coupon_remainder( $coupon, $items_to_apply, $cart_total_discount - $total_discount );
}
return $total_discount;
}
/**
* Apply fixed product discount to items.
*
* @since 3.2.0
* @param WC_Coupon $coupon Coupon object. Passed through filters.
* @param array $items_to_apply Array of items to apply the coupon to.
* @param int $amount Fixed discount amount to apply in cents. Leave blank to pull from coupon.
* @return int Total discounted.
*/
protected function apply_coupon_fixed_product( $coupon, $items_to_apply, $amount = null ) {
$total_discount = 0;
$amount = $amount ? $amount: wc_add_number_precision( $coupon->get_amount() );
foreach ( $items_to_apply as $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 = ( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ) ? $item->price: $discounted_price;
// Run coupon calculations.
$discount = $amount * $item->quantity;
$discount = min( $discounted_price, apply_filters( 'woocommerce_coupon_get_discount_amount', $discount, $price_to_discount, $item->object, false, $coupon ) );
$total_discount += $discount;
// Store code and discount amount per item.
$this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
}
return $total_discount;
}
/**
* Apply fixed cart discount to items.
*
* @since 3.2.0
* @param WC_Coupon $coupon Coupon object. Passed through filters.
* @param array $items_to_apply Array of items to apply the coupon to.
* @param int $amount Fixed discount amount to apply in cents. Leave blank to pull from coupon.
* @return int Total discounted.
*/
protected function apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount = null ) {
$total_discount = 0;
$amount = $amount ? $amount : wc_add_number_precision( $coupon->get_amount() );
$items_to_apply = array_filter( $items_to_apply, array( $this, 'filter_products_with_price' ) );
if ( ! $item_count = array_sum( wp_list_pluck( $items_to_apply, 'quantity' ) ) ) {
return $total_discount;
}
$per_item_discount = absint( $amount / $item_count ); // round it down to the nearest cent.
if ( $per_item_discount > 0 ) {
$total_discount = $this->apply_coupon_fixed_product( $coupon, $items_to_apply, $per_item_discount );
/**
* If there is still discount remaining, repeat the process.
*/
if ( $total_discount > 0 && $total_discount < $amount ) {
$total_discount += $this->apply_coupon_fixed_cart( $coupon, $items_to_apply, $amount - $total_discount );
}
} elseif ( $amount > 0 ) {
$total_discount += $this->apply_coupon_remainder( $coupon, $items_to_apply, $amount );
}
return $total_discount;
}
/**
* Deal with remaining fractional discounts by splitting it over items
* until the amount is expired, discounting 1 cent at a time.
*
* @since 3.2.0
* @param WC_Coupon $coupon Coupon object if appliable. Passed through filters.
* @param array $items_to_apply Array of items to apply the coupon to.
* @param int $amount Fixed discount amount to apply.
* @return int Total discounted.
*/
protected function apply_coupon_remainder( $coupon, $items_to_apply, $amount ) {
$total_discount = 0;
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' ) ) ? $item->price: $discounted_price;
// Run coupon calculations.
$discount = min( $discounted_price, 1 );
// Store totals.
$total_discount += $discount;
// Store code and discount amount per item.
$this->discounts[ $coupon->get_code() ][ $item->key ] += $discount;
if ( $total_discount >= $amount ) {
break 2;
}
}
if ( $total_discount >= $amount ) {
break;
}
}
return $total_discount;
}
/*
|--------------------------------------------------------------------------
| Validation & Error Handling
|--------------------------------------------------------------------------
*/
/**
* Ensure coupon exists or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_exists( $coupon ) {
if ( ! $coupon->get_id() ) {
/* translators: %s: coupon code */
throw new Exception( sprintf( __( 'Coupon "%s" does not exist!', 'woocommerce' ), $coupon->get_code() ), 105 );
}
return true;
}
/**
* Ensure coupon usage limit is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_usage_limit( $coupon ) {
if ( $coupon->get_usage_limit() > 0 && $coupon->get_usage_count() >= $coupon->get_usage_limit() ) {
throw new Exception( __( 'Coupon usage limit has been reached.', 'woocommerce' ), 106 );
}
return true;
}
/**
* Ensure coupon user usage limit is valid or throw exception.
*
* Per user usage limit - check here if user is logged in (against user IDs).
* Checked again for emails later on in WC_Cart::check_customer_coupons().
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @param int $user_id User ID.
* @return bool
*/
protected function validate_coupon_user_usage_limit( $coupon, $user_id = 0 ) {
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
if ( $coupon->get_usage_limit_per_user() > 0 && is_user_logged_in() && $coupon->get_id() && $coupon->get_data_store() ) {
$date_store = $coupon->get_data_store();
$usage_count = $date_store->get_usage_by_user_id( $coupon, $user_id );
if ( $usage_count >= $coupon->get_usage_limit_per_user() ) {
throw new Exception( __( 'Coupon usage limit has been reached.', 'woocommerce' ), 106 );
}
}
return true;
}
/**
* Ensure coupon date is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_expiry_date( $coupon ) {
if ( $coupon->get_date_expires() && current_time( 'timestamp', true ) > $coupon->get_date_expires()->getTimestamp() ) {
throw new Exception( __( 'This coupon has expired.', 'woocommerce' ), 107 );
}
return true;
}
/**
* Ensure coupon amount is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @param float $subtotal Items subtotal.
* @return bool
*/
protected function validate_coupon_minimum_amount( $coupon, $subtotal = 0 ) {
if ( $coupon->get_minimum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_minimum_amount', $coupon->get_minimum_amount() > $subtotal, $coupon, $subtotal ) ) {
/* translators: %s: coupon minimum amount */
throw new Exception( sprintf( __( 'The minimum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_minimum_amount() ) ), 108 );
}
return true;
}
/**
* Ensure coupon amount is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @param float $subtotal Items subtotal.
* @return bool
*/
protected function validate_coupon_maximum_amount( $coupon, $subtotal = 0 ) {
if ( $coupon->get_maximum_amount() > 0 && apply_filters( 'woocommerce_coupon_validate_maximum_amount', $coupon->get_maximum_amount() < $subtotal, $coupon ) ) {
/* translators: %s: coupon maximum amount */
throw new Exception( sprintf( __( 'The maximum spend for this coupon is %s.', 'woocommerce' ), wc_price( $coupon->get_maximum_amount() ) ), 112 );
}
return true;
}
/**
* Ensure coupon is valid for products in the list is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_product_ids( $coupon ) {
if ( count( $coupon->get_product_ids() ) > 0 ) {
$valid = false;
foreach ( $this->items as $item ) {
if ( $item->product && in_array( $item->product->get_id(), $coupon->get_product_ids(), true ) || in_array( $item->product->get_parent_id(), $coupon->get_product_ids(), true ) ) {
$valid = true;
break;
}
}
if ( ! $valid ) {
throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
}
}
return true;
}
/**
* Ensure coupon is valid for product categories in the list is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_product_categories( $coupon ) {
if ( count( $coupon->get_product_categories() ) > 0 ) {
$valid = false;
foreach ( $this->items as $item ) {
if ( $coupon->get_exclude_sale_items() && $item->product && $item->product->is_on_sale() ) {
continue;
}
$product_cats = wc_get_product_cat_ids( $item->product->get_id() );
// If we find an item with a cat in our allowed cat list, the coupon is valid.
if ( count( array_intersect( $product_cats, $coupon->get_product_categories() ) ) > 0 ) {
$valid = true;
break;
}
}
if ( ! $valid ) {
throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
}
}
return true;
}
/**
* Ensure coupon is valid for sale items in the list is valid or throw exception.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_sale_items( $coupon ) {
if ( $coupon->get_exclude_sale_items() ) {
$valid = false;
foreach ( $this->items as $item ) {
if ( $item->product && ! $item->product->is_on_sale() ) {
$valid = true;
break;
}
}
if ( ! $valid ) {
throw new Exception( __( 'Sorry, this coupon is not valid for sale items.', 'woocommerce' ), 110 );
}
}
return true;
}
/**
* All exclusion rules must pass at the same time for a product coupon to be valid.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_excluded_items( $coupon ) {
if ( ! $this->items && $coupon->is_type( wc_get_product_coupon_types() ) ) {
$valid = false;
foreach ( $this->items as $item ) {
if ( $item->product && $coupon->is_valid_for_product( $item->product, $item->object ) ) {
$valid = true;
break;
}
}
if ( ! $valid ) {
throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
}
}
return true;
}
/**
* Cart discounts cannot be added if non-eligible product is found.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_eligible_items( $coupon ) {
if ( ! $coupon->is_type( wc_get_product_coupon_types() ) ) {
$this->validate_coupon_excluded_product_ids( $coupon );
$this->validate_coupon_excluded_product_categories( $coupon );
}
return true;
}
/**
* Exclude products.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_excluded_product_ids( $coupon ) {
// Exclude Products.
if ( count( $coupon->get_excluded_product_ids() ) > 0 ) {
$products = array();
foreach ( $this->items as $item ) {
if ( $item->product && in_array( $item->product->get_id(), $coupon->get_excluded_product_ids(), true ) || in_array( $item->product->get_parent_id(), $coupon->get_excluded_product_ids(), true ) ) {
$products[] = $item->product->get_name();
}
}
if ( ! empty( $products ) ) {
/* translators: %s: products list */
throw new Exception( sprintf( __( 'Sorry, this coupon is not applicable to the products: %s.', 'woocommerce' ), implode( ', ', $products ) ), 113 );
}
}
return true;
}
/**
* Exclude categories from product list.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool
*/
protected function validate_coupon_excluded_product_categories( $coupon ) {
if ( count( $coupon->get_excluded_product_categories() ) > 0 ) {
$categories = array();
foreach ( $this->items as $item ) {
if ( $coupon->get_exclude_sale_items() && $item->product && $item->product->is_on_sale() ) {
continue;
}
$product_cats = wc_get_product_cat_ids( $item->product->get_id() );
$cat_id_list = array_intersect( $product_cats, $coupon->get_excluded_product_categories() );
if ( count( $cat_id_list ) > 0 ) {
foreach ( $cat_id_list as $cat_id ) {
$cat = get_term( $cat_id, 'product_cat' );
$categories[] = $cat->name;
}
}
}
if ( ! empty( $categories ) ) {
/* translators: %s: categories list */
throw new Exception( sprintf( __( 'Sorry, this coupon is not applicable to the categories: %s.', 'woocommerce' ), implode( ', ', array_unique( $categories ) ) ), 114 );
}
}
return true;
}
/**
* Check if a coupon is valid.
*
* Error Codes:
* - 100: Invalid filtered.
* - 101: Invalid removed.
* - 102: Not yours removed.
* - 103: Already applied.
* - 104: Individual use only.
* - 105: Not exists.
* - 106: Usage limit reached.
* - 107: Expired.
* - 108: Minimum spend limit not met.
* - 109: Not applicable.
* - 110: Not valid for sale items.
* - 111: Missing coupon code.
* - 112: Maximum spend limit met.
* - 113: Excluded products.
* - 114: Excluded categories.
*
* @since 3.2.0
* @throws Exception Error message.
* @param WC_Coupon $coupon Coupon data.
* @return bool|WP_Error
*/
public function is_coupon_valid( $coupon ) {
try {
$this->validate_coupon_exists( $coupon );
$this->validate_coupon_usage_limit( $coupon );
$this->validate_coupon_user_usage_limit( $coupon );
$this->validate_coupon_expiry_date( $coupon );
$this->validate_coupon_minimum_amount( $coupon );
$this->validate_coupon_maximum_amount( $coupon );
$this->validate_coupon_product_ids( $coupon );
$this->validate_coupon_product_categories( $coupon );
$this->validate_coupon_sale_items( $coupon );
$this->validate_coupon_excluded_items( $coupon );
$this->validate_coupon_eligible_items( $coupon );
if ( ! apply_filters( 'woocommerce_coupon_is_valid', true, $coupon, $this ) ) {
throw new Exception( __( 'Coupon is not valid.', 'woocommerce' ), 100 );
}
} catch ( Exception $e ) {
/**
* Filter the coupon error message.
*
* @param string $error_message Error message.
* @param int $error_code Error code.
* @param WC_Coupon $coupon Coupon data.
*/
$message = apply_filters( 'woocommerce_coupon_error', $e->getMessage(), $e->getCode(), $coupon );
return new WP_Error( 'invalid_coupon', $message, array(
'status' => 400,
) );
}
return true;
}
}

View File

@ -28,6 +28,27 @@ class WC_Order_Item_Shipping extends WC_Order_Item {
),
);
/**
* Calculate item taxes.
*
* @since 3.2.0
* @param array $calculate_tax_for Location data to get taxes for. Required.
* @return bool True if taxes were calculated.
*/
public function calculate_taxes( $calculate_tax_for = array() ) {
if ( ! isset( $calculate_tax_for['country'], $calculate_tax_for['state'], $calculate_tax_for['postcode'], $calculate_tax_for['city'], $calculate_tax_for['tax_class'] ) ) {
return false;
}
if ( wc_tax_enabled() ) {
$tax_rates = WC_Tax::find_shipping_rates( $calculate_tax_for );
$taxes = WC_Tax::calc_tax( $this->get_total(), $tax_rates, false );
$this->set_taxes( array( 'total' => $taxes ) );
} else {
$this->set_taxes( false );
}
return true;
}
/*
|--------------------------------------------------------------------------
| Setters

View File

@ -152,7 +152,8 @@ class WC_Order_Item extends WC_Data implements ArrayAccess {
*/
/**
* Type checking
* Type checking.
*
* @param string|array $type
* @return boolean
*/
@ -160,6 +161,34 @@ class WC_Order_Item extends WC_Data implements ArrayAccess {
return is_array( $type ) ? in_array( $this->get_type(), $type ) : $type === $this->get_type();
}
/**
* Calculate item taxes.
*
* @since 3.2.0
* @param array $calculate_tax_for Location data to get taxes for. Required.
* @return bool True if taxes were calculated.
*/
public function calculate_taxes( $calculate_tax_for = array() ) {
if ( ! isset( $calculate_tax_for['country'], $calculate_tax_for['state'], $calculate_tax_for['postcode'], $calculate_tax_for['city'] ) ) {
return false;
}
if ( '0' !== $this->get_tax_class() && 'taxable' === $this->get_tax_status() && wc_tax_enabled() ) {
$calculate_tax_for['tax_class'] = $this->get_tax_class();
$tax_rates = WC_Tax::find_rates( $calculate_tax_for );
$taxes = WC_Tax::calc_tax( $this->get_total(), $tax_rates, false );
if ( method_exists( $this, 'get_subtotal' ) ) {
$subtotal_taxes = WC_Tax::calc_tax( $this->get_subtotal(), $tax_rates, false );
$this->set_taxes( array( 'total' => $taxes, 'subtotal' => $subtotal_taxes ) );
} else {
$this->set_taxes( array( 'total' => $taxes ) );
}
} else {
$this->set_taxes( false );
}
return true;
}
/*
|--------------------------------------------------------------------------
| Meta Data Handling

View File

@ -26,12 +26,6 @@ class WC_Shipping {
/** @var array|null Stores methods loaded into woocommerce. */
public $shipping_methods = null;
/** @var float Stores the cost of shipping */
public $shipping_total = 0;
/** @var array Stores an array of shipping taxes. */
public $shipping_taxes = array();
/** @var array Stores the shipping classes. */
public $shipping_classes = array();
@ -237,18 +231,17 @@ class WC_Shipping {
/**
* Calculate shipping for (multiple) packages of cart items.
*
* @param array $packages multi-dimensional array of cart items to calc shipping for
* @param array $packages multi-dimensional array of cart items to calc shipping for.
* @return array Array of calculated packages.
*/
public function calculate_shipping( $packages = array() ) {
$this->shipping_total = 0;
$this->shipping_taxes = array();
$this->packages = array();
$this->packages = array();
if ( ! $this->enabled || empty( $packages ) ) {
return;
return array();
}
// Calculate costs for passed packages
// Calculate costs for passed packages.
foreach ( $packages as $package_key => $package ) {
$this->packages[ $package_key ] = $this->calculate_shipping_for_package( $package, $package_key );
}
@ -264,58 +257,9 @@ class WC_Shipping {
*
* @param array $packages The array of packages after shipping costs are calculated.
*/
$this->packages = apply_filters( 'woocommerce_shipping_packages', $this->packages );
$this->packages = array_filter( (array) apply_filters( 'woocommerce_shipping_packages', $this->packages ) );
if ( ! is_array( $this->packages ) || empty( $this->packages ) ) {
return;
}
// Get all chosen methods
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$method_counts = WC()->session->get( 'shipping_method_counts' );
// Get chosen methods for each package
foreach ( $this->packages as $i => $package ) {
$chosen_method = false;
$method_count = false;
if ( ! empty( $chosen_methods[ $i ] ) ) {
$chosen_method = $chosen_methods[ $i ];
}
if ( ! empty( $method_counts[ $i ] ) ) {
$method_count = absint( $method_counts[ $i ] );
}
if ( sizeof( $package['rates'] ) > 0 ) {
// If not set, not available, or available methods have changed, set to the DEFAULT option
if ( empty( $chosen_method ) || ! isset( $package['rates'][ $chosen_method ] ) || sizeof( $package['rates'] ) !== $method_count ) {
$chosen_method = apply_filters( 'woocommerce_shipping_chosen_method', $this->get_default_method( $package['rates'], false ), $package['rates'], $chosen_method );
$chosen_methods[ $i ] = $chosen_method;
$method_counts[ $i ] = sizeof( $package['rates'] );
do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
}
// Store total costs
if ( $chosen_method && isset( $package['rates'][ $chosen_method ] ) ) {
$rate = $package['rates'][ $chosen_method ];
// Merge cost and taxes - label and ID will be the same
$this->shipping_total += $rate->cost;
if ( ! empty( $rate->taxes ) && is_array( $rate->taxes ) ) {
foreach ( array_keys( $this->shipping_taxes + $rate->taxes ) as $key ) {
$this->shipping_taxes[ $key ] = ( isset( $rate->taxes[ $key ] ) ? $rate->taxes[ $key ] : 0 ) + ( isset( $this->shipping_taxes[ $key ] ) ? $this->shipping_taxes[ $key ] : 0 );
}
}
}
}
}
// Save all chosen methods (array)
WC()->session->set( 'chosen_shipping_methods', $chosen_methods );
WC()->session->set( 'shipping_method_counts', $method_counts );
return $this->packages;
}
/**
@ -396,8 +340,6 @@ class WC_Shipping {
*/
public function reset_shipping() {
unset( WC()->session->chosen_shipping_methods );
$this->shipping_total = 0;
$this->shipping_taxes = array();
$this->packages = array();
}

View File

@ -452,13 +452,18 @@ class WC_Tax {
* Used by get_rates(), get_shipping_rates().
*
* @param $tax_class string Optional, passed to the filter for advanced tax setups.
* @param object $customer Override the customer object to get their location.
* @return array
*/
public static function get_tax_location( $tax_class = '' ) {
public static function get_tax_location( $tax_class = '', $customer = null ) {
$location = array();
if ( ! empty( WC()->customer ) ) {
$location = WC()->customer->get_taxable_address();
if ( is_null( $customer ) && ! empty( WC()->customer ) ) {
$customer = WC()->customer;
}
if ( ! empty( $customer ) ) {
$location = $customer->get_taxable_address();
} elseif ( wc_prices_include_tax() || 'base' === get_option( 'woocommerce_default_customer_address' ) || 'base' === get_option( 'woocommerce_tax_based_on' ) ) {
$location = array(
WC()->countries->get_base_country(),
@ -468,17 +473,19 @@ class WC_Tax {
);
}
return apply_filters( 'woocommerce_get_tax_location', $location, $tax_class );
return apply_filters( 'woocommerce_get_tax_location', $location, $tax_class, $customer );
}
/**
* Get's an array of matching rates for a tax class.
* @param string $tax_class
*
* @param string $tax_class Tax class to get rates for.
* @param object $customer Override the customer object to get their location.
* @return array
*/
public static function get_rates( $tax_class = '' ) {
public static function get_rates( $tax_class = '', $customer = null ) {
$tax_class = sanitize_title( $tax_class );
$location = self::get_tax_location( $tax_class );
$location = self::get_tax_location( $tax_class, $customer );
$matched_tax_rates = array();
if ( sizeof( $location ) === 4 ) {
@ -526,10 +533,11 @@ class WC_Tax {
/**
* Gets an array of matching shipping tax rates for a given class.
*
* @param string Tax Class
* @return mixed
* @param string $tax_class Tax class to get rates for.
* @param object $customer Override the customer object to get their location.
* @return mixed
*/
public static function get_shipping_tax_rates( $tax_class = null ) {
public static function get_shipping_tax_rates( $tax_class = null, $customer = null ) {
// See if we have an explicitly set shipping tax class
$shipping_tax_class = get_option( 'woocommerce_shipping_tax_class' );
@ -537,7 +545,7 @@ class WC_Tax {
$tax_class = $shipping_tax_class;
}
$location = self::get_tax_location( $tax_class );
$location = self::get_tax_location( $tax_class, $customer );
$matched_tax_rates = array();
if ( sizeof( $location ) === 4 ) {

View File

@ -335,6 +335,8 @@ final class WooCommerce {
include_once( WC_ABSPATH . 'includes/class-wc-deprecated-action-hooks.php' );
include_once( WC_ABSPATH . 'includes/class-wc-deprecated-filter-hooks.php' );
include_once( WC_ABSPATH . 'includes/class-wc-background-emailer.php' );
include_once( WC_ABSPATH . 'includes/class-wc-discounts.php' );
include_once( WC_ABSPATH . 'includes/class-wc-cart-totals.php' );
/**
* Data stores - used to store and retrieve CRUD object data from the database.

View File

@ -0,0 +1,150 @@
<?php
/**
* Legacy cart
*
* Legacy and deprecated functions are here to keep the WC_Cart class clean.
* This class will be removed in future versions.
*
* @version 3.2.0
* @package WooCommerce/Classes
* @category Class
* @author Automattic
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Legacy cart class.
*/
abstract class WC_Legacy_Cart {
/**
* Contains an array of coupon usage counts after they have been applied.
*
* @deprecated 3.2.0
* @var array
*/
public $coupon_applied_count = array();
/**
* Function to apply discounts to a product and get the discounted price (before tax is applied).
*
* @deprecated Calculation and coupon logic is handled in WC_Cart_Totals.
* @param mixed $values Cart item.
* @param mixed $price Price of item.
* @param bool $add_totals Legacy.
* @return float price
*/
public function get_discounted_price( $values, $price, $add_totals = false ) {
wc_deprecated_function( 'WC_Cart::get_discounted_price', '3.2', '' );
$cart_item_key = $values['key'];
$cart_item = $this->cart_contents[ $cart_item_key ];
return $cart_item->get_line_total();
}
/**
* Gets the url to the cart page.
*
* @deprecated 2.5.0 in favor to wc_get_cart_url()
* @return string url to page
*/
public function get_cart_url() {
wc_deprecated_function( 'WC_Cart::get_cart_url', '2.5', 'wc_get_cart_url' );
return wc_get_cart_url();
}
/**
* Gets the url to the checkout page.
*
* @deprecated 2.5.0 in favor to wc_get_checkout_url()
* @return string url to page
*/
public function get_checkout_url() {
wc_deprecated_function( 'WC_Cart::get_checkout_url', '2.5', 'wc_get_checkout_url' );
return wc_get_checkout_url();
}
/**
* Sees if we need a shipping address.
*
* @deprecated 2.5.0 in favor to wc_ship_to_billing_address_only()
* @return bool
*/
public function ship_to_billing_address_only() {
wc_deprecated_function( 'WC_Cart::ship_to_billing_address_only', '2.5', 'wc_ship_to_billing_address_only' );
return wc_ship_to_billing_address_only();
}
/**
* Coupons enabled function. Filterable.
*
* @deprecated 2.5.0 in favor to wc_coupons_enabled()
* @return bool
*/
public function coupons_enabled() {
return wc_coupons_enabled();
}
/**
* Gets the total (product) discount amount - these are applied before tax.
*
* @deprecated Order discounts (after tax) removed in 2.3 so multiple methods for discounts are no longer required.
* @return mixed formatted price or false if there are none.
*/
public function get_discounts_before_tax() {
wc_deprecated_function( 'get_discounts_before_tax', '2.3', 'get_total_discount' );
if ( $this->get_cart_discount_total() ) {
$discounts_before_tax = wc_price( $this->get_cart_discount_total() );
} else {
$discounts_before_tax = false;
}
return apply_filters( 'woocommerce_cart_discounts_before_tax', $discounts_before_tax, $this );
}
/**
* Get the total of all order discounts (after tax discounts).
*
* @deprecated Order discounts (after tax) removed in 2.3.
* @return int
*/
public function get_order_discount_total() {
wc_deprecated_function( 'get_order_discount_total', '2.3' );
return 0;
}
/**
* Function to apply cart discounts after tax.
*
* @deprecated Coupons can not be applied after tax.
* @param $values
* @param $price
*/
public function apply_cart_discounts_after_tax( $values, $price ) {
wc_deprecated_function( 'apply_cart_discounts_after_tax', '2.3' );
}
/**
* Function to apply product discounts after tax.
*
* @deprecated Coupons can not be applied after tax.
*
* @param $values
* @param $price
*/
public function apply_product_discounts_after_tax( $values, $price ) {
wc_deprecated_function( 'apply_product_discounts_after_tax', '2.3' );
}
/**
* Gets the order discount amount - these are applied after tax.
*
* @deprecated Coupons can not be applied after tax.
*/
public function get_discounts_after_tax() {
wc_deprecated_function( 'get_discounts_after_tax', '2.3' );
}
}

View File

@ -387,3 +387,69 @@ function wc_get_chosen_shipping_method_ids() {
}
return $method_ids;
}
/**
* Get chosen method for package from session.
*
* @since 3.2.0
* @param int $key
* @param array $package
* @return string|bool
*/
function wc_get_chosen_shipping_method_for_package( $key, $package ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_method = isset( $chosen_methods[ $key ] ) ? $chosen_methods[ $key ] : false;
$changed = wc_shipping_methods_have_changed( $key, $package );
// If not set, not available, or available methods have changed, set to the DEFAULT option
if ( ! $chosen_method || $changed || ! isset( $package['rates'][ $chosen_method ] ) ) {
$chosen_method = wc_get_default_shipping_method_for_package( $key, $package, $chosen_method );
$chosen_methods[ $key ] = $chosen_method;
WC()->session->set( 'chosen_shipping_methods', $chosen_methods );
do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
}
return $chosen_method;
}
/**
* Choose the default method for a package.
*
* @since 3.2.0
* @param string $key
* @param array $package
* @return string
*/
function wc_get_default_shipping_method_for_package( $key, $package, $chosen_method ) {
$rate_keys = array_keys( $package['rates'] );
$default = current( $rate_keys );
$coupons = WC()->cart->get_coupons();
foreach ( $coupons as $coupon ) {
if ( $coupon->get_free_shipping() ) {
foreach ( $rate_keys as $rate_key ) {
if ( 0 === stripos( $rate_key, 'free_shipping' ) ) {
$default = $rate_key;
break;
}
}
break;
}
}
return apply_filters( 'woocommerce_shipping_chosen_method', $default, $package['rates'], $chosen_method );
}
/**
* See if the methods have changed since the last request.
*
* @since 3.2.0
* @param int $key
* @param array $package
* @return bool
*/
function wc_shipping_methods_have_changed( $key, $package ) {
// Lookup previous methods from session.
$previous_shipping_methods = WC()->session->get( 'previous_shipping_methods' );
// Get new and old rates.
$new_rates = array_keys( $package['rates'] );
$prev_rates = isset( $previous_shipping_methods[ $key ] ) ? $previous_shipping_methods[ $key ] : false;
// Update session.
$previous_shipping_methods[ $key ] = $new_rates;
WC()->session->set( 'previous_shipping_methods', $previous_shipping_methods );
return $new_rates != $prev_rates;
}

View File

@ -1443,6 +1443,66 @@ function wc_get_rounding_precision() {
return $precision;
}
/**
* Add precision to a number and return an int.
*
* @since 3.2.0
* @param float $value Number to add precision to.
* @return int
*/
function wc_add_number_precision( $value ) {
$precision = pow( 10, wc_get_price_decimals() );
return $value * $precision;
}
/**
* Remove precision from a number and return a float.
*
* @since 3.2.0
* @param float $value Number to add precision to.
* @return float
*/
function wc_remove_number_precision( $value ) {
$precision = pow( 10, wc_get_price_decimals() );
return wc_format_decimal( $value / $precision, wc_get_price_decimals() );
}
/**
* Add precision to an array of number and return an array of int.
*
* @since 3.2.0
* @param array $value Number to add precision to.
* @return int
*/
function wc_add_number_precision_deep( $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $key => $subvalue ) {
$value[ $key ] = wc_add_number_precision_deep( $subvalue );
}
} else {
$value = wc_add_number_precision( $value );
}
return $value;
}
/**
* Remove precision from an array of number and return an array of int.
*
* @since 3.2.0
* @param array $value Number to add precision to.
* @return int
*/
function wc_remove_number_precision_deep( $value ) {
if ( is_array( $value ) ) {
foreach ( $value as $key => $subvalue ) {
$value[ $key ] = wc_remove_number_precision_deep( $subvalue );
}
} else {
$value = wc_remove_number_precision( $value );
}
return $value;
}
/**
* Get a shared logger instance.
*

View File

@ -216,11 +216,12 @@ function wc_trim_zeros( $price ) {
/**
* Round a tax amount.
*
* @param mixed $tax
* @param double $tax Amount to round.
* @param int $dp DP to round. Defaults to wc_get_price_decimals.
* @return double
*/
function wc_round_tax_total( $tax ) {
$dp = wc_get_price_decimals();
function wc_round_tax_total( $tax, $dp = null ) {
$dp = is_null( $dp ) ? wc_get_price_decimals() : absint( $dp );
// @codeCoverageIgnoreStart
if ( version_compare( phpversion(), '5.3', '<' ) ) {

View File

@ -18,8 +18,10 @@
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">.</directory>
<exclude>
<directory suffix=".php">./apigen/</directory>
<directory suffix=".php">./i18n/</directory>
<directory>./apigen/</directory>
<directory>./assets/</directory>
<directory>./dummy-data/</directory>
<directory>./i18n/</directory>
<directory suffix=".php">./includes/api/legacy/</directory>
<directory suffix=".php">./includes/gateways/simplify-commerce-deprecated/</directory>
<directory suffix=".php">./includes/gateways/simplify-commerce/includes/</directory>
@ -33,6 +35,10 @@
<directory suffix=".php">./includes/vendor/</directory>
<directory suffix=".php">./includes/widgets/</directory>
<directory suffix=".php">./templates/</directory>
<directory>./tests/</directory>
<directory>./vendor/</directory>
<directory>./.*/</directory>
<directory>./tmp/</directory>
<directory suffix=".php">./tests/</directory>
<directory suffix=".php">./tmp/</directory>
<directory suffix=".php">./vendor/</directory>

44
phpunit.xml.dist Normal file
View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
bootstrap="tests/bootstrap.php"
backupGlobals="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
verbose="true"
syntaxCheck="true"
>
<testsuites>
<testsuite name="WooCommerce Test Suite">
<directory suffix=".php">./tests/unit-tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">.</directory>
<exclude>
<directory>./apigen/</directory>
<directory>./assets/</directory>
<directory>./dummy-data/</directory>
<directory>./i18n/</directory>
<directory suffix=".php">./includes/api/legacy/</directory>
<directory suffix=".php">./includes/gateways/simplify-commerce-deprecated/</directory>
<directory suffix=".php">./includes/gateways/simplify-commerce/includes/</directory>
<directory suffix=".php">./includes/libraries/</directory>
<directory suffix=".php">./includes/shipping/legacy-flat-rate/</directory>
<directory suffix=".php">./includes/shipping/legacy-free-shipping/</directory>
<directory suffix=".php">./includes/shipping/legacy-international-delivery/</directory>
<directory suffix=".php">./includes/shipping/legacy-local-delivery/</directory>
<directory suffix=".php">./includes/shipping/legacy-local-pickup/</directory>
<directory suffix=".php">./includes/updates/</directory>
<directory suffix=".php">./includes/widgets/</directory>
<directory suffix=".php">./templates/</directory>
<directory>./tests/</directory>
<directory>./vendor/</directory>
<directory>./.*/</directory>
<directory>./tmp/</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@ -25,7 +25,7 @@ class WC_Helper_Shipping {
update_option( 'woocommerce_flat_rate_settings', $flat_rate_settings );
update_option( 'woocommerce_flat_rate', array() );
WC_Cache_Helper::get_transient_version( 'shipping', true );
WC()->shipping->unregister_shipping_methods();
WC()->shipping->load_shipping_methods();
}
/**

View File

@ -150,6 +150,75 @@ class WC_Tests_Cart extends WC_Unit_Test_Case {
WC_Helper_Coupon::delete_coupon( $coupon->get_id() );
}
/**
* Test that calculation rounding is done correctly with and without taxes.
*
* @see https://github.com/woocommerce/woocommerce/issues/16305
* @since 3.2
*/
public function test_discount_cart_rounding() {
global $wpdb;
# Test with no taxes.
WC()->cart->empty_cart();
WC()->cart->remove_coupons();
$product = new WC_Product_Simple;
$product->set_regular_price( 51.86 );
$product->save();
$coupon = new WC_Coupon;
$coupon->set_code( 'testpercent' );
$coupon->set_discount_type( 'percent' );
$coupon->set_amount( 40 );
$coupon->save();
WC()->cart->add_to_cart( $product->get_id(), 1 );
WC()->cart->add_discount( $coupon->get_code() );
WC()->cart->calculate_totals();
$cart_item = current( WC()->cart->get_cart() );
$this->assertEquals( '31.12', number_format( $cart_item['line_total'], 2, '.', '' ) );
// Clean up.
WC()->cart->empty_cart();
WC()->cart->remove_coupons();
# Test with taxes.
update_option( 'woocommerce_prices_include_tax', 'no' );
update_option( 'woocommerce_calc_taxes', 'yes' );
$tax_rate = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '8.2500',
'tax_rate_name' => 'TAX',
'tax_rate_priority' => '1',
'tax_rate_compound' => '0',
'tax_rate_shipping' => '1',
'tax_rate_order' => '1',
'tax_rate_class' => '',
);
WC_Tax::_insert_tax_rate( $tax_rate );
WC()->cart->add_to_cart( $product->get_id(), 1 );
WC()->cart->add_discount( $coupon->get_code() );
WC()->cart->calculate_totals();
$cart_item = current( WC()->cart->get_cart() );
$this->assertEquals( '33.69', number_format( $cart_item['line_total'] + $cart_item['line_tax'], 2, '.', '' ) );
// Clean up.
WC()->cart->empty_cart();
WC()->cart->remove_coupons();
WC_Helper_Product::delete_product( $product->get_id() );
WC_Helper_Coupon::delete_coupon( $coupon->get_id() );
$wpdb->query( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rates" );
$wpdb->query( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations" );
update_option( 'woocommerce_prices_include_tax', 'no' );
update_option( 'woocommerce_calc_taxes', 'no' );
}
/**
* Test get_remove_url.
*

View File

@ -0,0 +1,36 @@
<?php
/**
* Test for the discount class.
* @package WooCommerce\Tests\Discounts
*/
class WC_Tests_Discount extends WC_Unit_Test_Case {
/**
* Test get and set ID.
*/
public function test_get_set_amount() {
$discount = new WC_Discount;
$discount->set_amount( '10' );
$this->assertEquals( '10', $discount->get_amount() );
}
public function test_get_set_type() {
$discount = new WC_Discount;
$discount->set_discount_type( 'fixed' );
$this->assertEquals( 'fixed', $discount->get_discount_type() );
$discount->set_discount_type( 'percent' );
$this->assertEquals( 'percent', $discount->get_discount_type() );
}
/**
* Test get and set discount total.
*/
public function test_get_set_discount_total() {
$discount = new WC_Discount;
$discount->set_discount_total( 1000 );
$this->assertEquals( 1000, $discount->get_discount_total() );
}
}

View File

@ -0,0 +1,459 @@
<?php
/**
* Test for the discounts class.
* @package WooCommerce\Tests\Discounts
*/
class WC_Tests_Discounts extends WC_Unit_Test_Case {
/**
* Test get and set items.
*/
public function test_get_set_items_from_cart() {
// Create dummy product - price will be 10
$product = WC_Helper_Product::create_simple_product();
// Add product to the cart.
WC()->cart->add_to_cart( $product->get_id(), 1 );
// Add product to a dummy order.
$order = new WC_Order();
$order->add_product( $product, 1 );
$order->calculate_totals();
$order->save();
// Test setting items to the cart.
$discounts = new WC_Discounts();
$discounts->set_items_from_cart( WC()->cart );
$this->assertEquals( 1, count( $discounts->get_items() ) );
// Test setting items to an order.
$discounts = new WC_Discounts();
$discounts->set_items_from_cart( WC()->cart );
$this->assertEquals( 1, count( $discounts->get_items() ) );
// Empty array of items.
$discounts = new WC_Discounts();
$discounts->set_items_from_cart( array() );
$this->assertEquals( array(), $discounts->get_items() );
// Invalid items.
$discounts = new WC_Discounts();
$discounts->set_items_from_cart( false );
$this->assertEquals( array(), $discounts->get_items() );
// Cleanup.
WC()->cart->empty_cart();
$product->delete( true );
$order->delete( true );
}
/**
* Test applying a coupon (make sure it changes prices).
*/
public function test_apply_coupon() {
$discounts = new WC_Discounts();
// Create dummy content.
$product = WC_Helper_Product::create_simple_product();
$product->set_tax_status( 'taxable' );
$product->save();
WC()->cart->empty_cart();
WC()->cart->add_to_cart( $product->get_id(), 1 );
$coupon = WC_Helper_Coupon::create_coupon( 'test' );
$coupon->set_amount( 10 );
// Apply a percent discount.
$coupon->set_discount_type( 'percent' );
$discounts->set_items_from_cart( WC()->cart );
$discounts->apply_discount( $coupon );
$this->assertEquals( 9, $discounts->get_discounted_price( current( $discounts->get_items() ) ), print_r( $discounts->get_discounts(), true ) );
// Apply a fixed cart coupon.
$coupon->set_discount_type( 'fixed_cart' );
$discounts->set_items_from_cart( WC()->cart );
$discounts->apply_discount( $coupon );
$this->assertEquals( 0, $discounts->get_discounted_price( current( $discounts->get_items() ) ), print_r( $discounts->get_discounts(), true ) );
// Apply a fixed product coupon.
$coupon->set_discount_type( 'fixed_product' );
$discounts->set_items_from_cart( WC()->cart );
$discounts->apply_discount( $coupon );
$this->assertEquals( 0, $discounts->get_discounted_price( current( $discounts->get_items() ) ), print_r( $discounts->get_discounts(), true ) );
// Cleanup.
WC()->cart->empty_cart();
$product->delete( true );
$coupon->delete( true );
}
/**
* Test various discount calculations are working correctly and produding expected results.
*/
public function test_calculations() {
$tax_rate = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '20.0000',
'tax_rate_name' => 'VAT',
'tax_rate_priority' => '1',
'tax_rate_compound' => '0',
'tax_rate_shipping' => '1',
'tax_rate_order' => '1',
'tax_rate_class' => '',
);
$tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
update_option( 'woocommerce_calc_taxes', 'yes' );
$tests = array(
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 1,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'percent',
'amount' => '20',
),
),
'expected_total_discount' => 2,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 2,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'fixed_cart',
'amount' => '10',
),
),
'expected_total_discount' => 10,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'fixed_cart',
'amount' => '10',
),
),
'expected_total_discount' => 10,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'fixed_cart',
'amount' => '10',
),
),
'expected_total_discount' => 10,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 2,
),
array(
'price' => 10,
'qty' => 3,
),
array(
'price' => 10,
'qty' => 2,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'fixed_cart',
'amount' => '10',
),
),
'expected_total_discount' => 10,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
array(
'price' => 10,
'qty' => 1,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'fixed_cart',
'amount' => '10',
),
),
'expected_total_discount' => 10,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 1,
'qty' => 1,
),
array(
'price' => 1,
'qty' => 1,
),
array(
'price' => 1,
'qty' => 1,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'fixed_cart',
'amount' => '1',
),
),
'expected_total_discount' => 1,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 2,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'percent',
'amount' => '10',
'limit_usage_to_x_items' => 1,
),
),
'expected_total_discount' => 1,
),
array(
'prices_include_tax' => false,
'cart' => array(
array(
'price' => 10,
'qty' => 2,
),
array(
'price' => 10,
'qty' => 2,
),
),
'coupons' => array(
array(
'code' => 'test',
'discount_type' => 'percent',
'amount' => '10',
'limit_usage_to_x_items' => 1,
),
),
'expected_total_discount' => 1,
),
);
$coupon = WC_Helper_Coupon::create_coupon( 'test' );
foreach ( $tests as $test_index => $test ) {
$discounts = new WC_Discounts();
$products = array();
foreach ( $test['cart'] as $item ) {
$product = WC_Helper_Product::create_simple_product();
$product->set_regular_price( $item['price'] );
$product->set_tax_status( 'taxable' );
$product->save();
WC()->cart->add_to_cart( $product->get_id(), $item['qty'] );
$products[] = $product;
}
$discounts->set_items_from_cart( WC()->cart );
foreach ( $test['coupons'] as $coupon_props ) {
$coupon->set_props( $coupon_props );
$discounts->apply_discount( $coupon );
}
$all_discounts = $discounts->get_discounts();
$this->assertEquals( $test['expected_total_discount'], array_sum( $all_discounts['test'] ), 'Test case ' . $test_index . ' failed (' . print_r( $test, true ) . ' - ' . print_r( $discounts->get_discounts(), true ) . ')' );
// Clean.
WC()->cart->empty_cart();
foreach ( $products as $product ) {
$product->delete( true );
}
}
WC_Tax::_delete_tax_rate( $tax_rate_id );
update_option( 'woocommerce_calc_taxes', 'no' );
$coupon->delete( true );
}
/**
* Test apply_discount method.
*/
public function test_apply_discount() {
$tax_rate = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '20.0000',
'tax_rate_name' => 'VAT',
'tax_rate_priority' => '1',
'tax_rate_compound' => '0',
'tax_rate_shipping' => '1',
'tax_rate_order' => '1',
'tax_rate_class' => '',
);
$tax_rate2 = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '20.0000',
'tax_rate_name' => 'VAT',
'tax_rate_priority' => '1',
'tax_rate_compound' => '0',
'tax_rate_shipping' => '1',
'tax_rate_order' => '1',
'tax_rate_class' => 'reduced-rate',
);
$tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
$tax_rate_id2 = WC_Tax::_insert_tax_rate( $tax_rate2 );
update_option( 'woocommerce_calc_taxes', 'yes' );
$product = WC_Helper_Product::create_simple_product();
$product2 = WC_Helper_Product::create_simple_product();
$product->set_tax_class( '' );
$product2->set_tax_class( 'reduced-rate' );
$product->save();
$product2->save();
// Add product to the cart.
WC()->cart->empty_cart();
WC()->cart->add_to_cart( $product->get_id(), 1 );
WC()->cart->add_to_cart( $product2->get_id(), 1 );
$discounts = new WC_Discounts();
$discounts->set_items_from_cart( WC()->cart );
$discounts->apply_discount( '50%' );
$all_discounts = $discounts->get_discounts();
$this->assertEquals( 10, $all_discounts['discount-50%'], print_r( $all_discounts, true ) );
$discounts->apply_discount( '50%' );
$all_discounts = $discounts->get_discounts();
$this->assertEquals( 10, $all_discounts['discount-50%'], print_r( $all_discounts, true ) );
$this->assertEquals( 5, $all_discounts['discount-50%-2'], print_r( $all_discounts, true ) );
// Test fixed discounts.
$discounts = new WC_Discounts();
$discounts->set_items_from_cart( WC()->cart );
$discounts->apply_discount( '5' );
$all_discounts = $discounts->get_discounts();
$this->assertEquals( 5, $all_discounts['discount-500'] );
$discounts->apply_discount( '5' );
$all_discounts = $discounts->get_discounts();
$this->assertEquals( 5, $all_discounts['discount-500'], print_r( $all_discounts, true ) );
$this->assertEquals( 5, $all_discounts['discount-500-2'], print_r( $all_discounts, true ) );
$discounts->apply_discount( '15' );
$all_discounts = $discounts->get_discounts();
$this->assertEquals( 5, $all_discounts['discount-500'], print_r( $all_discounts, true ) );
$this->assertEquals( 5, $all_discounts['discount-500-2'], print_r( $all_discounts, true ) );
$this->assertEquals( 10, $all_discounts['discount-1500'], print_r( $all_discounts, true ) );
// Cleanup.
WC()->cart->empty_cart();
$product->delete( true );
$product2->delete( true );
WC_Tax::_delete_tax_rate( $tax_rate_id );
WC_Tax::_delete_tax_rate( $tax_rate_id2 );
update_option( 'woocommerce_calc_taxes', 'no' );
}
}

View File

@ -0,0 +1,159 @@
<?php
/**
* Tests for the totals class.
*
* @package WooCommerce\Tests\Discounts
*/
/**
* WC_Tests_Totals
*/
class WC_Tests_Totals extends WC_Unit_Test_Case {
/**
* Totals class for getter tests.
*
* @var object
*/
protected $totals;
/**
* ID tracking for cleanup.
*
* @var array
*/
protected $ids = array();
/**
* Setup the cart for totals calculation.
*/
public function setUp() {
$this->ids = array();
if ( ! defined( 'WOOCOMMERCE_CHECKOUT' ) ) {
define( 'WOOCOMMERCE_CHECKOUT', 1 );
}
$tax_rate = array(
'tax_rate_country' => '',
'tax_rate_state' => '',
'tax_rate' => '20.0000',
'tax_rate_name' => 'VAT',
'tax_rate_priority' => '1',
'tax_rate_compound' => '0',
'tax_rate_shipping' => '1',
'tax_rate_order' => '1',
'tax_rate_class' => '',
);
$tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
update_option( 'woocommerce_calc_taxes', 'yes' );
update_option( 'woocommerce_default_customer_address', 'base' );
update_option( 'woocommerce_tax_based_on', 'base' );
$product = WC_Helper_Product::create_simple_product();
$product2 = WC_Helper_Product::create_simple_product();
WC_Helper_Shipping::create_simple_flat_rate();
WC()->session->set( 'chosen_shipping_methods', array( 'flat_rate' ) );
$coupon = new WC_Coupon;
$coupon->set_code( 'test-coupon-10' );
$coupon->set_amount( 10 );
$coupon->set_discount_type( 'percent' );
$coupon->save();
$this->ids['tax_rate_ids'][] = $tax_rate_id;
$this->ids['products'][] = $product;
$this->ids['products'][] = $product2;
$this->ids['coupons'][] = $coupon;
WC()->cart->add_to_cart( $product->get_id(), 1 );
WC()->cart->add_to_cart( $product2->get_id(), 2 );
WC()->cart->add_discount( $coupon->get_code() );
add_action( 'woocommerce_cart_calculate_fees', array( $this, 'add_cart_fees_callback' ) );
$this->totals = new WC_Cart_Totals( WC()->cart );
}
/**
* Add fees when the fees API is called.
*/
public function add_cart_fees_callback() {
WC()->cart->add_fee( 'test fee', 10, true );
WC()->cart->add_fee( 'test fee 2', 20, true );
WC()->cart->add_fee( 'test fee non-taxable', 10, false );
}
/**
* Clean up after test.
*/
public function tearDown() {
WC()->cart->empty_cart();
WC()->session->set( 'chosen_shipping_methods', array() );
WC_Helper_Shipping::delete_simple_flat_rate();
update_option( 'woocommerce_calc_taxes', 'no' );
remove_action( 'woocommerce_cart_calculate_fees', array( $this, 'add_cart_fees_callback' ) );
foreach ( $this->ids['products'] as $product ) {
$product->delete( true );
}
foreach ( $this->ids['coupons'] as $coupon ) {
$coupon->delete( true );
wp_cache_delete( WC_Cache_Helper::get_cache_prefix( 'coupons' ) . 'coupon_id_from_code_' . $coupon->get_code(), 'coupons' );
}
foreach ( $this->ids['tax_rate_ids'] as $tax_rate_id ) {
WC_Tax::_delete_tax_rate( $tax_rate_id );
}
$this->ids = array();
}
/**
* Test get and set items.
*/
public function test_get_totals() {
$this->assertEquals( array(
'fees_total' => 40.00,
'fees_total_tax' => 6.00,
'items_subtotal' => 30.00,
'items_subtotal_tax' => 6.00,
'items_total' => 27.00,
'items_total_tax' => 5.40,
'total' => 90.40,
'taxes' => array(
$this->ids['tax_rate_ids'][0] => array(
'tax_total' => 11.40,
'shipping_tax_total' => 2.00,
),
),
'tax_total' => 11.40,
'shipping_total' => 10,
'shipping_tax_total' => 2,
'discounts_total' => 3.00,
'discounts_tax_total' => 0.60,
), $this->totals->get_totals() );
}
/**
* Test that cart totals get updated.
*/
public function test_cart_totals() {
$cart = WC()->cart;
$this->assertEquals( 40.00, $cart->fee_total );
$this->assertEquals( 27.00, $cart->cart_contents_total );
$this->assertEquals( 90.40, $cart->total );
$this->assertEquals( 36.00, $cart->subtotal );
$this->assertEquals( 30.00, $cart->subtotal_ex_tax );
$this->assertEquals( 11.40, $cart->tax_total );
$this->assertEquals( 2.40, $cart->discount_cart );
$this->assertEquals( 0.60, $cart->discount_cart_tax );
$this->assertEquals( 40.00, $cart->fee_total );
$this->assertEquals( 10, $cart->shipping_total );
$this->assertEquals( 2, $cart->shipping_tax_total );
}
}