WC_Abstract_Order::set_coupon_discount_amounts()protectedWC 3.2.0

After applying coupons via the WC_Discounts class, update or create coupon items.

Метод класса: WC_Abstract_Order{}

Хуков нет.

Возвращает

null. Ничего (null).

Использование

// protected - в коде основоного (родительского) или дочернего класса
$result = $this->set_coupon_discount_amounts( $discounts );
$discounts(WC_Discounts) (обязательный)
Discounts class.

Список изменений

С версии 3.2.0 Введена.

Код WC_Abstract_Order::set_coupon_discount_amounts() WC 8.7.0

protected function set_coupon_discount_amounts( $discounts ) {
	$coupons           = $this->get_items( 'coupon' );
	$coupon_code_to_id = wc_list_pluck( $coupons, 'get_id', 'get_code' );
	$all_discounts     = $discounts->get_discounts();
	$coupon_discounts  = $discounts->get_discounts_by_coupon();
	$tax_location      = $this->get_tax_location();
	$tax_location      = array(
		$tax_location['country'],
		$tax_location['state'],
		$tax_location['postcode'],
		$tax_location['city'],
	);

	if ( $coupon_discounts ) {
		foreach ( $coupon_discounts as $coupon_code => $amount ) {
			$item_id = isset( $coupon_code_to_id[ $coupon_code ] ) ? $coupon_code_to_id[ $coupon_code ] : 0;

			if ( ! $item_id ) {
				$coupon_item = new WC_Order_Item_Coupon();
				$coupon_item->set_code( $coupon_code );

				// Add coupon data.
				$coupon_id = wc_get_coupon_id_by_code( $coupon_code );
				$coupon    = new WC_Coupon( $coupon_id );

				$coupon_info = $coupon->get_short_info();
				$coupon_item->add_meta_data( 'coupon_info', $coupon_info );
			} else {
				$coupon_item = $this->get_item( $item_id, false );
			}

			$discount_tax = 0;

			// Work out how much tax has been removed as a result of the discount from this coupon.
			foreach ( $all_discounts[ $coupon_code ] as $item_id => $item_discount_amount ) {
				$item = $this->get_item( $item_id, false );

				if ( 'taxable' !== $item->get_tax_status() || ! wc_tax_enabled() ) {
					continue;
				}

				$taxes = array_sum( WC_Tax::calc_tax( $item_discount_amount, $this->get_tax_rates( $item->get_tax_class(), $tax_location ), $this->get_prices_include_tax() ) );
				if ( 'yes' !== get_option( 'woocommerce_tax_round_at_subtotal' ) ) {
					$taxes = wc_round_tax_total( $taxes );
				}

				$discount_tax += $taxes;

				if ( $this->get_prices_include_tax() ) {
					$amount = $amount - $taxes;
				}
			}

			$coupon_item->set_discount( $amount );
			$coupon_item->set_discount_tax( $discount_tax );

			$this->add_item( $coupon_item );
		}
	}
}