Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add base shipping price to order (#10771)

Filip Owczarekb659fc29459f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e865c343b..55cdb9ba6f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,8 @@ All notable, unreleased changes to this project will be documented in this file.
### Other changes
- Reference attribute linking to product variants - #10468 by @IKarbowiak
+- Add base shipping price to `Order` - #10771 by @fowczarek
+
### GraphQL API
- Add `taxExemptionManage` mutation - #10344 by @SzymJ
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index e1a381a420..a112eb988f 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -124,16 +124,42 @@ def base_checkout_delivery_price(
lines: Iterable["CheckoutLineInfo"] = None,
) -> Money:
"""Calculate base (untaxed) price for any kind of delivery method."""
+ currency = checkout_info.checkout.currency
+
+ shipping_price = base_checkout_undiscounted_delivery_price(checkout_info, lines)
+
+ is_shipping_voucher = (
+ checkout_info.voucher.type == VoucherType.SHIPPING
+ if checkout_info.voucher
+ else False
+ )
+
+ if is_shipping_voucher:
+ discount = checkout_info.checkout.discount
+ shipping_price = max(zero_money(currency), shipping_price - discount)
+
+ return quantize_price(
+ shipping_price,
+ currency,
+ )
+
+
+def base_checkout_undiscounted_delivery_price(
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"] = None,
+) -> Money:
+ """Calculate base (untaxed) undiscounted price for any kind of delivery method."""
from .fetch import ShippingMethodInfo
delivery_method_info = checkout_info.delivery_method_info
+ currency = checkout_info.checkout.currency
- if isinstance(delivery_method_info, ShippingMethodInfo):
- return calculate_base_price_for_shipping_method(
- checkout_info, delivery_method_info, lines
- )
+ if not isinstance(delivery_method_info, ShippingMethodInfo):
+ return zero_money(currency)
- return zero_money(checkout_info.checkout.currency)
+ return calculate_base_price_for_shipping_method(
+ checkout_info, delivery_method_info, lines
+ )
def calculate_base_price_for_shipping_method(
@@ -144,7 +170,6 @@ def calculate_base_price_for_shipping_method(
"""Return checkout shipping price."""
from .fetch import CheckoutLineInfo
- # FIXME: Optimize checkout.is_shipping_required
shipping_method = shipping_method_info.delivery_method
if lines is not None and all(isinstance(line, CheckoutLineInfo) for line in lines):
@@ -190,9 +215,7 @@ def base_checkout_total(
)
# Discount is subtracted from both gross and net values, which may cause negative
# net value if we are having a discount that covers whole price.
- if is_shipping_voucher:
- shipping_price = max(zero_money(currency), shipping_price - discount)
- else:
+ if not is_shipping_voucher:
subtotal = max(zero_money(currency), subtotal - discount)
return subtotal + shipping_price
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 142f76882d..b1aa24062b 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -54,6 +54,7 @@ from ..warehouse.management import allocate_preorders, allocate_stocks
from ..warehouse.reservations import is_reservation_enabled
from . import AddressType
from .base_calculations import (
+ base_checkout_delivery_price,
calculate_base_line_unit_price,
calculate_undiscounted_base_line_total_price,
calculate_undiscounted_base_line_unit_price,
@@ -68,7 +69,6 @@ from .fetch import CheckoutInfo, CheckoutLineInfo
from .utils import get_voucher_for_checkout_info
if TYPE_CHECKING:
- from ..account.models import Address
from ..app.models import App
from ..discount.models import Voucher
from ..plugins.manager import PluginsManager
@@ -106,6 +106,7 @@ def _process_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:
def _process_shipping_data_for_order(
checkout_info: "CheckoutInfo",
+ base_shipping_price: Money,
shipping_price: TaxedMoney,
manager: "PluginsManager",
lines: Iterable["CheckoutLineInfo"],
@@ -127,6 +128,7 @@ def _process_shipping_data_for_order(
result: Dict[str, Any] = {
"shipping_address": shipping_address,
+ "base_shipping_price": base_shipping_price,
"shipping_price": shipping_price,
"weight": checkout_info.checkout.get_total_weight(lines),
}
@@ -397,6 +399,7 @@ def _prepare_order_data(
)
undiscounted_total = taxed_total + checkout.discount
+ base_shipping_price = base_checkout_delivery_price(checkout_info, lines)
shipping_total = calculations.checkout_shipping_price(
manager=manager,
checkout_info=checkout_info,
@@ -412,7 +415,9 @@ def _prepare_order_data(
discounts=discounts,
)
order_data.update(
- _process_shipping_data_for_order(checkout_info, shipping_total, manager, lines)
+ _process_shipping_data_for_order(
+ checkout_info, base_shipping_price, shipping_total, manager, lines
+ )
)
order_data.update(_process_user_data_for_order(checkout_info, manager))
order_data.update(
@@ -860,28 +865,6 @@ def _is_refund_ongoing(payment):
)
-def _get_order_total(
- checkout_info: CheckoutInfo,
- lines: List[CheckoutLineInfo],
- discounts: List["DiscountInfo"],
- manager: "PluginsManager",
- address: Optional["Address"],
-) -> TaxedMoney:
- """Calculate a taxed total for order."""
- taxed_total = calculations.checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- discounts=discounts,
- )
- cards_total = checkout_info.checkout.get_total_gift_cards_balance()
- taxed_total.gross -= cards_total
- taxed_total.net -= cards_total
- taxed_total = max(taxed_total, zero_taxed_money(checkout_info.checkout.currency))
- return taxed_total
-
-
def _increase_voucher_usage(checkout_info: "CheckoutInfo"):
"""Increase a voucher usage applied to the checkout."""
voucher = get_voucher_for_checkout_info(checkout_info, with_lock=True)
@@ -1034,12 +1017,12 @@ def _create_order_from_checkout(
taxes_included_in_prices = site_settings.include_taxes_in_prices
# total
- taxed_total = _get_order_total(
- checkout_info,
- checkout_lines_info,
- discounts,
- manager,
- address,
+ taxed_total = calculations.calculate_checkout_total_with_gift_cards(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=checkout_lines_info,
+ address=address,
+ discounts=discounts,
)
undiscounted_total = taxed_total + checkout_info.checkout.discount
@@ -1047,11 +1030,22 @@ def _create_order_from_checkout(
voucher = checkout_info.voucher
# shipping
- shipping_total = manager.calculate_checkout_shipping(
- checkout_info, checkout_lines_info, address, discounts
+ base_shipping_price = base_checkout_delivery_price(
+ checkout_info, checkout_lines_info
+ )
+ shipping_total = calculations.checkout_shipping_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=checkout_lines_info,
+ address=address,
+ discounts=discounts,
)
- shipping_tax_rate = manager.get_checkout_shipping_tax_rate(
- checkout_info, checkout_lines_info, address, discounts, shipping_total
+ shipping_tax_rate = calculations.checkout_shipping_tax_rate(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=checkout_lines_info,
+ address=address,
+ discounts=discounts,
)
# status
@@ -1089,7 +1083,11 @@ def _create_order_from_checkout(
should_refresh_prices=False,
tax_exemption=checkout_info.checkout.tax_exemption,
**_process_shipping_data_for_order(
- checkout_info, shipping_total, manager, checkout_lines_info
+ checkout_info,
+ base_shipping_price,
+ shipping_total,
+ manager,
+ checkout_lines_info,
),
**_process_user_data_for_order(checkout_info, manager),
)
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 4cde534962..ccd1e28fba 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -970,12 +970,11 @@ def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, vo
def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping(
- checkout_with_voucher_percentage_and_shipping,
- voucher_free_shipping,
+ checkout_with_voucher_free_shipping,
shipping_method,
channel_USD,
):
- checkout = checkout_with_voucher_percentage_and_shipping
+ checkout = checkout_with_voucher_free_shipping
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
@@ -987,15 +986,10 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping
address=checkout.shipping_address,
).gross + Money("10.00", "USD")
channel_listing.save()
- checkout.price_expiration = timezone.now()
- checkout.save()
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
recalculate_checkout_discount(manager, checkout_info, lines, None)
- checkout.price_expiration = timezone.now()
- checkout.save()
-
assert checkout.discount == channel_listing.price
assert checkout.discount_name == "Free shipping"
checkout_total = calculations.checkout_total(
@@ -1014,12 +1008,11 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping
def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shipping(
- checkout_with_voucher_percentage_and_shipping,
- voucher_free_shipping,
+ checkout_with_voucher_free_shipping,
shipping_method,
channel_USD,
):
- checkout = checkout_with_voucher_percentage_and_shipping
+ checkout = checkout_with_voucher_free_shipping
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
@@ -1031,13 +1024,9 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shippi
address=checkout.shipping_address,
).gross - Money("1.00", "USD")
channel_listing.save()
- checkout.price_expiration = timezone.now()
- checkout.save()
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
recalculate_checkout_discount(manager, checkout_info, lines, None)
- checkout.price_expiration = timezone.now()
- checkout.save()
assert checkout.discount == channel_listing.price
assert checkout.discount_name == "Free shipping"
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 2794f48d8f..d8d60f7c48 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -1,8 +1,10 @@
+from decimal import Decimal
from unittest import mock
import pytest
from django.contrib.auth.models import AnonymousUser
from django.test import override_settings
+from prices import TaxedMoney
from ...account import CustomerEvents
from ...account.models import CustomerEvent
@@ -1417,9 +1419,12 @@ def test_process_shipping_data_for_order_store_customer_shipping_address(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
shipping_price = zero_taxed_money(checkout.currency)
+ base_shipping_price = zero_money(checkout.currency)
# when
- _ = _process_shipping_data_for_order(checkout_info, shipping_price, manager, lines)
+ _ = _process_shipping_data_for_order(
+ checkout_info, base_shipping_price, shipping_price, manager, lines
+ )
# then
new_user_address_count = customer_user.addresses.count()
@@ -1449,12 +1454,120 @@ def test_process_shipping_data_for_order_dont_store_customer_click_and_collect_a
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
shipping_price = zero_taxed_money(checkout.currency)
+ base_shipping_price = zero_money(checkout.currency)
# when
- _ = _process_shipping_data_for_order(checkout_info, shipping_price, manager, lines)
+ _ = _process_shipping_data_for_order(
+ checkout_info, base_shipping_price, shipping_price, manager, lines
+ )
# then
new_user_address_count = customer_user.addresses.count()
new_address_data = warehouse_for_cc.address.as_data()
assert new_user_address_count == user_address_count
assert not customer_user.addresses.filter(**new_address_data).exists()
+
+
+def test_create_order_store_shipping_prices(
+ checkout_with_items_and_shipping, shipping_method, customer_user
+):
+ # given
+ checkout = checkout_with_items_and_shipping
+
+ expected_base_shipping_price = shipping_method.channel_listings.get(
+ channel=checkout.channel
+ ).price
+ expected_shipping_price = TaxedMoney(
+ net=expected_base_shipping_price * Decimal("0.9"),
+ gross=expected_base_shipping_price,
+ )
+ expected_shipping_tax_rate = Decimal("0.1")
+
+ manager = get_plugins_manager()
+ manager.get_checkout_shipping_tax_rate = mock.Mock(
+ return_value=expected_shipping_tax_rate
+ )
+ manager.calculate_checkout_shipping = mock.Mock(
+ return_value=expected_shipping_price
+ )
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ # when
+ order = _create_order(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ order_data=_prepare_order_data(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=None,
+ taxes_included_in_prices=True,
+ ),
+ user=customer_user,
+ app=None,
+ manager=manager,
+ )
+
+ # then
+ assert order.base_shipping_price == expected_base_shipping_price
+ assert order.shipping_price == expected_shipping_price
+ manager.calculate_checkout_shipping.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, []
+ )
+ assert order.shipping_tax_rate == expected_shipping_tax_rate
+ manager.get_checkout_shipping_tax_rate.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, [], expected_shipping_price
+ )
+
+
+def test_create_order_store_shipping_prices_with_free_shipping_voucher(
+ checkout_with_voucher_free_shipping,
+ shipping_method,
+ customer_user,
+):
+ # given
+ checkout = checkout_with_voucher_free_shipping
+ manager = get_plugins_manager()
+
+ expected_base_shipping_price = zero_money(checkout.currency)
+ expected_shipping_price = zero_taxed_money(checkout.currency)
+ expected_shipping_tax_rate = Decimal("0.0")
+
+ manager.get_checkout_shipping_tax_rate = mock.Mock(
+ return_value=expected_shipping_tax_rate
+ )
+ manager.calculate_checkout_shipping = mock.Mock(
+ return_value=expected_shipping_price
+ )
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ # when
+ order = _create_order(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ order_data=_prepare_order_data(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ discounts=None,
+ taxes_included_in_prices=True,
+ ),
+ user=customer_user,
+ app=None,
+ manager=manager,
+ )
+
+ # then
+ assert order.base_shipping_price == expected_base_shipping_price
+ assert order.shipping_price == expected_shipping_price
+ manager.calculate_checkout_shipping.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, []
+ )
+ assert order.shipping_tax_rate == expected_shipping_tax_rate
+ manager.get_checkout_shipping_tax_rate.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, [], expected_shipping_price
+ )
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index ee7b46d583..252d34e897 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -4,6 +4,7 @@ from unittest import mock
import pytest
from django.contrib.auth.models import AnonymousUser
from django.test import override_settings
+from prices import TaxedMoney
from ...core.exceptions import InsufficientStock
from ...core.taxes import zero_money, zero_taxed_money
@@ -564,3 +565,100 @@ def test_create_order_from_checkout_updates_total_charged_amount(
# then
assert order.total_charged_amount == charged_value
+
+
+def test_create_order_from_checkout_store_shipping_prices(
+ checkout_with_items_and_shipping, shipping_method, customer_user, app
+):
+ # given
+ checkout = checkout_with_items_and_shipping
+
+ expected_base_shipping_price = shipping_method.channel_listings.get(
+ channel=checkout.channel
+ ).price
+ expected_shipping_price = TaxedMoney(
+ net=expected_base_shipping_price * Decimal("0.9"),
+ gross=expected_base_shipping_price,
+ )
+ expected_shipping_tax_rate = Decimal("0.1")
+
+ manager = get_plugins_manager()
+ manager.get_checkout_shipping_tax_rate = mock.Mock(
+ return_value=expected_shipping_tax_rate
+ )
+ manager.calculate_checkout_shipping = mock.Mock(
+ return_value=expected_shipping_price
+ )
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ # when
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ # then
+ assert order.base_shipping_price == expected_base_shipping_price
+ assert order.shipping_price == expected_shipping_price
+ manager.calculate_checkout_shipping.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, []
+ )
+ assert order.shipping_tax_rate == expected_shipping_tax_rate
+ manager.get_checkout_shipping_tax_rate.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, [], expected_shipping_price
+ )
+
+
+def test_create_order_from_store_shipping_prices_with_free_shipping_voucher(
+ checkout_with_voucher_free_shipping,
+ shipping_method,
+ customer_user,
+ voucher_free_shipping,
+ app,
+):
+ # given
+ checkout = checkout_with_voucher_free_shipping
+
+ expected_base_shipping_price = zero_money(checkout.currency)
+ expected_shipping_price = zero_taxed_money(checkout.currency)
+ expected_shipping_tax_rate = Decimal("0.0")
+
+ manager = get_plugins_manager()
+ manager.get_checkout_shipping_tax_rate = mock.Mock(
+ return_value=expected_shipping_tax_rate
+ )
+ manager.calculate_checkout_shipping = mock.Mock(
+ return_value=expected_shipping_price
+ )
+
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ # when
+ order = create_order_from_checkout(
+ checkout_info=checkout_info,
+ checkout_lines=lines,
+ discounts=[],
+ manager=manager,
+ user=AnonymousUser(),
+ app=app,
+ tracking_code="tracking_code",
+ )
+
+ # then
+ assert order.base_shipping_price == expected_base_shipping_price
+ assert order.shipping_price == expected_shipping_price
+ manager.calculate_checkout_shipping.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, []
+ )
+ assert order.shipping_tax_rate == expected_shipping_tax_rate
+ manager.get_checkout_shipping_tax_rate.assert_called_once_with(
+ checkout_info, lines, checkout.shipping_address, [], expected_shipping_price
+ )
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index c14cd27e8c..0dd961d93a 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -400,7 +400,7 @@ def _get_shipping_voucher_discount_for_checkout(
msg = "This offer is not valid in your country."
raise NotApplicable(msg)
- shipping_price = base_calculations.base_checkout_delivery_price(
+ shipping_price = base_calculations.base_checkout_undiscounted_delivery_price(
checkout_info=checkout_info, lines=lines
)
return voucher.get_discount_amount_for(shipping_price, checkout_info.channel)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index ee4f93de69..78c2d74366 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -818,6 +818,7 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
"shipping_method": shipping_method,
"shipping_method_name": shipping_method.name,
"shipping_price": shipping_price,
+ "base_shipping_price": shipping_method_channel_listing.price,
}
)
if will_be_unconfirmed:
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
index dede8766c8..4178b42c22 100644
--- a/saleor/graphql/core/types/taxes.py
+++ b/saleor/graphql/core/types/taxes.py
@@ -1,5 +1,4 @@
-from decimal import Decimal
-from typing import List, Union
+from typing import Union
import graphene
from promise import Promise
@@ -7,10 +6,9 @@ from promise import Promise
from ....checkout import base_calculations
from ....checkout.models import Checkout, CheckoutLine
from ....core.prices import quantize_price
-from ....core.taxes import include_taxes_in_prices, zero_money
+from ....core.taxes import include_taxes_in_prices
from ....discount import VoucherType
from ....order.models import Order, OrderLine
-from ....shipping.models import ShippingMethodChannelListing
from ...account.dataloaders import AddressByIdLoader
from ...channel.dataloaders import ChannelByIdLoader
from ...channel.types import Channel
@@ -31,7 +29,6 @@ from ...product.dataloaders.products import (
ProductByVariantIdLoader,
ProductVariantByIdLoader,
)
-from ...shipping.dataloaders import ShippingMethodChannelListingByShippingMethodIdLoader
from .common import NonNullList
from .money import Money
@@ -312,19 +309,9 @@ class TaxableObject(graphene.ObjectType):
def calculate_shipping_price(data):
checkout_info, lines = data
- is_shipping_voucher = (
- checkout_info.voucher.type == VoucherType.SHIPPING
- if checkout_info.voucher
- else False
- )
price = base_calculations.base_checkout_delivery_price(
checkout_info, lines
)
- if is_shipping_voucher:
- price.amount = max(
- price.amount - checkout_info.checkout.discount_amount,
- Decimal("0.0"),
- )
return quantize_price(
price,
@@ -344,22 +331,7 @@ class TaxableObject(graphene.ObjectType):
]
).then(calculate_shipping_price)
- def calculate_base_shipping_method(
- channel_listins: List[ShippingMethodChannelListing],
- ):
- for listing in channel_listins:
- if listing.channel_id == root.channel_id:
- return listing.price
- return zero_money(root.currency)
-
- if not root.shipping_method:
- return zero_money(root.currency)
-
- return (
- ShippingMethodChannelListingByShippingMethodIdLoader(info.context)
- .load(root.shipping_method_id)
- .then(calculate_base_shipping_method)
- )
+ return root.base_shipping_price
@staticmethod
def resolve_discounts(root: Union[Checkout, Order], info):
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
index 30d2ae6178..260c48073a 100644
--- a/saleor/graphql/order/mutations/order_update_shipping.py
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -2,7 +2,7 @@ import graphene
from django.core.exceptions import ValidationError
from ....core.permissions import OrderPermissions
-from ....core.taxes import zero_taxed_money
+from ....core.taxes import zero_money, zero_taxed_money
from ....order import models
from ....order.actions import order_shipping_updated
from ....order.error_codes import OrderErrorCode
@@ -96,6 +96,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
)
order.shipping_method = None
+ order.base_shipping_price = zero_money(order.currency)
order.shipping_price = zero_taxed_money(order.currency)
order.shipping_method_name = None
invalidate_order_prices(order)
@@ -105,6 +106,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"shipping_method",
"shipping_price_net_amount",
"shipping_price_gross_amount",
+ "base_shipping_price_amount",
"shipping_method_name",
"should_refresh_prices",
"updated_at",
@@ -146,12 +148,14 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
order.shipping_method = method
order.shipping_method_name = method.name
+ order.base_shipping_price = shipping_method_data.price
invalidate_order_prices(order)
order.save(
update_fields=[
"currency",
"shipping_method",
"shipping_method_name",
+ "base_shipping_price_amount",
"should_refresh_prices",
"updated_at",
]
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 89e3fe5eac..dc2e0d78a1 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -24,7 +24,7 @@ from ....core.anonymize import obfuscate_email
from ....core.notify_events import NotifyEventType
from ....core.postgres import FlatConcatSearchVector
from ....core.prices import quantize_price
-from ....core.taxes import TaxError, zero_taxed_money
+from ....core.taxes import TaxError, zero_money, zero_taxed_money
from ....discount.models import OrderDiscount, VoucherChannelListing
from ....giftcard import GiftCardEvents
from ....giftcard.events import gift_cards_bought_event, gift_cards_used_in_order_event
@@ -7378,9 +7378,11 @@ def test_order_update_shipping(
staff_user,
):
order = order_with_lines
+ order.base_shipping_price = zero_money(order.currency)
order.status = status
order.save()
assert order.shipping_method != shipping_method
+
query = ORDER_UPDATE_SHIPPING_QUERY
order_id = graphene.Node.to_global_id("Order", order.id)
method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
@@ -7399,6 +7401,7 @@ def test_order_update_shipping(
shipping_price = TaxedMoney(shipping_total, shipping_total)
assert order.status == status
assert order.shipping_method == shipping_method
+ assert order.base_shipping_price == shipping_total
assert order.shipping_price_net == shipping_price.net
assert order.shipping_price_gross == shipping_price.gross
assert order.shipping_tax_rate == Decimal("0.0")
@@ -7470,6 +7473,7 @@ def test_order_update_shipping_tax_included(
).quantize()
assert order.status == OrderStatus.UNCONFIRMED
assert order.shipping_method == shipping_method
+ assert order.base_shipping_price == shipping_total
assert order.shipping_price_net == shipping_price.net
assert order.shipping_price_gross == shipping_price.gross
assert order.shipping_tax_rate == Decimal("0.19")
@@ -7504,6 +7508,7 @@ def test_order_update_shipping_clear_shipping_method(
order.refresh_from_db()
assert order.shipping_method is None
+ assert order.base_shipping_price == zero_money(order.currency)
assert order.shipping_price == zero_taxed_money(order.currency)
assert order.shipping_method_name is None
@@ -7686,18 +7691,27 @@ def test_order_update_shipping_excluded_shipping_method_postal_code(
def test_draft_order_clear_shipping_method(
staff_api_client, draft_order, permission_manage_orders
):
+ # given
assert draft_order.shipping_method
+ assert draft_order.base_shipping_price != zero_money(draft_order.currency)
+ assert draft_order.shipping_price != zero_taxed_money(draft_order.currency)
query = ORDER_UPDATE_SHIPPING_QUERY
order_id = graphene.Node.to_global_id("Order", draft_order.id)
variables = {"order": order_id, "shippingMethod": None}
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
+
+ # then
data = content["data"]["orderUpdateShipping"]
assert data["order"]["id"] == order_id
+
draft_order.refresh_from_db()
assert draft_order.shipping_method is None
+ assert draft_order.base_shipping_price == zero_money(draft_order.currency)
assert draft_order.shipping_price == zero_taxed_money(draft_order.currency)
assert draft_order.shipping_method_name is None
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index 3f3d85ed3d..ec7f53ca69 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -12,15 +12,9 @@ if TYPE_CHECKING:
from .models import Order, OrderLine
+# We need this function to don't break Avalara Excise.
def base_order_shipping(order: "Order") -> Money:
- if not order.shipping_method:
- return zero_money(order.currency)
- channel_listing = order.shipping_method.channel_listings.filter(
- channel_id=order.channel_id
- ).first()
- if not channel_listing:
- return zero_money(order.currency)
- return channel_listing.price
+ return order.base_shipping_price
def _base_order_subtotal(order: "Order", lines: Iterable["OrderLine"]) -> Money:
@@ -46,7 +40,7 @@ def base_order_total(order: "Order", lines: Iterable["OrderLine"]) -> Money:
"""
currency = order.currency
subtotal = _base_order_subtotal(order, lines)
- shipping_price = base_order_shipping(order)
+ shipping_price = order.base_shipping_price
order_discounts = order.discounts.all()
order_discounts_to_update = []
for order_discount in order_discounts:
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index b599fbb38b..fe78804857 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -112,7 +112,7 @@ def _get_order_base_prices(order, lines):
pass
try:
- shipping_price = base_order_calculations.base_order_shipping(order)
+ shipping_price = order.base_shipping_price
order.shipping_price = quantize_price(
TaxedMoney(net=shipping_price, gross=shipping_price),
shipping_price.currency,
diff --git a/saleor/order/migrations/0157_order_base_shipping_price_amount.py b/saleor/order/migrations/0157_order_base_shipping_price_amount.py
new file mode 100644
index 0000000000..a30b2c93d3
--- /dev/null
+++ b/saleor/order/migrations/0157_order_base_shipping_price_amount.py
@@ -0,0 +1,21 @@
+# Generated by Django 4.0.7 on 2022-09-20 09:40
+
+from decimal import Decimal
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0156_order_tax_exemption"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="base_shipping_price_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0.0"), max_digits=12
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0158_migrate_base_shipping_price_amount.py b/saleor/order/migrations/0158_migrate_base_shipping_price_amount.py
new file mode 100644
index 0000000000..8c7040b861
--- /dev/null
+++ b/saleor/order/migrations/0158_migrate_base_shipping_price_amount.py
@@ -0,0 +1,70 @@
+# Generated by Django 4.0.7 on 2022-09-26 10:15
+
+from django.db import migrations
+from django.db.models import F
+
+AVATAX_PLUGIN_ID = "mirumee.taxes.avalara"
+
+
+def set_base_shipping_price(apps, _schema_editor):
+ Order = apps.get_model("order", "Order")
+ PluginConfiguration = apps.get_model("plugins", "PluginConfiguration")
+ SiteSettings = apps.get_model("site", "SiteSettings")
+ Channel = apps.get_model("channel", "Channel")
+
+ channel_ids_with_tax_included = []
+ channel_ids_with_tax_excluded = []
+
+ # Fetch channel ids with overrode `SiteSettings.include_taxes_in_prices`
+ avatax_configs = PluginConfiguration.objects.filter(
+ identifier=AVATAX_PLUGIN_ID, active=True
+ )
+ for config in avatax_configs:
+ config_dict = {item["name"]: item["value"] for item in config.configuration}
+ override_global_tax = config_dict.get("override_global_tax")
+ if override_global_tax:
+ include_taxes_in_prices = config_dict.get("include_taxes_in_prices")
+ if include_taxes_in_prices:
+ channel_ids_with_tax_included.append(config.channel_id)
+ else:
+ channel_ids_with_tax_excluded.append(config.channel_id)
+
+ # Fetch channel ids with default settings
+ channel_ids_with_override_config = (
+ channel_ids_with_tax_included + channel_ids_with_tax_excluded
+ )
+ site_settings = SiteSettings.objects.first()
+ channel_ids_without_override_config = Channel.objects.exclude(
+ id__in=channel_ids_with_override_config
+ ).values_list("id", flat=True)
+ if site_settings and site_settings.include_taxes_in_prices:
+ channel_ids_with_tax_included.extend(channel_ids_without_override_config)
+ else:
+ channel_ids_with_tax_excluded.extend(channel_ids_without_override_config)
+
+ # Set base shipping price for channels with tax included in prices
+ if channel_ids_with_tax_included:
+ Order.objects.filter(channel_id__in=channel_ids_with_tax_included).update(
+ base_shipping_price_amount=F("shipping_price_gross_amount")
+ )
+
+ # Set base shipping price for channels with tax excluded in prices
+ if channel_ids_with_tax_excluded:
+ Order.objects.filter(channel_id__in=channel_ids_with_tax_excluded).update(
+ base_shipping_price_amount=F("shipping_price_net_amount")
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0157_order_base_shipping_price_amount"),
+ ("site", "0034_sitesettings_limit_quantity_per_checkout"),
+ ("channel", "0005_channel_allocation_strategy"),
+ ("plugins", "0010_auto_20220104_1239"),
+ ]
+ operations = [
+ migrations.RunPython(
+ set_base_shipping_price, reverse_code=migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 375c8326fc..60b8d5e791 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -183,7 +183,7 @@ class Order(ModelWithMetadata):
shipping_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
editable=False,
)
shipping_price_net = MoneyField(
@@ -193,7 +193,7 @@ class Order(ModelWithMetadata):
shipping_price_gross_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
editable=False,
)
shipping_price_gross = MoneyField(
@@ -205,6 +205,14 @@ class Order(ModelWithMetadata):
gross_amount_field="shipping_price_gross_amount",
currency_field="currency",
)
+ base_shipping_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal("0.0"),
+ )
+ base_shipping_price = MoneyField(
+ amount_field="base_shipping_price_amount", currency_field="currency"
+ )
shipping_tax_rate = models.DecimalField(
max_digits=5, decimal_places=4, default=Decimal("0.0")
)
@@ -215,12 +223,12 @@ class Order(ModelWithMetadata):
total_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_total_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
total_net = MoneyField(amount_field="total_net_amount", currency_field="currency")
@@ -231,12 +239,12 @@ class Order(ModelWithMetadata):
total_gross_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_total_gross_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
total_gross = MoneyField(
@@ -260,12 +268,12 @@ class Order(ModelWithMetadata):
total_charged_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
total_authorized_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
total_authorized = MoneyField(
amount_field="total_authorized_amount", currency_field="currency"
@@ -489,7 +497,7 @@ class OrderLine(ModelWithMetadata):
unit_discount_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
unit_discount = MoneyField(
amount_field="unit_discount_amount", currency_field="currency"
@@ -556,12 +564,12 @@ class OrderLine(ModelWithMetadata):
undiscounted_unit_price_gross_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_unit_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_unit_price = TaxedMoneyField(
net_amount_field="undiscounted_unit_price_net_amount",
@@ -572,12 +580,12 @@ class OrderLine(ModelWithMetadata):
undiscounted_total_price_gross_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_total_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_total_price = TaxedMoneyField(
net_amount_field="undiscounted_total_price_net_amount",
@@ -588,7 +596,7 @@ class OrderLine(ModelWithMetadata):
base_unit_price_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
base_unit_price = MoneyField(
amount_field="base_unit_price_amount", currency_field="currency"
@@ -597,7 +605,7 @@ class OrderLine(ModelWithMetadata):
undiscounted_base_unit_price_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
+ default=Decimal("0.0"),
)
undiscounted_base_unit_price = MoneyField(
amount_field="undiscounted_base_unit_price_amount", currency_field="currency"
diff --git a/saleor/order/tests/test_base_calculations/test_base_order_shipping.py b/saleor/order/tests/test_base_calculations/test_base_order_shipping.py
deleted file mode 100644
index f6f3326f96..0000000000
--- a/saleor/order/tests/test_base_calculations/test_base_order_shipping.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from ....core.taxes import zero_money
-from ... import base_calculations
-
-
-def test_base_order_shipping(order_with_lines):
- # given
- order = order_with_lines
- channel_listing = order.shipping_method.channel_listings.filter(
- channel_id=order.channel_id
- ).first()
-
- # when
- order_total = base_calculations.base_order_shipping(order)
-
- # then
- assert order_total == channel_listing.price
-
-
-def test_base_order_shipping_without_shipping(order):
- # given
-
- # when
- order_total = base_calculations.base_order_shipping(order)
-
- # then
- assert order_total == zero_money(order.currency)
-
-
-def test_base_order_shipping_shipping_without_channel_listing(order_with_lines):
- # given
- order = order_with_lines
- order.shipping_method.channel_listings.filter(channel_id=order.channel_id).delete()
-
- # when
- order_total = base_calculations.base_order_shipping(order)
-
- # then
- assert order_total == zero_money(order.currency)
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index 405b56eda1..e23e981c91 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -9,7 +9,6 @@ from ...core.prices import quantize_price
from ...core.taxes import TaxData, TaxError, TaxLineData, zero_taxed_money
from ...plugins.manager import get_plugins_manager
from .. import OrderStatus, calculations
-from ..base_calculations import base_order_shipping
from ..interface import OrderTaxedPricesData
@@ -648,7 +647,7 @@ def test_fetch_order_prices_when_tax_exemption_and_not_include_taxes_in_prices(
subtotal = zero_taxed_money(currency)
undiscounted_subtotal = zero_taxed_money(currency)
- shipping_price = base_order_shipping(order_with_lines)
+ shipping_price = order_with_lines.base_shipping_price
shipping_price = quantize_price(
TaxedMoney(
shipping_price,
@@ -722,6 +721,31 @@ def test_fetch_order_prices_if_expired_prefetch_with_lines(
assert all(line._state.fields_cache for line in order_lines)
+def test_fetch_order_prices_if_expired_use_base_shipping_price(
+ plugins_manager, fetch_kwargs, order_with_lines
+):
+ # given
+ order = order_with_lines
+ currency = order.currency
+ shipping_channel_listing = order.shipping_method.channel_listings.get(
+ channel=order.channel
+ )
+ expected_price = Money("2.00", currency)
+ order.base_shipping_price = expected_price
+ order.save()
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ order_with_lines.refresh_from_db()
+ assert order_with_lines.base_shipping_price != shipping_channel_listing.price
+ assert order_with_lines.base_shipping_price == expected_price
+ assert order_with_lines.shipping_price == TaxedMoney(
+ net=expected_price, gross=expected_price
+ )
+
+
@patch("saleor.order.calculations.fetch_order_prices_if_expired")
def test_order_line_unit(mocked_fetch_order_prices_if_expired):
# given
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index be64d8921b..fefe83c357 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -19,11 +19,8 @@ from ...checkout.utils import is_shipping_required
from ...core.taxes import TaxError
from ...discount import OrderDiscountType, VoucherType
from ...order import base_calculations as base_order_calculations
-from ...order.utils import (
- get_total_order_discount_excluding_shipping,
- get_voucher_discount_assigned_to_order,
-)
-from ...shipping.models import ShippingMethod, ShippingMethodChannelListing
+from ...order.utils import get_total_order_discount_excluding_shipping
+from ...shipping.models import ShippingMethod
from ...warehouse.models import Warehouse
if TYPE_CHECKING:
@@ -405,28 +402,13 @@ def get_order_lines_data(
amount=price_with_discounts_amount,
)
- shipping_method_channel_listing = ShippingMethodChannelListing.objects.filter(
- shipping_method=order.shipping_method_id, channel=order.channel_id
- ).first()
- if shipping_method_channel_listing:
- shipping_discount_amount = Decimal("0")
- if (
- order.voucher_id
- and order.voucher.type == VoucherType.SHIPPING # type: ignore
- ):
- shipping_discount = get_voucher_discount_assigned_to_order(order)
- if shipping_discount:
- shipping_discount_amount = shipping_discount.amount_value
- shipping_price = max(
- shipping_method_channel_listing.price.amount - shipping_discount_amount,
- Decimal("0"),
- )
+ if shipping_price := order.base_shipping_price_amount:
shipping_discounted = order.discounts.filter(
type=OrderDiscountType.MANUAL
).exists()
append_shipping_to_data(
data,
- shipping_price if shipping_price else None,
+ shipping_price,
config.shipping_tax_code,
tax_included,
shipping_discounted,
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 30ccf993df..5f5ab9b9b9 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -568,14 +568,7 @@ class AvataxPlugin(BasePlugin):
net = Money(amount=net, currency=currency)
return TaxedMoney(net=net, gross=gross)
- channel_listing = None
- if shipping_method := order.shipping_method:
- channel_listing = shipping_method.channel_listings.filter(
- channel_id=order.channel_id
- ).first()
- if not channel_listing:
- return previous_value
- price = channel_listing.price
+ price = order.base_shipping_price
return TaxedMoney(
net=price,
gross=price,
@@ -616,7 +609,7 @@ class AvataxPlugin(BasePlugin):
).price_with_discounts
taxed_subtotal += taxed_line_total_data
- base_shipping_price = base_order_calculations.base_order_shipping(order)
+ base_shipping_price = order.base_shipping_price
shipping_price = self._calculate_order_shipping(
order, taxes_data, base_shipping_price
)
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 07b914caf4..54420b0c71 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -19,7 +19,7 @@ from ....checkout.fetch import (
)
from ....checkout.utils import add_variant_to_checkout
from ....core.prices import quantize_price
-from ....core.taxes import TaxError, TaxType, zero_taxed_money
+from ....core.taxes import TaxError, TaxType, zero_money, zero_taxed_money
from ....discount import DiscountValueType, OrderDiscountType, VoucherType
from ....order import OrderStatus
from ....product import ProductTypeKind
@@ -918,6 +918,7 @@ def test_calculate_order_shipping_order_not_valid(
net=Money("10.00", "USD"), gross=Money("10.00", "USD")
)
order.shipping_address = None
+ order.base_shipping_price = Money("10.00", "USD")
order.shipping_method = shipping_method
order.save()
@@ -4108,11 +4109,13 @@ def test_get_order_request_data_draft_order_with_shipping_voucher(
order_with_lines.shipping_address = order_with_lines.billing_address.get_copy()
order_with_lines.shipping_method_name = method.name
order_with_lines.shipping_method = method
+ order_with_lines.base_shipping_price = zero_money(order_with_lines.currency)
order_with_lines.voucher = voucher_free_shipping
order_with_lines.save(
update_fields=[
"status",
"voucher",
+ "base_shipping_price_amount",
"shipping_address",
"shipping_method_name",
"shipping_method",
@@ -4170,11 +4173,13 @@ def test_get_order_request_data_draft_order_shipping_voucher_amount_too_high(
order_with_lines.shipping_address = order_with_lines.billing_address.get_copy()
order_with_lines.shipping_method_name = method.name
order_with_lines.shipping_method = method
+ order_with_lines.base_shipping_price = zero_money(order_with_lines.currency)
order_with_lines.voucher = voucher_free_shipping
order_with_lines.save(
update_fields=[
"status",
"voucher",
+ "base_shipping_price_amount",
"shipping_address",
"shipping_method_name",
"shipping_method",
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 1c6932f162..cf34cb0878 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -318,7 +318,7 @@ class PluginsManager(PaymentInterface):
)
def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
- shipping_price = base_order_calculations.base_order_shipping(order)
+ shipping_price = order.base_shipping_price
default_value = quantize_price(
TaxedMoney(net=shipping_price, gross=shipping_price),
shipping_price.currency,
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index f5b8c81631..3a11f2f022 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -277,24 +277,7 @@ class VatlayerPlugin(BasePlugin):
if not order.shipping_method:
return previous_value
- shipping_price = order.shipping_method.channel_listings.get(
- channel_id=order.channel_id
- ).price
-
- if (
- order.voucher_id
- and order.voucher.type == VoucherType.SHIPPING # type: ignore
- ):
- shipping_discount = get_voucher_discount_assigned_to_order(order)
- if shipping_discount:
- shipping_price = Money(
- max(
- shipping_price.amount - shipping_discount.amount_value,
- Decimal("0"),
- ),
- shipping_price.currency,
- )
- return get_taxed_shipping_price(shipping_price, taxes)
+ return get_taxed_shipping_price(order.base_shipping_price, taxes)
def update_taxes_for_order_lines(
self,
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index a3450ca638..cd92c9466c 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -11,7 +11,7 @@ from ....checkout import calculations
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import add_variant_to_checkout
from ....core.prices import quantize_price
-from ....core.taxes import zero_taxed_money
+from ....core.taxes import zero_money, zero_taxed_money
from ....discount import DiscountValueType, OrderDiscountType
from ....product.models import Product
from ...manager import get_plugins_manager
@@ -748,6 +748,7 @@ def test_calculate_order_shipping(vatlayer, order_line, shipping_zone, site_sett
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = method.name
order.shipping_method = method
+ order.base_shipping_price = method.channel_listings.get(channel=order.channel).price
order.save()
price = manager.calculate_order_shipping(order)
price = quantize_price(price, price.currency)
@@ -766,6 +767,7 @@ def test_calculate_order_shipping_from_origin_country(
method = shipping_zone.shipping_methods.get()
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = method.name
+ order.base_shipping_price = method.channel_listings.get(channel=order.channel).price
order.shipping_method = method
order.save()
@@ -790,6 +792,7 @@ def test_calculate_order_shipping_with_excluded_country(
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = method.name
order.shipping_method = method
+ order.base_shipping_price = method.channel_listings.get(channel=order.channel).price
order.save()
price = manager.calculate_order_shipping(order)
@@ -817,15 +820,19 @@ def test_calculate_order_shipping_voucher_on_shipping(
# given
manager = get_plugins_manager()
order = order_line.order
+ currency = order.currency
+ discount_amount = Decimal("5.0")
+
method = shipping_zone.shipping_methods.get()
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = method.name
order.shipping_method = method
+ order.base_shipping_price = method.channel_listings.get(
+ channel=order.channel
+ ).price - Money(discount_amount, currency)
order.voucher = voucher_shipping_type
order.save()
- currency = order.currency
- discount_amount = Decimal("5.0")
order.discounts.create(
type=OrderDiscountType.VOUCHER,
value_type=DiscountValueType.FIXED,
@@ -863,6 +870,7 @@ def test_calculate_order_shipping_free_shipping_voucher(
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = method.name
order.shipping_method = method
+ order.base_shipping_price = zero_money(order.currency)
order.voucher = voucher_shipping_type
order.save()
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
index cfa89305de..be4d63839c 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -1,6 +1,7 @@
import json
from decimal import Decimal
from functools import partial
+from unittest.mock import ANY
from freezegun import freeze_time
from prices import Money, fixed_discount
@@ -139,6 +140,49 @@ def test_checkout_calculate_taxes(
}
+@freeze_time("2020-03-18 12:00:00")
+def test_checkout_calculate_taxes_with_free_shipping_voucher(
+ checkout_with_voucher_free_shipping,
+ webhook_app,
+ permission_handle_taxes,
+):
+ # given
+ checkout = checkout_with_voucher_free_shipping
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ event_type, checkout, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(checkout.shipping_address)},
+ "currency": "USD",
+ "discounts": [],
+ "channel": {"id": to_global_id_or_none(checkout.channel)},
+ "lines": ANY,
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "sourceObject": {
+ "id": to_global_id_or_none(checkout),
+ "__typename": "Checkout",
+ },
+ },
+ }
+
+
@freeze_time("2020-03-18 12:00:00")
def test_checkout_calculate_taxes_with_voucher(
checkout_with_voucher,
@@ -304,6 +348,9 @@ def test_order_calculate_taxes(
# given
order = order_line.order
+ expected_shipping_price = Money("2.00", order.currency)
+ order.base_shipping_price = expected_shipping_price
+ order.save()
shipping_method = shipping_zone.shipping_methods.first()
order.shipping_method = shipping_method
webhook_app.permissions.add(permission_handle_taxes)
@@ -325,6 +372,7 @@ def test_order_calculate_taxes(
channel=order.channel
).price.amount
shipping_price_amount = quantize_price(shipping_price_amount, order.currency)
+ assert expected_shipping_price != shipping_price_amount
assert json.loads(deliveries.payload.payload) == {
"__typename": "CalculateTaxes",
"taxBase": {
@@ -348,7 +396,7 @@ def test_order_calculate_taxes(
}
],
"pricesEnteredWithTax": True,
- "shippingPrice": {"amount": shipping_price_amount},
+ "shippingPrice": {"amount": expected_shipping_price.amount},
"sourceObject": {
"__typename": "Order",
"id": to_global_id_or_none(order),
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 1398232d47..8ebf06554c 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -637,6 +637,19 @@ def checkout_with_voucher_percentage(checkout, product, voucher_percentage):
return checkout
+def checkout_with_voucher_free_shipping(
+ checkout_with_items_and_shipping, voucher_free_shipping
+):
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_items_and_shipping)
+ checkout_info = fetch_checkout_info(
+ checkout_with_items_and_shipping, lines, [], manager
+ )
+ add_voucher_to_checkout(manager, checkout_info, lines, voucher_free_shipping, [])
+ return checkout_with_items_and_shipping
+
+
@pytest.fixture
def checkout_with_gift_card(checkout_with_item, gift_card):
checkout_with_item.gift_cards.add(gift_card)
@@ -3896,6 +3909,7 @@ def order_with_lines(
net = shipping_price.get_total()
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
order.shipping_price = TaxedMoney(net=net, gross=gross)
+ order.base_shipping_price = net
order.save()
recalculate_order(order)
@@ -4168,6 +4182,7 @@ def order_with_lines_channel_PLN(
net = shipping_price.get_total()
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
order.shipping_price = TaxedMoney(net=net, gross=gross)
+ order.base_shipping_price = net
order.save()
recalculate_order(order)
@@ -4279,6 +4294,7 @@ def order_with_preorder_lines(
net = shipping_price.get_total()
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
order.shipping_price = TaxedMoney(net=net, gross=gross)
+ order.base_shipping_price = net
order.save()
recalculate_order(order)
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index f0a3390476..e07a963002 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -46,7 +46,6 @@ from .serializers import (
serialize_checkout_lines_for_tax_calculation,
serialize_product_or_variant_attributes,
)
-from .utils import get_base_price
if TYPE_CHECKING:
# pylint: disable=unused-import
@@ -1328,8 +1327,7 @@ def generate_order_payload_for_tax_calculation(order: "Order"):
# Prepare shipping data
shipping_method_name = order.shipping_method_name
shipping_method_amount = quantize_price(
- get_base_price(order.shipping_price, included_taxes_in_prices),
- order.currency,
+ order.base_shipping_price_amount, order.currency
)
order_data = serializer.serialize(
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 14425ebc78..df9b431ea7 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -4,7 +4,7 @@ from datetime import datetime, timedelta
from decimal import Decimal
from itertools import chain
from unittest import mock
-from unittest.mock import ANY, Mock, patch, sentinel
+from unittest.mock import ANY, patch, sentinel
import graphene
import pytest
@@ -58,7 +58,6 @@ from ..payloads import (
generate_sale_toggle_payload,
generate_transaction_action_request_payload,
generate_translation_payload,
- get_base_price,
serialize_refund_data,
)
from ..serializers import serialize_checkout_lines
@@ -349,9 +348,7 @@ def test_generate_order_payload_for_tax_calculation(
"currency": order.currency,
"shipping_name": order.shipping_method.name,
"shipping_amount": str(
- quantize_price(
- get_base_price(order.shipping_price, taxes_included), currency
- )
+ quantize_price(order.base_shipping_price_amount, currency)
),
"metadata": order.metadata,
"discounts": [
@@ -1784,15 +1781,6 @@ NET_AMOUNT = sentinel.NET_AMOUNT
GROSS_AMOUNT = sentinel.GROSS_AMOUNT
- "taxes_included, amount", [(True, GROSS_AMOUNT), (False, NET_AMOUNT)]
-)
-def test_get_base_price(taxes_included, amount):
- # given
- price = Mock(net=Mock(amount=NET_AMOUNT), gross=Mock(amount=GROSS_AMOUNT))
- assert amount == get_base_price(price, taxes_included)
-
-
@pytest.mark.parametrize(
"action_type, action_value",
[
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index a44b8a0b6a..3151ff02c6 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -1,9 +1,7 @@
-from decimal import Decimal
from typing import TYPE_CHECKING, Optional
from django.db.models import Q
from django.db.models.expressions import Exists, OuterRef
-from prices import TaxedMoney
from ..app.models import App
from .event_types import WebhookEventAsyncType, WebhookEventSyncType
@@ -41,9 +39,3 @@ def get_webhooks_for_event(
.select_related("app")
.prefetch_related("app__permissions__content_type")
)
-
-
-def get_base_price(price: TaxedMoney, include_taxes_in_prices: bool) -> Decimal:
- if include_taxes_in_prices:
- return price.gross.amount
- return price.net.amount