diff --git a/includes/class-wc-cart.php b/includes/class-wc-cart.php index 23e17377e94..3db24df3ed9 100644 --- a/includes/class-wc-cart.php +++ b/includes/class-wc-cart.php @@ -18,6 +18,12 @@ if ( ! defined( 'ABSPATH' ) ) { */ class WC_Cart { + /** + * This stores the chosen shipping methods for the cart item packages. + * @var array + */ + protected $shipping_methods; + /** @var array Contains an array of cart items. */ public $cart_contents = array(); @@ -295,6 +301,7 @@ class WC_Cart { */ public function empty_cart( $clear_persistent_cart = true ) { $this->cart_contents = array(); + $this->shipping_methods = null; $this->reset( true ); unset( WC()->session->order_awaiting_payment, WC()->session->applied_coupons, WC()->session->coupon_discount_amounts, WC()->session->coupon_discount_tax_amounts, WC()->session->cart ); @@ -1452,15 +1459,32 @@ class WC_Cart { * Uses the shipping class to calculate shipping then gets the totals when its finished. */ public function calculate_shipping() { - if ( $this->needs_shipping() && $this->show_shipping() ) { - WC()->shipping->calculate_shipping( $this->get_shipping_packages() ); - } else { - WC()->shipping->reset_shipping(); - } + $this->shipping_methods = $this->needs_shipping() ? $this->get_chosen_shipping_methods( WC()->shipping->calculate_shipping( $this->get_shipping_packages() ) ) : array(); - // Get totals for the chosen shipping method - $this->shipping_total = WC()->shipping->shipping_total; // Shipping Total - $this->shipping_taxes = WC()->shipping->shipping_taxes; // Shipping Taxes + // Set legacy totals for backwards compatibility with versions prior to 3.2. + $this->shipping_total = WC()->shipping->shipping_total = array_sum( wp_list_pluck( $this->shipping_methods, 'cost' ) ); + $this->shipping_taxes = WC()->shipping->shipping_taxes = wp_list_pluck( $this->shipping_methods, 'taxes' ); + + return $this->shipping_methods; + } + + /** + * Given a set of packages with rates, get the chosen ones only. + * + * @since 3.2.0 + * @param array $calculated_shipping_packages + * @return array + */ + protected function get_chosen_shipping_methods( $calculated_shipping_packages = array() ) { + $chosen_methods = array(); + // Get chosen methods for each package to get our totals. + foreach ( $calculated_shipping_packages as $key => $package ) { + $chosen_method = wc_get_chosen_shipping_method_for_package( $key, $package ); + if ( $chosen_method ) { + $chosen_methods[ $key ] = $package['rates'][ $chosen_method ]; + } + } + return $chosen_methods; } /** diff --git a/includes/class-wc-discounts.php b/includes/class-wc-discounts.php index da074123b4e..9df5bf1f7ae 100644 --- a/includes/class-wc-discounts.php +++ b/includes/class-wc-discounts.php @@ -45,9 +45,12 @@ class WC_Discounts { /** * Constructor. + * + * @param array $items Items to discount. */ - public function __construct() { + public function __construct( $items = array() ) { $this->precision = pow( 10, wc_get_price_decimals() ); + $this->set_items( $items ); } /** @@ -64,6 +67,7 @@ class WC_Discounts { * Get discount by key without precision. * * @since 3.2.0 + * @param string $key name of discount row to return. * @return array */ public function get_discount( $key ) { @@ -71,20 +75,21 @@ class WC_Discounts { } /** - * Get all discount totals without precision. + * Get all discount totals with precision. * * @since 3.2.0 + * @param bool $in_cents Should the totals be returned in cents, or without precision. * @return array */ - public function get_discounts() { - return array_map( array( $this, 'remove_precision' ), $this->discounts ); + public function get_discounts( $in_cents = false ) { + return $in_cents ? $this->discounts : array_map( array( $this, 'remove_precision' ), $this->discounts ); } /** * Get discounted price of an item without precision. * * @since 3.2.0 - * @param object $item + * @param object $item Get data for this item. * @return float */ public function get_discounted_price( $item ) { @@ -95,7 +100,7 @@ class WC_Discounts { * Get discounted price of an item to precision (in cents). * * @since 3.2.0 - * @param object $item + * @param object $item Get data for this item. * @return float */ public function get_discounted_price_in_cents( $item ) { @@ -117,42 +122,19 @@ class WC_Discounts { * Set cart/order items which will be discounted. * * @since 3.2.0 - * @param array $raw_items List of raw cart or order items. + * @param array $items List items, normailised, by WC_Totals. */ - public function set_items( $raw_items ) { + public function set_items( $items ) { $this->items = array(); $this->discounts = array(); $this->applied_coupons = array(); - if ( ! empty( $raw_items ) && is_array( $raw_items ) ) { - foreach ( $raw_items as $raw_item ) { - $item = (object) array( - 'price' => 0, // Line price without discounts, in cents. - 'quantity' => 0, // Line qty. - 'product' => false, - ); - if ( is_a( $raw_item, 'WC_Cart_Item' ) ) { - // $item->quantity = $raw_item->get_quantity(); - // $item->price = $raw_item->get_price() * $raw_item->get_quantity(); - // $item->is_taxable = $raw_item->is_taxable(); - // $item->tax_class = $raw_item->get_tax_class(); - // @todo - } elseif ( is_a( $raw_item, 'WC_Order_Item_Product' ) ) { - $item->key = $raw_item->get_id(); - $item->quantity = $raw_item->get_quantity(); - $item->price = $raw_item->get_subtotal() * $this->precision; - $item->product = $raw_item->get_product(); - } else { - $item->key = $raw_item['key']; - $item->quantity = $raw_item['quantity']; - $item->price = $raw_item['data']->get_price() * $this->precision * $raw_item['quantity']; - $item->product = $raw_item['data']; - } - $this->items[ $item->key ] = $item; - $this->discounts[ $item->key ] = 0; - } - uasort( $this->items, array( $this, 'sort_by_price' ) ); + if ( ! empty( $items ) && is_array( $items ) ) { + $this->items = $items; + $this->discounts = array_fill_keys( array_keys( $items ), 0 ); } + + uasort( $this->items, array( $this, 'sort_by_price' ) ); } /** @@ -161,7 +143,7 @@ class WC_Discounts { * @todo Coupon class has lots of WC()->cart calls and needs decoupling. This makes 'is valid' hard to use here. * * @since 3.2.0 - * @param WC_Coupon $coupon + * @param WC_Coupon $coupon Coupon object being applied to the items. * @return bool|WP_Error True if applied or WP_Error instance in failure. */ public function apply_coupon( $coupon ) { @@ -195,20 +177,46 @@ class WC_Discounts { } /** - * Remove precision from a price. + * Add precision (deep) to a price. * - * @param int $value + * @since 3.2.0 + * @param int|array $value Value to remove precision from. + * @return float + */ + protected function add_precision( $value ) { + if ( is_array( $value ) ) { + foreach ( $value as $key => $subvalue ) { + $value[ $key ] = $this->add_precision( $subvalue ); + } + } else { + $value = $value * $this->precision; + } + return $value; + } + + /** + * Remove precision (deep) from a price. + * + * @since 3.2.0 + * @param int|array $value Value to remove precision from. * @return float */ protected function remove_precision( $value ) { - return wc_format_decimal( $value / $this->precision, wc_get_price_decimals() ); + if ( is_array( $value ) ) { + foreach ( $value as $key => $subvalue ) { + $value[ $key ] = $this->remove_precision( $subvalue ); + } + } else { + $value = wc_format_decimal( $value / $this->precision, wc_get_price_decimals() ); + } + return $value; } /** * Sort by price. * - * @param array $a - * @param array $b + * @param array $a First element. + * @param array $b Second element. * @return int */ protected function sort_by_price( $a, $b ) { @@ -224,7 +232,7 @@ class WC_Discounts { * Filter out all products which have been fully discounted to 0. * Used as array_filter callback. * - * @param object $item + * @param object $item Get data for this item. * @return bool */ protected function filter_products_with_price( $item ) { @@ -234,7 +242,7 @@ class WC_Discounts { /** * Get items which the coupon should be applied to. * - * @param object $coupon + * @param object $coupon Coupon object. * @return array */ protected function get_items_to_apply_coupon( $coupon ) { @@ -276,9 +284,9 @@ class WC_Discounts { * Apply a discount amount to an item and ensure it does not go negative. * * @since 3.2.0 - * @param object $item - * @param int $discount - * @return int Amount discounted. + * @param object $item Get data for this item. + * @param int $discount Amount of discount. + * @return int Amount discounted. */ protected function add_item_discount( &$item, $discount ) { $discounted_price = $this->get_discounted_price_in_cents( $item ); @@ -291,9 +299,9 @@ class WC_Discounts { * Apply percent discount to items. * * @since 3.2.0 - * @param array $items_to_apply Array of items to apply the coupon to. - * @param int $amount - * @return int total discounted in cents + * @param array $items_to_apply Array of items to apply the coupon to. + * @param int $amount Amount of discount. + * @return int total discounted in cents */ protected function apply_percentage_discount( $items_to_apply, $amount ) { $total_discounted = 0; @@ -310,7 +318,7 @@ class WC_Discounts { * * @since 3.2.0 * @param array $items_to_apply Array of items to apply the coupon to. - * @param int $amount + * @param int $discount Amount of discout. * @return int total discounted in cents */ protected function apply_fixed_product_discount( $items_to_apply, $discount ) { @@ -328,7 +336,7 @@ class WC_Discounts { * * @since 3.2.0 * @param array $items_to_apply Array of items to apply the coupon to. - * @param int $cart_discount + * @param int $cart_discount Fixed discount amount to apply. * @return int total discounted in cents */ protected function apply_fixed_cart_discount( $items_to_apply, $cart_discount ) { @@ -352,12 +360,11 @@ class WC_Discounts { if ( $amount_discounted > 0 && $amount_discounted < $cart_discount ) { $amount_discounted += $this->apply_fixed_cart_discount( $items_to_apply, $cart_discount - $amount_discounted ); } - - /** - * Deal with remaining fractional discounts by splitting it over items - * until the amount is expired, discounting 1 cent at a time. - */ } elseif ( $cart_discount > 0 ) { + /** + * Deal with remaining fractional discounts by splitting it over items + * until the amount is expired, discounting 1 cent at a time. + */ foreach ( $items_to_apply as $item ) { for ( $i = 0; $i < $item->quantity; $i ++ ) { $amount_discounted += $this->add_item_discount( $item, 1 ); diff --git a/includes/class-wc-shipping.php b/includes/class-wc-shipping.php index 0a1e931f8a2..ece466afd5e 100644 --- a/includes/class-wc-shipping.php +++ b/includes/class-wc-shipping.php @@ -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(); } diff --git a/includes/class-wc-totals.php b/includes/class-wc-totals.php new file mode 100644 index 00000000000..f79a176e2a2 --- /dev/null +++ b/includes/class-wc-totals.php @@ -0,0 +1,523 @@ + 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 or order object to calculate totals for. + */ + public function __construct( &$cart = null ) { + $this->precision = pow( 10, wc_get_price_decimals() ); + $this->object = $cart; + $this->set_items(); + $this->calculate(); + } + + /** + * Handles a cart or order object passed in for calculation. Normalises data + * into the same format for use by this class. + * + * @since 3.2.0 + */ + private function set_items() { + if ( is_a( $this->object, 'WC_Cart' ) ) { + foreach ( $this->object->get_cart() as $cart_item_key => $cart_item ) { + $item = $this->get_default_item_props(); + $item->key = $cart_item_key; + $item->quantity = $cart_item['quantity']; + $item->price = $this->add_precision( $cart_item['data']->get_price() ) * $cart_item['quantity']; + $item->product = $cart_item['data']; + $this->items[ $cart_item_key ] = $item; + } + } + } + + /** + * Add precision (deep) to a price. + * + * @since 3.2.0 + * @param int|array $value Value to remove precision from. + * @return float + */ + private function add_precision( $value ) { + if ( is_array( $value ) ) { + foreach ( $value as $key => $subvalue ) { + $value[ $key ] = $this->add_precision( $subvalue ); + } + } else { + $value = $value * $this->precision; + } + return $value; + } + + /** + * Remove precision (deep) from a price. + * + * @since 3.2.0 + * @param int|array $value Value to remove precision from. + * @return float + */ + private function remove_precision( $value ) { + if ( is_array( $value ) ) { + foreach ( $value as $key => $subvalue ) { + $value[ $key ] = $this->remove_precision( $subvalue ); + } + } else { + $value = wc_format_decimal( $value / $this->precision, wc_get_price_decimals() ); + } + return $value; + } + + /** + * Get default blank set of props used per item. + * + * @since 3.2.0 + * @return array + */ + private function get_default_item_props() { + return (object) array( + 'key' => '', + 'quantity' => 0, + 'price' => 0, + 'product' => false, + 'price_includes_tax' => wc_prices_include_tax(), + 'subtotal' => 0, + 'subtotal_tax' => 0, + 'subtotal_taxes' => array(), + 'total' => 0, + 'total_tax' => 0, + 'taxes' => array(), + 'discounted_price' => 0, + ); + } + + /** + * Get default blank set of props used per fee. + * + * @since 3.2.0 + * @return array + */ + private 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 + */ + private function get_default_shipping_props() { + return (object) array( + 'total' => 0, + 'total_tax' => 0, + 'taxes' => array(), + ); + } + + /** + * 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. + * + * @since 3.2.0 + * @param object $item Item to adjust the prices of. + * @return object + */ + private function adjust_non_base_location_price( $item ) { + $base_tax_rates = WC_Tax::get_base_tax_rates( $item->product->tax_class ); + $item_tax_rates = $this->get_item_tax_rates( $item ); + + 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->price, $base_tax_rates, true, true ); + + // Now we have a new item price (excluding TAX). + $item->price = $item->price - 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 Item to get the price of. + * @return int + */ + private function get_discounted_price_in_cents( $item ) { + return $item->price - $this->discount_totals[ $item->key ]; + } + + /** + * 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 + */ + private 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() ); + } + + /** + * Return array of coupon objects from the cart or an order. + * + * @since 3.2.0 + * @return array + */ + private function get_coupons() { + if ( is_a( $this->object, 'WC_Cart' ) ) { + return $this->object->get_coupons(); + } + } + + /** + * 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. + */ + private 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 : array_map( array( $this, 'remove_precision' ), $this->totals ); + } + + /** + * Get all tax rows from items (including shipping and product line items). + * + * @since 3.2.0 + * @return array + */ + private 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. + |-------------------------------------------------------------------------- + */ + + /** + * Run all calculations methods on the given items in sequence. + * + * @since 3.2.0 + */ + private function calculate() { + $this->calculate_item_subtotals(); + $this->calculate_discounts(); + $this->calculate_item_totals(); + $this->calculate_fee_totals(); + $this->calculate_shipping_totals(); + $this->calculate_totals(); + } + + /** + * 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 + */ + private function calculate_item_subtotals() { + foreach ( $this->items as $item ) { + if ( $item->price_includes_tax && apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ) { + $item = $this->adjust_non_base_location_price( $item ); + } + + $item->subtotal = $item->price; + $item->subtotal_tax = 0; + + if ( wc_tax_enabled() && $item->product->is_taxable() ) { + $item->subtotal_taxes = WC_Tax::calc_tax( $item->subtotal, $this->get_item_tax_rates( $item ), $item->price_includes_tax ); + $item->subtotal_tax = array_sum( $item->subtotal_taxes ); + + if ( $item->price_includes_tax ) { + $item->subtotal = $item->subtotal - $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' ) ) ) ); + } + + /** + * Calculate all discount and coupon amounts. + * + * @todo Manual discounts. + * @todo record coupon totals and counts for cart. + * + * @since 3.2.0 + * @uses WC_Discounts class. + */ + private function calculate_discounts() { + $discounts = new WC_Discounts( $this->items ); + + foreach ( $this->get_coupons() as $coupon ) { + $discounts->apply_coupon( $coupon ); + } + + $this->discount_totals = $discounts->get_discounts( true ); + $this->totals['discounts_total'] = array_sum( $this->discount_totals ); + + // See how much tax was 'discounted'. + if ( wc_tax_enabled() ) { + foreach ( $this->discount_totals as $cart_item_key => $discount ) { + $item = $this->items[ $cart_item_key ]; + if ( $item->product->is_taxable() ) { + $tax_rates = $this->get_item_tax_rates( $item ); + $taxes = WC_Tax::calc_tax( $discount, $tax_rates, false ); + $this->totals['discounts_tax_total'] += array_sum( $taxes ); + } + } + } + } + + /** + * Totals are costs after discounts. @todo move cart specific setters to subclass? + * + * @since 3.2.0 + */ + private function calculate_item_totals() { + foreach ( $this->items as $item ) { + $item->total = $this->get_discounted_price_in_cents( $item ); + $item->total_tax = 0; + + if ( wc_tax_enabled() && $item->product->is_taxable() ) { + $item->taxes = WC_Tax::calc_tax( $item->total, $this->get_item_tax_rates( $item ), $item->price_includes_tax ); + $item->total_tax = array_sum( $item->taxes ); + + if ( $item->price_includes_tax ) { + $item->total = $item->total - $item->total_tax; + } else { + $item->total = $item->total; + } + } + } + $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' ) ) ) ); + + $this->object->subtotal = array_sum( wp_list_pluck( $this->items, 'total' ) ) + array_sum( wp_list_pluck( $this->items, 'total_tax' ) ); + $this->object->subtotal_ex_tax = array_sum( wp_list_pluck( $this->items, 'total' ) ); + } + + /** + * 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 + * @todo logic is unqiue to carts. + */ + private function calculate_fee_totals() { + $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 = $this->add_precision( $fee->object->amount ); + + if ( wc_tax_enabled() && $fee->object->taxable ) { + $fee->taxes = WC_Tax::calc_tax( $fee->total, WC_Tax::get_rates( $fee->object->tax_class ), false ); + $fee->total_tax = array_sum( $fee->taxes ); + } + + $this->fees[ $fee_key ] = $fee; + } + + // Store totals to self. + $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' ) ) ); + + // Transfer totals to the cart. + foreach ( $this->fees as $fee_key => $fee ) { + $this->object->fees[ $fee_key ]->tax = $this->remove_precision( $fee->total_tax ); + $this->object->fees[ $fee_key ]->tax_data = $this->remove_precision( $fee->taxes ); + } + $this->object->fee_total = $this->remove_precision( array_sum( wp_list_pluck( $this->fees, 'total' ) ) ); + } + + /** + * Calculate any shipping taxes. + * + * @since 3.2.0 + */ + private function calculate_shipping_totals() { + $this->shipping = array(); + + foreach ( $this->object->calculate_shipping() as $key => $shipping_object ) { + $shipping_line = $this->get_default_shipping_props(); + $shipping_line->total = $this->add_precision( $shipping_object->cost ); + $shipping_line->taxes = array_map( array( $this, 'add_precision' ), $shipping_object->taxes ); + $shipping_line->total_tax = array_sum( $shipping_object->taxes ); + $this->shipping[ $key ] = $shipping_line; + } + + $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' ) ) ); + } + + /** + * Main cart totals. + * + * @since 3.2.0 + */ + private 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( 'shipping_tax_total', array_sum( wp_list_pluck( $this->get_total( 'taxes', true ), 'shipping_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 ) ) ); + } +} diff --git a/includes/class-woocommerce.php b/includes/class-woocommerce.php index 58876dd9f54..3667641f93e 100644 --- a/includes/class-woocommerce.php +++ b/includes/class-woocommerce.php @@ -334,6 +334,7 @@ final class WooCommerce { 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-totals.php' ); /** * Data stores - used to store and retrieve CRUD object data from the database. diff --git a/includes/wc-cart-functions.php b/includes/wc-cart-functions.php index 2f69aa152b9..386424062ff 100644 --- a/includes/wc-cart-functions.php +++ b/includes/wc-cart-functions.php @@ -388,3 +388,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; +} diff --git a/tests/unit-tests/discounts/discounts.php b/tests/unit-tests/discounts/discounts.php index 49238d92c31..455c265a473 100644 --- a/tests/unit-tests/discounts/discounts.php +++ b/tests/unit-tests/discounts/discounts.php @@ -6,6 +6,33 @@ */ class WC_Tests_Discounts extends WC_Unit_Test_Case { + protected function get_items_for_discounts_class() { + $items = array(); + $precision = pow( 10, wc_get_price_decimals() ); + foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { + $item = (object) array( + 'key' => '', + 'quantity' => 0, + 'price' => 0, + 'product' => false, + 'price_includes_tax' => wc_prices_include_tax(), + 'subtotal' => 0, + 'subtotal_tax' => 0, + 'subtotal_taxes' => array(), + 'total' => 0, + 'total_tax' => 0, + 'taxes' => array(), + 'discounted_price' => 0, + ); + $item->key = $cart_item_key; + $item->quantity = $cart_item['quantity']; + $item->price = $cart_item['data']->get_price() * $precision * $cart_item['quantity']; + $item->product = $cart_item['data']; + $items[ $cart_item_key ] = $item; + } + return $items; + } + /** * Test get and set items. */ @@ -24,12 +51,12 @@ class WC_Tests_Discounts extends WC_Unit_Test_Case { // Test setting items to the cart. $discounts = new WC_Discounts(); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $this->assertEquals( 1, count( $discounts->get_items() ) ); // Test setting items to an order. $discounts = new WC_Discounts(); - $discounts->set_items( $order->get_items() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $this->assertEquals( 1, count( $discounts->get_items() ) ); // Empty array of items. @@ -55,7 +82,7 @@ class WC_Tests_Discounts extends WC_Unit_Test_Case { $discounts = new WC_Discounts(); $product = WC_Helper_Product::create_simple_product(); WC()->cart->add_to_cart( $product->get_id(), 1 ); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); // Test applying multiple coupons and getting totals. $coupon = WC_Helper_Coupon::create_coupon( 'test' ); @@ -81,12 +108,12 @@ class WC_Tests_Discounts extends WC_Unit_Test_Case { WC()->cart->add_to_cart( $product->get_id(), 2 ); $coupon->set_discount_type( 'fixed_product' ); $coupon->set_amount( 2 ); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $discounts->apply_coupon( $coupon ); $this->assertEquals( array( 'test' => 4 ), $discounts->get_applied_coupons() ); $coupon->set_discount_type( 'fixed_cart' ); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $discounts->apply_coupon( $coupon ); $this->assertEquals( array( 'test' => 2 ), $discounts->get_applied_coupons() ); @@ -114,19 +141,19 @@ class WC_Tests_Discounts extends WC_Unit_Test_Case { // Apply a percent discount. $coupon->set_discount_type( 'percent' ); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $discounts->apply_coupon( $coupon ); $this->assertEquals( 9, $discounts->get_discounted_price( current( $discounts->get_items() ) ) ); // Apply a fixed cart coupon. $coupon->set_discount_type( 'fixed_cart' ); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $discounts->apply_coupon( $coupon ); $this->assertEquals( 0, $discounts->get_discounted_price( current( $discounts->get_items() ) ) ); // Apply a fixed product coupon. $coupon->set_discount_type( 'fixed_product' ); - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); $discounts->apply_coupon( $coupon ); $this->assertEquals( 0, $discounts->get_discounted_price( current( $discounts->get_items() ) ) ); @@ -399,7 +426,7 @@ class WC_Tests_Discounts extends WC_Unit_Test_Case { $products[] = $product; } - $discounts->set_items( WC()->cart->get_cart() ); + $discounts->set_items( $this->get_items_for_discounts_class() ); foreach ( $test['coupons'] as $coupon_props ) { $coupon->set_props( $coupon_props ); diff --git a/tests/unit-tests/totals/totals.php b/tests/unit-tests/totals/totals.php new file mode 100644 index 00000000000..5789315110f --- /dev/null +++ b/tests/unit-tests/totals/totals.php @@ -0,0 +1,128 @@ + '', + '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' ); + + $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_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 ); + } + + foreach ( $this->ids['tax_rate_ids'] as $tax_rate_id ) { + WC_Tax::_delete_tax_rate( $tax_rate_id ); + } + } + + /** + * 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() ); + } +}