Do not send negative price items, add to discount

This commit is contained in:
Alex P 2022-05-10 18:09:48 +03:00
parent c3887bec7a
commit 88220aa3c6
3 changed files with 141 additions and 35 deletions

View file

@ -124,6 +124,27 @@ class AmountFactory {
$currency = $order->get_currency();
$items = $this->item_factory->from_wc_order( $order );
$discount_value = array_sum(
array(
(float) $order->get_total_discount( false ), // Only coupons.
$this->discounts_from_items( $items ),
)
);
$discount = null;
if ( $discount_value ) {
$discount = new Money(
(float) $discount_value,
$currency
);
}
$items = array_filter(
$items,
function ( Item $item ): bool {
return $item->unit_amount()->value() > 0;
}
);
$total_value = (float) $order->get_total();
if ( (
CreditCardGateway::ID === $order->get_payment_method()
@ -160,14 +181,6 @@ class AmountFactory {
$currency
);
$discount = null;
if ( (float) $order->get_total_discount( false ) ) {
$discount = new Money(
(float) $order->get_total_discount( false ),
$currency
);
}
$breakdown = new AmountBreakdown(
$item_total,
$shipping,
@ -251,4 +264,29 @@ class AmountFactory {
return new AmountBreakdown( ...$money );
}
/**
* Returns the sum of items with negative amount;
*
* @param Item[] $items PayPal order items.
* @return float
*/
private function discounts_from_items( array $items ): float {
$discounts = array_filter(
$items,
function ( Item $item ): bool {
return $item->unit_amount()->value() < 0;
}
);
return abs(
array_sum(
array_map(
function ( Item $item ): float {
return (float) $item->quantity() * $item->unit_amount()->value();
},
$discounts
)
)
);
}
}

View file

@ -107,7 +107,12 @@ class PurchaseUnitFactory {
*/
public function from_wc_order( \WC_Order $order ): PurchaseUnit {
$amount = $this->amount_factory->from_wc_order( $order );
$items = $this->item_factory->from_wc_order( $order );
$items = array_filter(
$this->item_factory->from_wc_order( $order ),
function ( Item $item ): bool {
return $item->unit_amount()->value() > 0;
}
);
$shipping = $this->shipping_factory->from_wc_order( $order );
if (
! $this->shipping_needed( ... array_values( $items ) ) ||
@ -153,7 +158,12 @@ class PurchaseUnitFactory {
*/
public function from_wc_cart( \WC_Cart $cart ): PurchaseUnit {
$amount = $this->amount_factory->from_wc_cart( $cart );
$items = $this->item_factory->from_wc_cart( $cart );
$items = array_filter(
$this->item_factory->from_wc_cart( $cart ),
function ( Item $item ): bool {
return $item->unit_amount()->value() > 0;
}
);
$shipping = null;
$customer = \WC()->customer;