Skip to content

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

Add support for calculating taxes in Saleor Apps (#9526)

Filip Owczarek3e06a6462559
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9cb4f487bc..fb3e85385b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,11 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
- Drop django-versatileimagefield package; add a proxy view to generate thumbnails on-demand - #9988 by @IKarbowiak
- Drop `create_thumbnails` command
+- Add synchronous tax calculation via webhooks - #9526 by @fowczarek, @mateuszgrzyb, @stnatic
+ - Change return type from `CheckoutTaxedPricesData` to `TaxedMoney` in plugin manager methods:
+ - `calculate_checkout_line_total`
+ - `calculate_checkout_line_unit_price`
+
### Other changes
- Add `VoucherFilter.ids` filter - #10157 by @Jakubkuc
@@ -29,6 +34,19 @@ All notable, unreleased changes to this project will be documented in this file.
- Fix problem with updating draft order with active avalara - #10183 by @IKarbowiak
- Fix stock validation and allocation for order with local collection point - #10218 by @IKarbowiak
- Fix stock allocation for order with global collection point - #10225 by @IKarbowiak
+- Add synchronous tax calculation via webhooks - #9526 by @fowczarek, @mateuszgrzyb, @stnatic
+ - Add option to calculate taxes via webhooks more info in docs
+ <!-- We should put docs link here before release -->
+
+### GraphQL API
+- Add synchronous tax calculation via webhooks - #9526 by @fowczarek, @mateuszgrzyb, @stnatic
+ - Add `CHECKOUT_CALCULATE_TAXES` and `ORDER_CALCULATE_TAXES` to `WebhookEventTypeSyncEnum`
+
+### Plugins
+- Add synchronous tax calculation via webhooks - #9526 by @fowczarek, @mateuszgrzyb, @stnatic
+ - Add new method to plugin manager:
+ - `get_taxes_for_checkout`
+ - `get_taxes_for_order`
# 3.5.0
diff --git a/saleor/checkout/__init__.py b/saleor/checkout/__init__.py
index a2fd060bcd..65fc6f1c47 100644
--- a/saleor/checkout/__init__.py
+++ b/saleor/checkout/__init__.py
@@ -2,6 +2,8 @@ import logging
logger = logging.getLogger(__name__)
+default_app_config = "saleor.checkout.app.CheckoutAppConfig"
+
class AddressType:
BILLING = "billing"
diff --git a/saleor/checkout/app.py b/saleor/checkout/app.py
new file mode 100644
index 0000000000..5df17e41e4
--- /dev/null
+++ b/saleor/checkout/app.py
@@ -0,0 +1,5 @@
+from django.apps import AppConfig
+
+
+class CheckoutAppConfig(AppConfig):
+ name = "saleor.checkout"
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 1e8f09a42b..1ec1399912 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -1,33 +1,75 @@
"""Contain functions which are base for calculating checkout properties.
-It's recommended to use functions from calculations.py module to take in account plugin
-manager.
+It's recommended to use functions from calculations.py module to take in account
+plugin manager. Functions from this module return price without
+taxes(Money instead of TaxedMoney). If you don't need pre-taxed prices use functions
+from calculations.py.
"""
from decimal import Decimal
from typing import TYPE_CHECKING, Iterable, Optional
-from prices import TaxedMoney
+from prices import Money, TaxedMoney
from ..core.prices import quantize_price
-from ..core.taxes import zero_money, zero_taxed_money
+from ..core.taxes import zero_money
from ..discount import DiscountInfo, VoucherType
from ..order.interface import OrderTaxedPricesData
-from .fetch import CheckoutLineInfo, ShippingMethodInfo
-from .interface import CheckoutPricesData, CheckoutTaxedPricesData
+from .fetch import CheckoutInfo, CheckoutLineInfo
if TYPE_CHECKING:
from ..channel.models import Channel
- from ..checkout.fetch import CheckoutInfo
from ..order.models import OrderLine
+ from .fetch import ShippingMethodInfo
+
+
+def calculate_base_line_unit_price(
+ line_info: "CheckoutLineInfo",
+ channel: "Channel",
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+) -> Money:
+ """Calculate line unit price including discounts and vouchers."""
+ total_line_price = calculate_base_line_total_price(
+ line_info=line_info, channel=channel, discounts=discounts
+ )
+ quantity = line_info.line.quantity
+ currency = total_line_price.currency
+ return quantize_price(total_line_price / quantity, currency)
+
+
+def calculate_base_line_total_price(
+ line_info: "CheckoutLineInfo",
+ channel: "Channel",
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+) -> Money:
+ """Calculate line total price including discounts and vouchers."""
+ unit_price = _calculate_base_line_unit_price(
+ line_info=line_info, channel=channel, discounts=discounts
+ )
+ if line_info.voucher and line_info.voucher.apply_once_per_order:
+ variant_price_with_discounts = max(
+ unit_price
+ - line_info.voucher.get_discount_amount_for(unit_price, channel=channel),
+ zero_money(unit_price.currency),
+ )
+ # we add -1 as we handle a case when voucher is applied only to single line
+ # of the cheapest item
+ quantity_without_voucher = line_info.line.quantity - 1
+ total_price = (
+ unit_price * quantity_without_voucher + variant_price_with_discounts
+ )
+ else:
+ total_price = unit_price * line_info.line.quantity
+
+ return quantize_price(total_price, total_price.currency)
def _calculate_base_line_unit_price(
- line_info: CheckoutLineInfo,
+ line_info: "CheckoutLineInfo",
channel: "Channel",
discounts: Optional[Iterable[DiscountInfo]] = None,
-) -> CheckoutPricesData:
- """Calculate base line unit price without voucher applied once per order."""
+) -> Money:
+ """Calculate base line unit price including discounts and vouchers."""
variant = line_info.variant
variant_price = variant.get_price(
line_info.product,
@@ -38,132 +80,54 @@ def _calculate_base_line_unit_price(
line_info.line.price_override,
)
- if not discounts:
- undiscounted_variant_price = variant_price
- else:
- undiscounted_variant_price = variant.get_price(
- line_info.product,
- line_info.collections,
- channel,
- line_info.channel_listing,
- [],
- line_info.line.price_override,
- )
-
if line_info.voucher and not line_info.voucher.apply_once_per_order:
- price_with_discounts = max(
+ unit_price = max(
variant_price
- line_info.voucher.get_discount_amount_for(variant_price, channel=channel),
zero_money(variant_price.currency),
)
else:
- price_with_discounts = variant_price
-
- return CheckoutPricesData(
- undiscounted_price=quantize_price(
- undiscounted_variant_price, undiscounted_variant_price.currency
- ),
- price_with_sale=quantize_price(variant_price, variant_price.currency),
- price_with_discounts=quantize_price(
- price_with_discounts, price_with_discounts.currency
- ),
- )
+ unit_price = variant_price
+ return quantize_price(unit_price, unit_price.currency)
-def calculate_base_line_unit_price(
- line_info: CheckoutLineInfo,
+
+def calculate_undiscounted_base_line_total_price(
+ line_info: "CheckoutLineInfo",
channel: "Channel",
- discounts: Optional[Iterable[DiscountInfo]] = None,
-) -> CheckoutPricesData:
- """Calculate line unit prices including discounts and vouchers.
-
- Returns a three money values. Undiscounted price, price and price with voucher.
- Voucher is added to 'price_with_discounts' when line's product matches to products
- applicable for voucher.
- For voucher with 'apply once per order', the price will be included in unit price.
- 'price' includes discount from sale if any valid exists.
- 'price_with_discounts' includes voucher discount and sale discount if any valid
- exists.
- 'undiscounted_price' is a price without any sale and voucher.
- """
- prices_data = calculate_base_line_total_price(
- line_info=line_info, channel=channel, discounts=discounts
- )
- quantity = line_info.line.quantity
- currency = prices_data.price_with_discounts.currency
- return CheckoutPricesData(
- undiscounted_price=quantize_price(
- prices_data.undiscounted_price / quantity, currency
- ),
- price_with_sale=quantize_price(
- prices_data.price_with_sale / quantity, currency
- ),
- price_with_discounts=quantize_price(
- prices_data.price_with_discounts / quantity, currency
- ),
+) -> Money:
+ """Calculate line total price excluding discounts and vouchers."""
+ unit_price = calculate_undiscounted_base_line_unit_price(
+ line_info=line_info, channel=channel
)
+ total_price = unit_price * line_info.line.quantity
+ return quantize_price(total_price, total_price.currency)
-def calculate_base_line_total_price(
- line_info: CheckoutLineInfo,
+def calculate_undiscounted_base_line_unit_price(
+ line_info: "CheckoutLineInfo",
channel: "Channel",
- discounts: Optional[Iterable[DiscountInfo]] = None,
-) -> CheckoutPricesData:
- """Calculate line total prices including discounts and vouchers.
-
- Returns a three money values. Undiscounted price, price and price with voucher.
- It calculates a unit prices and adds a voucher to line if voucher is applicable
- only once per order.
- 'price' includes discount from sale if any valid exists.
- 'price_with_discounts' includes voucher discount and sale discount if any valid
- exists.
- 'undiscounted_price' is a price without any sale and voucher.
- """
- prices_data = _calculate_base_line_unit_price(
- line_info=line_info, channel=channel, discounts=discounts
- )
- if line_info.voucher and line_info.voucher.apply_once_per_order:
- variant_price_with_discounts = max(
- prices_data.price_with_sale
- - line_info.voucher.get_discount_amount_for(
- prices_data.price_with_sale, channel=channel
- ),
- zero_money(prices_data.price_with_sale.currency),
- )
- # we add -1 as we handle a case when voucher is applied only to single line
- # of the cheapest item
- quantity_without_voucher = line_info.line.quantity - 1
- prices_data = CheckoutPricesData(
- price_with_discounts=(
- prices_data.price_with_sale * quantity_without_voucher
- + variant_price_with_discounts
- ),
- price_with_sale=prices_data.price_with_sale * line_info.line.quantity,
- undiscounted_price=prices_data.undiscounted_price * line_info.line.quantity,
- )
- else:
- prices_data = CheckoutPricesData(
- price_with_sale=prices_data.price_with_sale * line_info.line.quantity,
- price_with_discounts=prices_data.price_with_discounts
- * line_info.line.quantity,
- undiscounted_price=prices_data.undiscounted_price * line_info.line.quantity,
- )
- prices_data.price_with_sale = quantize_price(
- prices_data.price_with_sale, prices_data.price_with_sale.currency
- )
- prices_data.undiscounted_price = quantize_price(
- prices_data.undiscounted_price, prices_data.undiscounted_price.currency
- )
- prices_data.price_with_discounts = quantize_price(
- prices_data.price_with_discounts, prices_data.price_with_discounts.currency
+):
+ """Calculate line unit price without including discounts and vouchers."""
+ variant = line_info.variant
+ variant_price = variant.get_price(
+ line_info.product,
+ line_info.collections,
+ channel,
+ line_info.channel_listing,
+ [],
+ line_info.line.price_override,
)
- return prices_data
+ return quantize_price(variant_price, variant_price.currency)
def base_checkout_delivery_price(
- checkout_info: "CheckoutInfo", lines=None
-) -> TaxedMoney:
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"] = None,
+) -> Money:
"""Calculate base (untaxed) price for any kind of delivery method."""
+ from .fetch import ShippingMethodInfo
+
delivery_method_info = checkout_info.delivery_method_info
if isinstance(delivery_method_info, ShippingMethodInfo):
@@ -171,15 +135,17 @@ def base_checkout_delivery_price(
checkout_info, delivery_method_info, lines
)
- return zero_taxed_money(checkout_info.checkout.currency)
+ return zero_money(checkout_info.checkout.currency)
def calculate_base_price_for_shipping_method(
checkout_info: "CheckoutInfo",
- shipping_method_info: ShippingMethodInfo,
- lines=None,
-) -> TaxedMoney:
+ shipping_method_info: "ShippingMethodInfo",
+ lines: Iterable["CheckoutLineInfo"] = None,
+) -> Money:
"""Return checkout shipping price."""
+ from .fetch import CheckoutLineInfo
+
# FIXME: Optimize checkout.is_shipping_required
shipping_method = shipping_method_info.delivery_method
@@ -191,15 +157,10 @@ def calculate_base_price_for_shipping_method(
shipping_required = checkout_info.checkout.is_shipping_required()
if not shipping_method or not shipping_required:
- return zero_taxed_money(checkout_info.checkout.currency)
+ return zero_money(checkout_info.checkout.currency)
- # Base price does not yet contain tax information,
- # which can be later applied by tax plugins
return quantize_price(
- TaxedMoney(
- net=shipping_method.price,
- gross=shipping_method.price,
- ),
+ shipping_method.price,
checkout_info.checkout.currency,
)
@@ -208,18 +169,18 @@ def base_checkout_total(
checkout_info: "CheckoutInfo",
discounts: Iterable[DiscountInfo],
lines: Iterable["CheckoutLineInfo"],
-) -> TaxedMoney:
+) -> Money:
"""Return the total cost of the checkout."""
currency = checkout_info.checkout.currency
line_totals = [
- base_checkout_line_total(
+ calculate_base_line_total_price(
line_info,
checkout_info.channel,
discounts,
- ).price_with_discounts
+ )
for line_info in lines
]
- subtotal = sum(line_totals, zero_taxed_money(currency))
+ subtotal = sum(line_totals, zero_money(currency))
shipping_price = base_checkout_delivery_price(checkout_info, lines)
discount = checkout_info.checkout.discount
@@ -232,57 +193,28 @@ 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:
- # we can operate on amount as the base shipping net and gross is the same
- shipping_price = max(zero_money(currency), shipping_price.gross - discount)
- shipping_price = TaxedMoney(net=shipping_price, gross=shipping_price)
+ shipping_price = max(zero_money(currency), shipping_price - discount)
else:
- subtotal = subtotal - discount
- # Comparing TaxedMoney objects works only on gross values. That is why we are
- # explicitly returning zero_taxed_money if total.gross is less or equal zero.
- zero = zero_taxed_money(currency)
- if subtotal.gross <= zero.gross:
- subtotal = zero
+ subtotal = max(zero_money(currency), subtotal - discount)
return subtotal + shipping_price
-def base_checkout_lines_total(
+def base_checkout_subtotal(
checkout_lines: Iterable["CheckoutLineInfo"],
channel: "Channel",
currency: str,
discounts: Optional[Iterable[DiscountInfo]] = None,
-) -> TaxedMoney:
+) -> Money:
line_totals = [
calculate_base_line_total_price(
line,
channel,
discounts,
- ).price_with_sale
+ )
for line in checkout_lines
]
- return sum(line_totals, zero_taxed_money(currency))
-
-
-def base_checkout_line_total(
- checkout_line_info: "CheckoutLineInfo",
- channel: "Channel",
- discounts: Optional[Iterable[DiscountInfo]] = None,
-) -> CheckoutTaxedPricesData:
- """Return the total price of this line."""
- prices_data = calculate_base_line_total_price(
- line_info=checkout_line_info, channel=channel, discounts=discounts
- )
- return CheckoutTaxedPricesData(
- price_with_sale=TaxedMoney(
- net=prices_data.price_with_sale, gross=prices_data.price_with_sale
- ),
- price_with_discounts=TaxedMoney(
- net=prices_data.price_with_discounts, gross=prices_data.price_with_discounts
- ),
- undiscounted_price=TaxedMoney(
- net=prices_data.undiscounted_price, gross=prices_data.undiscounted_price
- ),
- )
+ return sum(line_totals, zero_money(currency))
def base_order_line_total(order_line: "OrderLine") -> OrderTaxedPricesData:
@@ -309,24 +241,3 @@ def base_tax_rate(price: TaxedMoney):
if not isinstance(price, Decimal) and all((price.gross, price.net)):
tax_rate = price.tax / price.net
return tax_rate
-
-
-def base_checkout_line_unit_price(
- checkout_line_info: "CheckoutLineInfo",
- channel: "Channel",
- discounts: Optional[Iterable[DiscountInfo]] = None,
-):
- prices_data = calculate_base_line_unit_price(
- line_info=checkout_line_info, channel=channel, discounts=discounts
- )
- return CheckoutTaxedPricesData(
- price_with_sale=TaxedMoney(
- net=prices_data.price_with_sale, gross=prices_data.price_with_sale
- ),
- price_with_discounts=TaxedMoney(
- net=prices_data.price_with_discounts, gross=prices_data.price_with_discounts
- ),
- undiscounted_price=TaxedMoney(
- net=prices_data.undiscounted_price, gross=prices_data.undiscounted_price
- ),
- )
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 16a9e0b3fb..94bbc837af 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -1,12 +1,16 @@
-from typing import TYPE_CHECKING, Iterable, Optional
+from decimal import Decimal
+from typing import TYPE_CHECKING, Iterable, Optional, Tuple
+
+from django.conf import settings
+from django.utils import timezone
+from prices import Money, TaxedMoney
from ..core.prices import quantize_price
-from ..core.taxes import zero_taxed_money
+from ..core.taxes import TaxData, zero_taxed_money
from ..discount import DiscountInfo
-from .interface import CheckoutTaxedPricesData
+from .models import Checkout
if TYPE_CHECKING:
- from prices import TaxedMoney
from ..account.models import Address
from ..plugins.manager import PluginsManager
@@ -25,10 +29,37 @@ def checkout_shipping_price(
It takes in account all plugins.
"""
- calculated_checkout_shipping = manager.calculate_checkout_shipping(
- checkout_info, lines, address, discounts or []
+ currency = checkout_info.checkout.currency
+ checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
)
- return quantize_price(calculated_checkout_shipping, checkout_info.checkout.currency)
+ return quantize_price(checkout_info.checkout.shipping_price, currency)
+
+
+def checkout_shipping_tax_rate(
+ *,
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+) -> Decimal:
+ """Return checkout shipping tax rate.
+
+ It takes in account all plugins.
+ """
+ checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ return checkout_info.checkout.shipping_tax_rate
def checkout_subtotal(
@@ -43,10 +74,15 @@ def checkout_subtotal(
It takes in account all plugins.
"""
- calculated_checkout_subtotal = manager.calculate_checkout_subtotal(
- checkout_info, lines, address, discounts or []
+ currency = checkout_info.checkout.currency
+ checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
)
- return quantize_price(calculated_checkout_subtotal, checkout_info.checkout.currency)
+ return quantize_price(checkout_info.checkout.subtotal, currency)
def calculate_checkout_total_with_gift_cards(
@@ -85,10 +121,30 @@ def checkout_total(
It takes in account all plugins.
"""
- calculated_checkout_total = manager.calculate_checkout_total(
- checkout_info, lines, address, discounts or []
+ currency = checkout_info.checkout.currency
+ checkout_info, _ = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ return quantize_price(checkout_info.checkout.total, currency)
+
+
+def _find_checkout_line_info(
+ lines: Iterable["CheckoutLineInfo"],
+ checkout_line_info: "CheckoutLineInfo",
+) -> "CheckoutLineInfo":
+ """Return checkout line info from lines parameter.
+
+ The return value represents the updated version of checkout_line_info parameter.
+ """
+ return next(
+ line_info
+ for line_info in lines
+ if line_info.line.pk == checkout_line_info.line.pk
)
- return quantize_price(calculated_checkout_total, checkout_info.checkout.currency)
def checkout_line_total(
@@ -98,17 +154,239 @@ def checkout_line_total(
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
discounts: Iterable[DiscountInfo] = [],
-) -> "CheckoutTaxedPricesData":
+) -> TaxedMoney:
"""Return the total price of provided line, taxes included.
+ It takes in account all plugins.
+ """
+ currency = checkout_info.checkout.currency
+ address = checkout_info.shipping_address or checkout_info.billing_address
+ _, lines = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ checkout_line = _find_checkout_line_info(lines, checkout_line_info).line
+ return quantize_price(checkout_line.total_price, currency)
+
+
+def checkout_line_unit_price(
+ *,
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ checkout_line_info: "CheckoutLineInfo",
+ discounts: Iterable[DiscountInfo],
+) -> TaxedMoney:
+ """Return the unit price of provided line, taxes included.
+
+ It takes in account all plugins.
+ """
+ currency = checkout_info.checkout.currency
+ address = checkout_info.shipping_address or checkout_info.billing_address
+ _, lines = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ checkout_line = _find_checkout_line_info(lines, checkout_line_info).line
+ unit_price = checkout_line.total_price / checkout_line.quantity
+ return quantize_price(unit_price, currency)
+
+
+def checkout_line_tax_rate(
+ *,
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ checkout_line_info: "CheckoutLineInfo",
+ discounts: Iterable[DiscountInfo],
+) -> Decimal:
+ """Return the tax rate of provided line.
+
It takes in account all plugins.
"""
address = checkout_info.shipping_address or checkout_info.billing_address
- calculated_line_total = manager.calculate_checkout_line_total(
+ _, lines = fetch_checkout_prices_if_expired(
+ checkout_info,
+ manager=manager,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ checkout_line_info = _find_checkout_line_info(lines, checkout_line_info)
+ return checkout_line_info.line.tax_rate
+
+
+def fetch_checkout_prices_if_expired(
+ checkout_info: "CheckoutInfo",
+ manager: "PluginsManager",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"] = None,
+ discounts: Optional[Iterable["DiscountInfo"]] = None,
+ force_update: bool = False,
+) -> Tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:
+ """Fetch checkout prices with taxes.
+
+ First calculate and apply all checkout prices with taxes separately,
+ then apply tax data as well if we receive one.
+
+ Prices can be updated only if force_update == True, or if time elapsed from the
+ last price update is greater than settings.CHECKOUT_PRICES_TTL.
+ """
+ checkout = checkout_info.checkout
+ if not force_update and checkout.price_expiration > timezone.now():
+ return checkout_info, lines
+
+ # Taxes are applied to the discounted prices
+ _apply_tax_data_from_plugins(
+ checkout, manager, checkout_info, lines, address, discounts
+ )
+
+ tax_data = manager.get_taxes_for_checkout(
checkout_info,
lines,
- checkout_line_info,
- address,
- discounts or [],
)
- return calculated_line_total
+ if tax_data:
+ _apply_tax_data_from_app(checkout, lines, tax_data)
+
+ checkout.price_expiration = (
+ timezone.now() + settings.CHECKOUT_PRICES_TTL # type: ignore
+ )
+ checkout.save(
+ update_fields=[
+ "voucher_code",
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_tax_rate",
+ "price_expiration",
+ "translated_discount_name",
+ "discount_amount",
+ "discount_name",
+ "currency",
+ ],
+ using=settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ )
+
+ checkout.lines.bulk_update(
+ [line_info.line for line_info in lines],
+ [
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ "tax_rate",
+ ],
+ )
+
+ return checkout_info, lines
+
+
+def _calculate_checkout_total(checkout, currency):
+ total = checkout.subtotal + checkout.shipping_price
+ return quantize_price(
+ total,
+ currency,
+ )
+
+
+def _calculate_checkout_subtotal(lines, currency):
+ line_totals = [line_info.line.total_price for line_info in lines]
+ total = sum(line_totals, zero_taxed_money(currency))
+ return quantize_price(
+ total,
+ currency,
+ )
+
+
+def _apply_tax_data_from_app(
+ checkout: "Checkout", lines: Iterable["CheckoutLineInfo"], tax_data: TaxData
+) -> None:
+ currency = checkout.currency
+ for (line_info, tax_line_data) in zip(lines, tax_data.lines):
+ line = line_info.line
+
+ line.total_price = quantize_price(
+ TaxedMoney(
+ net=Money(tax_line_data.total_net_amount, currency),
+ gross=Money(tax_line_data.total_gross_amount, currency),
+ ),
+ currency,
+ )
+ # We use % value in tax app input but on database we store
+ # it as a fractional value.
+ # e.g Tax app sends `10%` as `10` but in database it's stored as `0.1`
+ line.tax_rate = tax_line_data.tax_rate / 100
+
+ # We use % value in tax app input but on database we store it as a fractional value.
+ # e.g Tax app sends `10%` as `10` but in database it's stored as `0.1`
+ checkout.shipping_tax_rate = tax_data.shipping_tax_rate / 100
+ checkout.shipping_price = quantize_price(
+ TaxedMoney(
+ net=Money(tax_data.shipping_price_net_amount, currency),
+ gross=Money(tax_data.shipping_price_gross_amount, currency),
+ ),
+ currency,
+ )
+ checkout.subtotal = _calculate_checkout_subtotal(lines, currency)
+ checkout.total = _calculate_checkout_total(checkout, currency)
+
+
+def _apply_tax_data_from_plugins(
+ checkout: "Checkout",
+ manager: "PluginsManager",
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ address: Optional["Address"],
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+) -> None:
+ if not discounts:
+ discounts = []
+
+ for line_info in lines:
+ line = line_info.line
+
+ total_price = manager.calculate_checkout_line_total(
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ )
+ line.total_price = total_price
+
+ unit_price = manager.calculate_checkout_line_unit_price(
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ )
+
+ line.tax_rate = manager.get_checkout_line_tax_rate(
+ checkout_info,
+ lines,
+ line_info,
+ address,
+ discounts,
+ unit_price,
+ )
+
+ checkout.shipping_price = manager.calculate_checkout_shipping(
+ checkout_info, lines, address, discounts
+ )
+ checkout.shipping_tax_rate = manager.get_checkout_shipping_tax_rate(
+ checkout_info, lines, address, discounts, checkout.shipping_price
+ )
+ checkout.subtotal = manager.calculate_checkout_subtotal(
+ checkout_info, lines, address, discounts
+ )
+ checkout.total = manager.calculate_checkout_total(
+ checkout_info, lines, address, discounts
+ )
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 3bd711fd7e..55548795a9 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -53,7 +53,12 @@ from ..warehouse.availability import check_stock_and_preorder_quantity_bulk
from ..warehouse.management import allocate_preorders, allocate_stocks
from ..warehouse.reservations import is_reservation_enabled
from . import AddressType
-from .base_calculations import calculate_base_line_unit_price
+from .base_calculations import (
+ calculate_base_line_unit_price,
+ calculate_undiscounted_base_line_total_price,
+ calculate_undiscounted_base_line_unit_price,
+)
+from .calculations import fetch_checkout_prices_if_expired
from .checkout_cleaner import (
_validate_gift_cards,
clean_checkout_payment,
@@ -164,9 +169,6 @@ def _create_line_for_order(
quantity = checkout_line.quantity
variant = checkout_line_info.variant
product = checkout_line_info.product
- address = (
- checkout_info.shipping_address or checkout_info.billing_address
- ) # FIXME: check which address we need here
product_name = str(product)
variant_name = str(variant)
@@ -180,30 +182,43 @@ def _create_line_for_order(
if translated_variant_name == variant_name:
translated_variant_name = ""
- base_prices_data = calculate_base_line_unit_price(
+ base_unit_price = calculate_base_line_unit_price(
line_info=checkout_line_info, channel=checkout_info.channel, discounts=discounts
)
- total_line_price_data = manager.calculate_checkout_line_total(
- checkout_info,
- lines,
- checkout_line_info,
- address,
- discounts,
+ undiscounted_base_unit_price = calculate_undiscounted_base_line_unit_price(
+ line_info=checkout_line_info,
+ channel=checkout_info.channel,
)
- unit_price_data = manager.calculate_checkout_line_unit_price(
- checkout_info,
- lines,
- checkout_line_info,
- address,
- discounts,
+ undiscounted_base_total_price = calculate_undiscounted_base_line_total_price(
+ line_info=checkout_line_info,
+ channel=checkout_info.channel,
)
- tax_rate = manager.get_checkout_line_tax_rate(
- checkout_info,
- lines,
- checkout_line_info,
- address,
- discounts,
- unit_price_data.price_with_sale,
+ undiscounted_unit_price = TaxedMoney(
+ net=undiscounted_base_unit_price, gross=undiscounted_base_unit_price
+ )
+ undiscounted_total_price = TaxedMoney(
+ net=undiscounted_base_total_price, gross=undiscounted_base_total_price
+ )
+ total_line_price = calculations.checkout_line_total(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=checkout_line_info,
+ discounts=discounts,
+ )
+ unit_price = calculations.checkout_line_unit_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=checkout_line_info,
+ discounts=discounts,
+ )
+ tax_rate = calculations.checkout_line_tax_rate(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=checkout_line_info,
+ discounts=discounts,
)
price_override = checkout_line_info.line.price_override
@@ -226,13 +241,11 @@ def _create_line_for_order(
if checkout_line_info.voucher:
voucher_code = checkout_line_info.voucher.code
- discount_price_data = (
- unit_price_data.undiscounted_price - unit_price_data.price_with_discounts
- )
+ discount_price = undiscounted_unit_price - unit_price
if taxes_included_in_prices:
- discount_amount = discount_price_data.gross
+ discount_amount = discount_price.gross
else:
- discount_amount = discount_price_data.net
+ discount_amount = discount_price.net
unit_discount_reason = None
if sale_id:
@@ -254,20 +267,18 @@ def _create_line_for_order(
is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
- unit_price=unit_price_data.price_with_discounts, # type: ignore
- undiscounted_unit_price=unit_price_data.undiscounted_price, # type: ignore
- undiscounted_total_price=(
- total_line_price_data.undiscounted_price # type: ignore
- ),
- total_price=total_line_price_data.price_with_discounts, # type: ignore
+ unit_price=unit_price, # type: ignore
+ undiscounted_unit_price=undiscounted_unit_price, # type: ignore
+ undiscounted_total_price=undiscounted_total_price, # type: ignore
+ total_price=total_line_price, # type: ignore
tax_rate=tax_rate,
sale_id=graphene.Node.to_global_id("Sale", sale_id) if sale_id else None,
voucher_code=voucher_code,
unit_discount=discount_amount, # type: ignore
unit_discount_reason=unit_discount_reason,
unit_discount_value=discount_amount.amount, # we store value as fixed discount
- base_unit_price=base_prices_data.price_with_discounts,
- undiscounted_base_unit_price=base_prices_data.undiscounted_price,
+ base_unit_price=base_unit_price,
+ undiscounted_base_unit_price=undiscounted_base_unit_price,
metadata=checkout_line.metadata,
private_metadata=checkout_line.private_metadata,
)
@@ -373,25 +384,28 @@ def _prepare_order_data(
checkout_info.shipping_address or checkout_info.billing_address
) # FIXME: check which address we need here
- taxed_total = calculations.checkout_total(
+ taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
address=address,
discounts=discounts,
)
- cards_total = 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.currency))
undiscounted_total = taxed_total + checkout.discount
- shipping_total = manager.calculate_checkout_shipping(
- checkout_info, lines, address, discounts
+ shipping_total = calculations.checkout_shipping_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
)
- shipping_tax_rate = manager.get_checkout_shipping_tax_rate(
- checkout_info, lines, address, discounts, shipping_total
+ shipping_tax_rate = calculations.checkout_shipping_tax_rate(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
)
order_data.update(
_process_shipping_data_for_order(checkout_info, shipping_total, manager, lines)
@@ -422,7 +436,13 @@ def _prepare_order_data(
order_data.update(_process_voucher_data_for_order(checkout_info))
order_data["total_price_left"] = (
- manager.calculate_checkout_subtotal(checkout_info, lines, address, discounts)
+ calculations.checkout_subtotal(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
+ )
+ shipping_total
- checkout.discount
).gross
@@ -717,6 +737,9 @@ def complete_checkout(
for thread race.
:raises ValidationError
"""
+
+ fetch_checkout_prices_if_expired(checkout_info, manager, lines, discounts)
+
checkout = checkout_info.checkout
channel_slug = checkout_info.channel.slug
payment = checkout.get_last_active_payment()
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 0dfccdfbf5..9eaf6836d6 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -216,20 +216,22 @@ def fetch_checkout_lines(
"""Fetch checkout lines as CheckoutLineInfo objects."""
from .utils import get_voucher_for_checkout
- prefetched_fields = [
+ select_related_fields = ["variant__product__product_type"]
+ prefetch_related_fields = [
"variant__product__collections",
"variant__product__channel_listings__channel",
"variant__channel_listings__channel",
- "variant__product__product_type",
]
if prefetch_variant_attributes:
- prefetched_fields.extend(
+ prefetch_related_fields.extend(
[
"variant__attributes__assignment__attribute",
"variant__attributes__values",
]
)
- lines = checkout.lines.prefetch_related(*prefetched_fields)
+ lines = checkout.lines.select_related(*select_related_fields).prefetch_related(
+ *prefetch_related_fields
+ )
lines_info = []
unavailable_variant_pks = []
product_channel_listing_mapping: Dict[int, Optional["ProductChannelListing"]] = {}
@@ -490,7 +492,7 @@ def get_valid_internal_shipping_method_list_for_checkout_info(
country_code = shipping_address.country.code if shipping_address else None
- subtotal = base_calculations.base_checkout_lines_total(
+ subtotal = base_calculations.base_checkout_subtotal(
lines,
checkout_info.channel,
checkout_info.checkout.currency,
diff --git a/saleor/checkout/interface.py b/saleor/checkout/interface.py
deleted file mode 100644
index a09fb4a935..0000000000
--- a/saleor/checkout/interface.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from dataclasses import dataclass
-
-from prices import Money, TaxedMoney
-
-
-@dataclass
-class CheckoutTaxedPricesData:
- """Store a checkout prices data with applied taxes.
-
- 'price_with_sale' includes discount from sale if any valid exists.
- 'price_with_discounts' includes voucher discount and sale discount if any valid
- exists.
- 'undiscounted_price' is a price without any sale and voucher.
- """
-
- undiscounted_price: TaxedMoney
- price_with_discounts: TaxedMoney
- price_with_sale: TaxedMoney
-
-
-@dataclass
-class CheckoutPricesData:
- """Store a checkout prices data without applied taxes.
-
- 'price_with_sale' includes discount from sale if any valid exists.
- 'price_with_discounts' includes voucher discount and sale discount if any valid
- exists.
- 'undiscounted_price' is a price without any sale and voucher.
- """
-
- undiscounted_price: Money
- price_with_discounts: Money
- price_with_sale: Money
diff --git a/saleor/checkout/migrations/0050_auto_20220713_1057.py b/saleor/checkout/migrations/0050_auto_20220713_1057.py
new file mode 100644
index 0000000000..47409e0491
--- /dev/null
+++ b/saleor/checkout/migrations/0050_auto_20220713_1057.py
@@ -0,0 +1,106 @@
+# Generated by Django 3.2.14 on 2022-07-13 10:57
+
+from decimal import Decimal
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0049_auto_20220621_0850"),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name="checkout",
+ options={
+ "ordering": ("-last_change", "pk"),
+ "permissions": (
+ ("manage_checkouts", "Manage checkouts"),
+ ("handle_checkouts", "Handle checkouts"),
+ ("handle_taxes", "Handle taxes"),
+ ),
+ },
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="price_expiration",
+ field=models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="shipping_price_gross_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="shipping_price_net_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="shipping_tax_rate",
+ field=models.DecimalField(
+ decimal_places=4, default=Decimal("0.0"), max_digits=5
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="subtotal_gross_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="subtotal_net_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="total_gross_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkout",
+ name="total_net_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkoutline",
+ name="currency",
+ field=models.CharField(max_length=3, null=True),
+ ),
+ migrations.AddField(
+ model_name="checkoutline",
+ name="tax_rate",
+ field=models.DecimalField(
+ decimal_places=4, default=Decimal("0.0"), max_digits=5
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkoutline",
+ name="total_price_gross_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ migrations.AddField(
+ model_name="checkoutline",
+ name="total_price_net_amount",
+ field=models.DecimalField(
+ decimal_places=3, default=Decimal("0"), max_digits=12
+ ),
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0051_auto_20220713_1103.py b/saleor/checkout/migrations/0051_auto_20220713_1103.py
new file mode 100644
index 0000000000..e0fd3cb9d8
--- /dev/null
+++ b/saleor/checkout/migrations/0051_auto_20220713_1103.py
@@ -0,0 +1,61 @@
+# Generated by Django 3.2.14 on 2022-07-13 11:03
+
+
+from django.db import migrations
+from django.db.models.signals import post_migrate
+from saleor.checkout.app import CheckoutAppConfig
+
+
+def assign_permissions(apps, schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ # The `post_migrate`` signal is sent once for every app migrated
+ # we should execute it only once after update `order` module.
+ if isinstance(sender, CheckoutAppConfig):
+ Permission = apps.get_model("auth", "Permission")
+ App = apps.get_model("app", "App")
+ Group = apps.get_model("auth", "Group")
+
+ handle_taxes = Permission.objects.filter(
+ codename="handle_taxes", content_type__app_label="checkout"
+ ).first()
+ manage_checkouts = Permission.objects.filter(
+ codename="manage_checkouts", content_type__app_label="checkout"
+ ).first()
+
+ apps_qs = App.objects.filter(
+ permissions=manage_checkouts,
+ )
+ for app in apps_qs.iterator():
+ app.permissions.add(handle_taxes)
+
+ groups = Group.objects.filter(
+ permissions=manage_checkouts,
+ )
+ for group in groups.iterator():
+ group.permissions.add(handle_taxes)
+
+ post_migrate.connect(on_migrations_complete, weak=False)
+
+
+def set_default_checkout_line_currency(apps, schema_editor):
+ Checkout = apps.get_model("checkout", "Checkout")
+ CheckoutLine = apps.get_model("checkout", "CheckoutLine")
+
+ for currency in Checkout.objects.values_list("currency", flat=True):
+ CheckoutLine.objects.filter(currency=None, checkout__currency=currency).update(
+ currency=currency
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0050_auto_20220713_1057"),
+ ]
+
+ operations = [
+ migrations.RunPython(assign_permissions, migrations.RunPython.noop),
+ migrations.RunPython(
+ set_default_checkout_line_currency, migrations.RunPython.noop
+ ),
+ ]
diff --git a/saleor/checkout/migrations/0052_alter_checkoutline_currency.py b/saleor/checkout/migrations/0052_alter_checkoutline_currency.py
new file mode 100644
index 0000000000..004b195ea6
--- /dev/null
+++ b/saleor/checkout/migrations/0052_alter_checkoutline_currency.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.14 on 2022-07-13 11:07
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("checkout", "0051_auto_20220713_1103"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="checkoutline",
+ name="currency",
+ field=models.CharField(max_length=3),
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 0d2526a8f5..237f143a69 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -1,5 +1,6 @@
"""Checkout-related ORM models."""
from datetime import date
+from decimal import Decimal
from operator import attrgetter
from typing import TYPE_CHECKING, Iterable, Optional
from uuid import uuid4
@@ -8,9 +9,10 @@ from django.conf import settings
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models.deletion import SET_NULL
+from django.utils import timezone
from django.utils.encoding import smart_str
from django_countries.fields import Country, CountryField
-from django_prices.models import MoneyField
+from django_prices.models import MoneyField, TaxedMoneyField
from prices import Money
from ..channel.models import Channel
@@ -88,6 +90,56 @@ class Checkout(ModelWithMetadata):
)
country = CountryField(default=get_default_country)
+ total_net_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ total_gross_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ total = TaxedMoneyField(
+ net_amount_field="total_net_amount",
+ gross_amount_field="total_gross_amount",
+ )
+
+ subtotal_net_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ subtotal_gross_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ subtotal = TaxedMoneyField(
+ net_amount_field="subtotal_net_amount",
+ gross_amount_field="subtotal_gross_amount",
+ )
+
+ shipping_price_net_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ shipping_price_gross_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ shipping_price = TaxedMoneyField(
+ net_amount_field="shipping_price_net_amount",
+ gross_amount_field="shipping_price_gross_amount",
+ )
+ shipping_tax_rate = models.DecimalField(
+ max_digits=5, decimal_places=4, default=Decimal("0.0")
+ )
+
+ price_expiration = models.DateTimeField(default=timezone.now)
+
discount_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
@@ -112,6 +164,7 @@ class Checkout(ModelWithMetadata):
permissions = (
(CheckoutPermissions.MANAGE_CHECKOUTS.codename, "Manage checkouts"),
(CheckoutPermissions.HANDLE_CHECKOUTS.codename, "Handle checkouts"),
+ (CheckoutPermissions.HANDLE_TAXES.codename, "Handle taxes"),
)
def __iter__(self):
@@ -194,6 +247,27 @@ class CheckoutLine(ModelWithMetadata):
blank=True,
null=True,
)
+ currency = models.CharField(
+ max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
+ )
+
+ total_price_net_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ total_price_gross_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=Decimal(0),
+ )
+ total_price = TaxedMoneyField(
+ net_amount_field="total_price_net_amount",
+ gross_amount_field="total_price_gross_amount",
+ )
+ tax_rate = models.DecimalField(
+ max_digits=5, decimal_places=4, default=Decimal("0.0")
+ )
class Meta(ModelWithMetadata.Meta):
ordering = ("created_at", "id")
diff --git a/saleor/checkout/tests/conftest.py b/saleor/checkout/tests/conftest.py
new file mode 100644
index 0000000000..2a6f99169c
--- /dev/null
+++ b/saleor/checkout/tests/conftest.py
@@ -0,0 +1,75 @@
+from datetime import timedelta
+from decimal import Decimal
+
+import pytest
+from django.utils import timezone
+
+from ...checkout.models import CheckoutLine
+from ...plugins.manager import get_plugins_manager
+from ..fetch import fetch_checkout_info, fetch_checkout_lines
+
+
+def priced_checkout_factory():
+ def factory(checkout):
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+
+ tax = Decimal("1.23")
+
+ lines_to_update = []
+ for line_info in lines:
+ line = line_info.line
+ lines_to_update.append(line)
+
+ line.total_price = manager.calculate_checkout_line_total(
+ checkout_info, lines, line_info, None, []
+ )
+ line.total_price_gross_amount *= tax
+
+ CheckoutLine.objects.bulk_update(
+ lines_to_update,
+ [
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ ],
+ )
+
+ checkout.shipping_price = manager.calculate_checkout_shipping(
+ checkout_info, lines, None, []
+ )
+ checkout.subtotal = manager.calculate_checkout_subtotal(
+ checkout_info, lines, None, []
+ )
+ checkout.total = manager.calculate_checkout_total(
+ checkout_info, lines, None, []
+ )
+
+ checkout.shipping_price_gross_amount *= tax
+ checkout.subtotal_gross_amount *= tax
+ checkout.total_gross_amount *= tax
+ # Cache prices until invalidated by force
+ checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.save()
+
+ return checkout
+
+ return factory
+
+
+def priced_checkout_with_item(priced_checkout_factory, checkout_with_item):
+ return priced_checkout_factory(checkout_with_item)
+
+
+def priced_checkout_with_items(priced_checkout_factory, checkout_with_items):
+ return priced_checkout_factory(checkout_with_items)
+
+
+def priced_checkout_with_voucher_percentage(
+ priced_checkout_factory, checkout_with_voucher_percentage
+):
+ return priced_checkout_factory(checkout_with_voucher_percentage)
diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.py
index 8742f1f4ef..fa038dde03 100644
--- a/saleor/checkout/tests/test_base_calculations.py
+++ b/saleor/checkout/tests/test_base_calculations.py
@@ -22,7 +22,7 @@ def test_calculate_base_line_unit_price(checkout_with_single_item):
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -34,9 +34,7 @@ def test_calculate_base_line_unit_price(checkout_with_single_item):
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price
+ assert unit_price == expected_price
def test_calculate_base_line_unit_price_with_custom_price(checkout_with_single_item):
@@ -51,16 +49,14 @@ def test_calculate_base_line_unit_price_with_custom_price(checkout_with_single_i
assert not checkout_line_info.voucher
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
# then
currency = checkout_line_info.channel_listing.currency
expected_price = Money(price_override, currency)
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price
+ assert unit_price == expected_price
def test_calculate_base_line_unit_price_with_variant_on_sale(
@@ -77,7 +73,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale(
checkout_line_info.product = variant.product
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]
)
@@ -99,9 +95,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale(
)
expected_price = sale_discount(expected_undiscounted_price)
- assert prices_data.undiscounted_price == expected_undiscounted_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price
+ assert unit_price == expected_price
def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(
@@ -123,7 +117,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(
checkout_line_info.product = variant.product
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]
)
@@ -140,9 +134,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(
)
expected_price = sale_discount(expected_undiscounted_price)
- assert prices_data.undiscounted_price == expected_undiscounted_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price
+ assert unit_price == expected_price
def test_calculate_base_line_unit_price_with_fixed_voucher(
@@ -167,7 +159,7 @@ def test_calculate_base_line_unit_price_with_fixed_voucher(
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -179,9 +171,7 @@ def test_calculate_base_line_unit_price_with_fixed_voucher(
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - voucher_amount
+ assert unit_price == expected_price - voucher_amount
def test_calculate_base_line_unit_price_with_fixed_voucher_custom_prices(
@@ -208,16 +198,14 @@ def test_calculate_base_line_unit_price_with_fixed_voucher_custom_prices(
assert checkout_line_info.voucher
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
# then
currency = checkout_line_info.channel_listing.currency
expected_price = Money(price_override, currency)
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - voucher_amount
+ assert unit_price == expected_price - voucher_amount
def test_calculate_base_line_unit_price_with_percentage_voucher(
@@ -243,7 +231,7 @@ def test_calculate_base_line_unit_price_with_percentage_voucher(
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -256,9 +244,7 @@ def test_calculate_base_line_unit_price_with_percentage_voucher(
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - expected_voucher_amount
+ assert unit_price == expected_price - expected_voucher_amount
def test_calculate_base_line_unit_price_with_percentage_voucher_custom_prices(
@@ -286,7 +272,7 @@ def test_calculate_base_line_unit_price_with_percentage_voucher_custom_prices(
assert checkout_line_info.voucher
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -296,9 +282,7 @@ def test_calculate_base_line_unit_price_with_percentage_voucher_custom_prices(
expected_voucher_amount = Money(
price_override * voucher_percent_value / 100, checkout_with_single_item.currency
)
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - expected_voucher_amount
+ assert unit_price == expected_price - expected_voucher_amount
def test_calculate_base_line_unit_price_with_discounts_apply_once_per_order(
@@ -325,7 +309,7 @@ def test_calculate_base_line_unit_price_with_discounts_apply_once_per_order(
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -338,9 +322,7 @@ def test_calculate_base_line_unit_price_with_discounts_apply_once_per_order(
discounts=[],
)
expected_voucher_amount = expected_price * voucher_percent_value / 100
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - expected_voucher_amount
+ assert unit_price == expected_price - expected_voucher_amount
def test_calculate_base_line_unit_price_with_discounts_once_per_order_custom_prices(
@@ -369,7 +351,7 @@ def test_calculate_base_line_unit_price_with_discounts_once_per_order_custom_pri
assert checkout_line_info.voucher
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -377,9 +359,7 @@ def test_calculate_base_line_unit_price_with_discounts_once_per_order_custom_pri
currency = checkout_line_info.channel_listing.currency
expected_price = Money(price_override, currency)
expected_voucher_amount = expected_price * voucher_percent_value / 100
- assert prices_data.undiscounted_price == expected_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - expected_voucher_amount
+ assert unit_price == expected_price - expected_voucher_amount
def test_calculate_base_line_unit_price_with_variant_on_sale_and_voucher(
@@ -406,7 +386,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_and_voucher(
checkout_line_info.product = variant.product
# when
- prices_data = calculate_base_line_unit_price(
+ unit_price = calculate_base_line_unit_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]
)
@@ -429,9 +409,7 @@ def test_calculate_base_line_unit_price_with_variant_on_sale_and_voucher(
sale_discount_amount = sale_discount(expected_undiscounted_price)
expected_price = expected_undiscounted_price - sale_discount_amount
- assert prices_data.undiscounted_price == expected_undiscounted_price
- assert prices_data.price_with_sale == expected_price
- assert prices_data.price_with_discounts == expected_price - voucher_amount
+ assert unit_price == expected_price - voucher_amount
def test_calculate_base_line_total_price(checkout_with_single_item):
@@ -447,7 +425,7 @@ def test_calculate_base_line_total_price(checkout_with_single_item):
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -459,9 +437,7 @@ def test_calculate_base_line_total_price(checkout_with_single_item):
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_price * quantity
- assert prices_data.price_with_sale == expected_price * quantity
- assert prices_data.price_with_discounts == expected_price * quantity
+ assert total_price == expected_price * quantity
def test_calculate_base_line_total_price_with_variant_on_sale(
@@ -483,7 +459,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale(
checkout_line_info.product = variant.product
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]
)
@@ -506,9 +482,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale(
sale_discount_amount = sale_discount(expected_undiscounted_unit_price)
expected_price = expected_undiscounted_unit_price - sale_discount_amount
- assert prices_data.undiscounted_price == expected_undiscounted_unit_price * quantity
- assert prices_data.price_with_sale == expected_price * quantity
- assert prices_data.price_with_discounts == expected_price * quantity
+ assert total_price == expected_price * quantity
def test_calculate_base_line_total_price_with_fixed_voucher(
@@ -538,7 +512,7 @@ def test_calculate_base_line_total_price_with_fixed_voucher(
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -550,12 +524,7 @@ def test_calculate_base_line_total_price_with_fixed_voucher(
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_unit_price * quantity
- assert prices_data.price_with_sale == expected_unit_price * quantity
- assert (
- prices_data.price_with_discounts
- == (expected_unit_price - voucher_amount) * quantity
- )
+ assert total_price == (expected_unit_price - voucher_amount) * quantity
def test_calculate_base_line_total_price_with_percentage_voucher(
@@ -586,7 +555,7 @@ def test_calculate_base_line_total_price_with_percentage_voucher(
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -599,12 +568,7 @@ def test_calculate_base_line_total_price_with_percentage_voucher(
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_unit_price * quantity
- assert prices_data.price_with_sale == expected_unit_price * quantity
- assert (
- prices_data.price_with_discounts
- == (expected_unit_price - expected_voucher_amount) * quantity
- )
+ assert total_price == (expected_unit_price - expected_voucher_amount) * quantity
def test_calculate_base_line_total_price_with_discounts_apply_once_per_order(
@@ -636,7 +600,7 @@ def test_calculate_base_line_total_price_with_discounts_apply_once_per_order(
variant = checkout_line_info.variant
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[]
)
@@ -649,13 +613,8 @@ def test_calculate_base_line_total_price_with_discounts_apply_once_per_order(
channel_listing=checkout_line_info.channel_listing,
discounts=[],
)
- assert prices_data.undiscounted_price == expected_unit_price * quantity
- assert prices_data.price_with_sale == expected_unit_price * quantity
# apply once per order is applied when calculating line total.
- assert (
- prices_data.price_with_discounts
- == (expected_unit_price * quantity) - expected_voucher_amount
- )
+ assert total_price == (expected_unit_price * quantity) - expected_voucher_amount
def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(
@@ -690,7 +649,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(
checkout_line_info.product = variant.product
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]
)
@@ -713,12 +672,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher(
sale_discount_amount = sale_discount(expected_undiscounted_unit_price)
expected_unit_price = expected_undiscounted_unit_price - sale_discount_amount
- assert prices_data.undiscounted_price == expected_undiscounted_unit_price * quantity
- assert prices_data.price_with_sale == expected_unit_price * quantity
- assert (
- prices_data.price_with_discounts
- == (expected_unit_price - voucher_amount) * quantity
- )
+ assert total_price == (expected_unit_price - voucher_amount) * quantity
def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher_applied_once(
@@ -754,7 +708,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher_applie
checkout_line_info.product = variant.product
# when
- prices_data = calculate_base_line_total_price(
+ total_price = calculate_base_line_total_price(
checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]
)
@@ -777,12 +731,7 @@ def test_calculate_base_line_total_price_with_variant_on_sale_and_voucher_applie
sale_discount_amount = sale_discount(expected_undiscounted_unit_price)
expected_unit_price = expected_undiscounted_unit_price - sale_discount_amount
- assert prices_data.undiscounted_price == expected_undiscounted_unit_price * quantity
- assert prices_data.price_with_sale == expected_unit_price * quantity
- assert (
- prices_data.price_with_discounts
- == (expected_unit_price * quantity) - voucher_amount
- )
+ assert total_price == (expected_unit_price * quantity) - voucher_amount
def test_base_tax_rate_net_price_zero():
@@ -821,7 +770,7 @@ def test_base_checkout_total(checkout_with_item, shipping_method, voucher_percen
+ shipping_channel_listings.price
- discount_amount
)
- assert total == TaxedMoney(net=expected_price, gross=expected_price)
+ assert total == expected_price
def test_base_checkout_total_high_discount_on_entire_order(
@@ -829,8 +778,8 @@ def test_base_checkout_total_high_discount_on_entire_order(
):
# given
manager = get_plugins_manager()
-
currency = checkout_with_item.currency
+
discount_amount = Money(100, currency)
checkout_with_item.shipping_method = shipping_method
checkout_with_item.voucher_code = voucher_percentage.code
@@ -848,7 +797,7 @@ def test_base_checkout_total_high_discount_on_entire_order(
total = base_checkout_total(checkout_info, [], checkout_lines)
# then
- assert total == TaxedMoney(gross=shipping_price, net=shipping_price)
+ assert total == shipping_price
def test_base_checkout_total_high_discount_on_shipping(
@@ -877,4 +826,4 @@ def test_base_checkout_total_high_discount_on_shipping(
channel_listing = variant.channel_listings.get(channel=channel)
net = variant.get_price(variant.product, [], channel, channel_listing)
expected_price = net * checkout_with_item.lines.first().quantity
- assert total == TaxedMoney(net=expected_price, gross=expected_price)
+ assert total == expected_price
diff --git a/saleor/checkout/tests/test_calculations.py b/saleor/checkout/tests/test_calculations.py
new file mode 100644
index 0000000000..81f4f88238
--- /dev/null
+++ b/saleor/checkout/tests/test_calculations.py
@@ -0,0 +1,201 @@
+from decimal import Decimal
+from typing import Literal, Union
+from unittest.mock import Mock, patch
+
+import pytest
+from django.utils import timezone
+from freezegun import freeze_time
+from prices import Money, TaxedMoney
+
+from ...core.prices import quantize_price
+from ...core.taxes import TaxData, TaxLineData, zero_taxed_money
+from ..calculations import _apply_tax_data_from_app, fetch_checkout_prices_if_expired
+from ..fetch import CheckoutLineInfo, fetch_checkout_info, fetch_checkout_lines
+
+
+def checkout_lines(checkout_with_items):
+ return checkout_with_items.lines.all()
+
+
+def tax_data(checkout_with_items, checkout_lines):
+ checkout = checkout_with_items
+ tax_rate = Decimal("23")
+ net = Decimal("10.000")
+ gross = Decimal("12.300")
+ lines = checkout_lines
+ return TaxData(
+ shipping_price_net_amount=checkout.shipping_price.net.amount + net,
+ shipping_price_gross_amount=checkout.shipping_price.gross.amount + gross,
+ shipping_tax_rate=tax_rate,
+ lines=[
+ TaxLineData(
+ total_net_amount=line.total_price.net.amount + net,
+ total_gross_amount=line.total_price.gross.amount + gross,
+ tax_rate=tax_rate,
+ )
+ for line in lines
+ ],
+ )
+
+
+def test_apply_tax_data(checkout_with_items, checkout_lines, tax_data):
+ # given
+ checkout = checkout_with_items
+ lines = checkout_lines
+
+ # when
+ _apply_tax_data_from_app(
+ checkout,
+ [
+ Mock(spec=CheckoutLineInfo, line=line, variant=line.variant)
+ for line in lines
+ ],
+ tax_data,
+ )
+
+ # then
+ assert str(checkout.shipping_price.net.amount) == str(
+ quantize_price(tax_data.shipping_price_net_amount, checkout.currency)
+ )
+ assert str(checkout.shipping_price.gross.amount) == str(
+ quantize_price(tax_data.shipping_price_gross_amount, checkout.currency)
+ )
+
+ for line, tax_line in zip(lines, tax_data.lines):
+ assert str(line.total_price.net.amount) == str(
+ quantize_price(tax_line.total_net_amount, checkout.currency)
+ )
+ assert str(line.total_price.gross.amount) == str(
+ quantize_price(tax_line.total_gross_amount, checkout.currency)
+ )
+
+
+def fetch_kwargs(checkout_with_items, plugins_manager):
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ discounts = []
+ return {
+ "checkout_info": fetch_checkout_info(
+ checkout_with_items, lines, discounts, plugins_manager
+ ),
+ "manager": plugins_manager,
+ "lines": lines,
+ "address": checkout_with_items.shipping_address
+ or checkout_with_items.billing_address,
+ "discounts": discounts,
+ }
+
+
+SALE = Decimal("1.0")
+DISCOUNT = Decimal("1.5")
+
+
+def get_checkout_taxed_prices_data(
+ obj: Union[TaxData, TaxLineData],
+ attr: Literal["total", "shipping_price"],
+ currency: str,
+) -> TaxedMoney:
+ money = TaxedMoney(
+ Money(getattr(obj, f"{attr}_net_amount"), currency),
+ Money(getattr(obj, f"{attr}_gross_amount"), currency),
+ )
+ return money
+
+
+def get_taxed_money(
+ obj: Union[TaxData, TaxLineData],
+ attr: Literal["total", "shipping_price"],
+ currency: str,
+) -> TaxedMoney:
+ return TaxedMoney(
+ Money(getattr(obj, f"{attr}_net_amount"), currency),
+ Money(getattr(obj, f"{attr}_gross_amount"), currency),
+ )
+
+
+@freeze_time("2020-12-12 12:00:00")
+@patch("saleor.checkout.calculations._apply_tax_data_from_app")
+def test_fetch_checkout_prices_if_expired_plugins(
+ _mocked_from_app,
+ plugins_manager,
+ fetch_kwargs,
+ checkout_with_items,
+ tax_data,
+):
+ # given
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+ currency = checkout_with_items.currency
+ plugins_manager.get_taxes_for_checkout = Mock(return_value=None)
+
+ totals, tax_rates = zip(
+ *[
+ (
+ get_checkout_taxed_prices_data(line, "total", currency),
+ line.tax_rate / 100,
+ )
+ for line in tax_data.lines
+ ]
+ )
+ plugins_manager.calculate_checkout_line_total = Mock(side_effect=totals * 3)
+ plugins_manager.get_checkout_line_tax_rate = Mock(side_effect=tax_rates)
+
+ shipping_price = get_taxed_money(tax_data, "shipping_price", currency)
+ plugins_manager.calculate_checkout_shipping = Mock(return_value=shipping_price)
+
+ shipping_tax_rate = tax_data.shipping_tax_rate / 100
+ plugins_manager.get_checkout_shipping_tax_rate = Mock(
+ return_value=shipping_tax_rate
+ )
+
+ subtotal = zero_taxed_money(currency)
+ for tax_line in tax_data.lines:
+ total_price = get_taxed_money(tax_line, "total", currency)
+ subtotal = subtotal + total_price
+ plugins_manager.calculate_checkout_total = Mock(
+ return_value=shipping_price + subtotal
+ )
+
+ # when
+ fetch_checkout_prices_if_expired(**fetch_kwargs)
+
+ # then
+ checkout_with_items.refresh_from_db()
+ for checkout_line, tax_line in zip(checkout_with_items.lines.all(), tax_data.lines):
+ total_price = get_taxed_money(tax_line, "total", currency)
+ assert checkout_line.total_price == total_price
+ assert checkout_line.tax_rate == tax_line.tax_rate / 100
+
+ assert checkout_with_items.subtotal == subtotal
+ assert checkout_with_items.shipping_price == shipping_price
+ assert checkout_with_items.shipping_tax_rate == shipping_tax_rate
+ assert checkout_with_items.total == subtotal + shipping_price
+
+
+@freeze_time("2020-12-12 12:00:00")
+def test_fetch_checkout_prices_if_expired_webhooks_success(
+ plugins_manager,
+ fetch_kwargs,
+ checkout_with_items,
+ tax_data,
+):
+ # given
+ checkout_with_items.price_expiration = timezone.now()
+ checkout_with_items.save(update_fields=["price_expiration"])
+ currency = checkout_with_items.currency
+ plugins_manager.get_taxes_for_checkout = Mock(return_value=tax_data)
+
+ # when
+ fetch_checkout_prices_if_expired(**fetch_kwargs)
+
+ # then
+ checkout_with_items.refresh_from_db()
+ assert checkout_with_items.shipping_price == get_taxed_money(
+ tax_data, "shipping_price", currency
+ )
+ assert checkout_with_items.shipping_tax_rate == tax_data.shipping_tax_rate / 100
+ for checkout_line, tax_line in zip(checkout_with_items.lines.all(), tax_data.lines):
+ assert checkout_line.total_price == get_taxed_money(tax_line, "total", currency)
+ assert checkout_line.tax_rate == tax_line.tax_rate / 100
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 2dc99f6500..3eb580b175 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -1,4 +1,7 @@
+from datetime import timedelta
+
import pytest
+from django.utils import timezone
from measurement.measures import Weight
from prices import Money, TaxedMoney
@@ -88,9 +91,11 @@ def test_shipping_detection(checkout, product):
def test_get_prices_of_discounted_specific_product(
- checkout_with_item, collection, voucher_specific_product_type
+ priced_checkout_with_item,
+ collection,
+ voucher_specific_product_type,
):
- checkout = checkout_with_item
+ checkout = priced_checkout_with_item
voucher = voucher_specific_product_type
line = checkout.lines.first()
product = line.variant.product
@@ -110,20 +115,22 @@ def test_get_prices_of_discounted_specific_product(
manager, checkout_info, lines, voucher
)
- excepted_value = [
+ expected_value = [
line.variant.get_price(
product, [collection], channel, variant_channel_listing, []
)
for item in range(line.quantity)
]
- assert prices == excepted_value
+ assert prices == expected_value
def test_get_prices_of_discounted_specific_product_only_product(
- checkout_with_item, voucher_specific_product_type, product_with_default_variant
+ priced_checkout_with_item,
+ voucher_specific_product_type,
+ product_with_default_variant,
):
- checkout = checkout_with_item
+ checkout = priced_checkout_with_item
voucher = voucher_specific_product_type
line = checkout.lines.first()
product = line.variant.product
@@ -135,28 +142,31 @@ def test_get_prices_of_discounted_specific_product_only_product(
checkout_info = fetch_checkout_info(checkout, [], [], manager)
add_variant_to_checkout(checkout_info, product2.variants.get(), 1)
voucher.products.add(product)
+ # assume that cache is correct
+ checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.save()
lines, _ = fetch_checkout_lines(checkout)
prices = utils.get_prices_of_discounted_specific_product(
manager, checkout_info, lines, voucher
)
- excepted_value = [
+ expected_value = [
line.variant.get_price(product, [], channel, variant_channel_listing, [])
for item in range(line.quantity)
]
assert checkout.lines.count() > 1
- assert prices == excepted_value
+ assert prices == expected_value
def test_get_prices_of_discounted_specific_product_only_collection(
- checkout_with_item,
+ priced_checkout_with_item,
collection,
voucher_specific_product_type,
product_with_default_variant,
):
- checkout = checkout_with_item
+ checkout = priced_checkout_with_item
voucher = voucher_specific_product_type
line = checkout.lines.first()
product = line.variant.product
@@ -169,13 +179,16 @@ def test_get_prices_of_discounted_specific_product_only_collection(
add_variant_to_checkout(checkout_info, product2.variants.get(), 1)
product.collections.add(collection)
voucher.collections.add(collection)
+ # assume that cache is correct
+ checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.save()
lines, _ = fetch_checkout_lines(checkout)
prices = utils.get_prices_of_discounted_specific_product(
manager, checkout_info, lines, voucher
)
- excepted_value = [
+ expected_value = [
line.variant.get_price(
product, [collection], channel, variant_channel_listing, []
)
@@ -183,13 +196,15 @@ def test_get_prices_of_discounted_specific_product_only_collection(
]
assert checkout.lines.count() > 1
- assert prices == excepted_value
+ assert prices == expected_value
def test_get_prices_of_discounted_specific_product_only_category(
- checkout_with_item, voucher_specific_product_type, product_with_default_variant
+ priced_checkout_with_item,
+ voucher_specific_product_type,
+ product_with_default_variant,
):
- checkout = checkout_with_item
+ checkout = priced_checkout_with_item
voucher = voucher_specific_product_type
line = checkout.lines.first()
product = line.variant.product
@@ -205,25 +220,29 @@ def test_get_prices_of_discounted_specific_product_only_category(
checkout_info = fetch_checkout_info(checkout, [], [], manager)
add_variant_to_checkout(checkout_info, product2.variants.get(), 1)
voucher.categories.add(category)
+ # assume that cache is correct
+ checkout.price_expiration = timezone.now() + timedelta(days=1)
+ checkout.save()
lines, _ = fetch_checkout_lines(checkout)
prices = utils.get_prices_of_discounted_specific_product(
manager, checkout_info, lines, voucher
)
- excepted_value = [
+ expected_value = [
line.variant.get_price(product, [], channel, variant_channel_listing, [])
for item in range(line.quantity)
]
assert checkout.lines.count() > 1
- assert prices == excepted_value
+ assert prices == expected_value
def test_get_prices_of_discounted_specific_product_all_products(
- checkout_with_item, voucher_specific_product_type
+ priced_checkout_with_item,
+ voucher_specific_product_type,
):
- checkout = checkout_with_item
+ checkout = priced_checkout_with_item
voucher = voucher_specific_product_type
line = checkout.lines.first()
product = line.variant.product
@@ -237,12 +256,12 @@ def test_get_prices_of_discounted_specific_product_all_products(
manager, checkout_info, lines, voucher
)
- excepted_value = [
+ expected_value = [
line.variant.get_price(product, [], channel, variant_channel_listing, [])
for item in range(line.quantity)
]
- assert prices == excepted_value
+ assert prices == expected_value
def test_checkout_line_repr(product, checkout_with_single_item):
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 1b0fc56bfc..3af36684af 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -1,4 +1,5 @@
import datetime
+from decimal import Decimal
from unittest.mock import Mock, patch
import graphene
@@ -17,7 +18,7 @@ from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...shipping.interface import ShippingMethodData
from ...shipping.models import ShippingZone
-from .. import calculations
+from .. import base_calculations, calculations
from ..fetch import (
CheckoutInfo,
CheckoutLineInfo,
@@ -26,7 +27,7 @@ from ..fetch import (
fetch_checkout_lines,
get_delivery_method_info,
)
-from ..models import Checkout
+from ..models import Checkout, CheckoutLine
from ..utils import (
PRIVATE_META_APP_SHIPPING_ID,
add_voucher_to_checkout,
@@ -157,7 +158,7 @@ def test_last_change_update(checkout):
assert checkout.last_change == pytz.utc.localize(frozen_datetime())
-def test_last_change_update_foregin_key(checkout, shipping_method):
+def test_last_change_update_foreign_key(checkout, shipping_method):
with freeze_time(datetime.datetime.now()) as frozen_datetime:
assert checkout.last_change != frozen_datetime()
@@ -171,10 +172,10 @@ def test_last_change_update_foregin_key(checkout, shipping_method):
"total, min_spent_amount, min_checkout_items_quantity, "
"discount_value, discount_value_type, expected_value",
[
- (20, 20, 2, 50, DiscountValueType.PERCENTAGE, 10),
- (20, None, None, 50, DiscountValueType.PERCENTAGE, 10),
- (20, 20, 2, 5, DiscountValueType.FIXED, 5),
- (20, None, None, 5, DiscountValueType.FIXED, 5),
+ (20, 20, 2, 50, DiscountValueType.PERCENTAGE, Decimal("10.00")),
+ (20, None, None, 50, DiscountValueType.PERCENTAGE, Decimal("10.00")),
+ (20, 20, 2, 5, DiscountValueType.FIXED, Decimal("5.00")),
+ (20, None, None, 5, DiscountValueType.FIXED, Decimal("5.00")),
],
)
def test_get_discount_for_checkout_value_voucher(
@@ -201,10 +202,10 @@ def test_get_discount_for_checkout_value_voucher(
min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
)
checkout = Mock(spec=checkout_with_items, channel=channel_USD)
- subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
+ subtotal = Money(total, "USD")
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: subtotal,
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
)
checkout_info = CheckoutInfo(
checkout=checkout,
@@ -245,7 +246,9 @@ def test_get_voucher_discount_for_checkout_voucher_validation(
manager = get_plugins_manager()
address = checkout_with_voucher.shipping_address
get_voucher_discount_for_checkout(manager, voucher, checkout_info, lines, address)
- subtotal = manager.calculate_checkout_subtotal(checkout_info, lines, address, [])
+ subtotal = base_calculations.base_checkout_subtotal(
+ lines, checkout_info.channel, checkout_with_voucher.currency, []
+ )
customer_email = checkout_with_voucher.get_customer_email()
mock_validate_voucher.assert_called_once_with(
voucher,
@@ -291,10 +294,10 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
)
checkout = Mock(spec=Checkout, channel=channel_USD)
- subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
+ subtotal = Money(total, "USD")
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: subtotal,
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
)
checkout_info = CheckoutInfo(
checkout=checkout,
@@ -314,12 +317,12 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
@pytest.mark.parametrize(
"discount_value, discount_type, total_discount_amount",
[
- (5, DiscountValueType.FIXED, 15),
- (10, DiscountValueType.PERCENTAGE, 6),
+ (5, DiscountValueType.FIXED, Decimal("15.00")),
+ (10, DiscountValueType.PERCENTAGE, Decimal("6.00")),
],
)
def test_get_discount_for_checkout_specific_products_voucher(
- checkout_with_items,
+ priced_checkout_with_items,
product_list,
discount_value,
discount_type,
@@ -340,13 +343,13 @@ def test_get_discount_for_checkout_specific_products_voucher(
)
for product in product_list:
voucher.products.add(product)
- checkout_with_items.voucher_code = voucher.code
- checkout_with_items.save()
+ priced_checkout_with_items.voucher_code = voucher.code
+ priced_checkout_with_items.save()
manager = get_plugins_manager()
# when
- lines, _ = fetch_checkout_lines(checkout_with_items)
- checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ lines, _ = fetch_checkout_lines(priced_checkout_with_items)
+ checkout_info = fetch_checkout_info(priced_checkout_with_items, lines, [], manager)
subtotal = manager.calculate_checkout_subtotal(
checkout_info, lines, checkout_info.shipping_address, []
).gross
@@ -450,10 +453,8 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
lambda _: TaxedMoney(Money(0, "USD"), Money(0, "USD")),
)
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: TaxedMoney(
- Money(total, "USD"), Money(total, "USD")
- ),
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: Money(total, "USD"),
)
manager = get_plugins_manager()
@@ -490,10 +491,46 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
"shipping_cost, shipping_country_code, discount_value, discount_type,"
"countries, expected_value",
[
- # (10, None, 50, DiscountValueType.PERCENTAGE, [], 5),
- # (10, None, 20, DiscountValueType.FIXED, [], 10),
- # (10, "PL", 20, DiscountValueType.FIXED, [], 10),
- (5, "PL", 5, DiscountValueType.FIXED, ["PL"], 5),
+ (
+ Decimal("10.00"),
+ None,
+ 50,
+ DiscountValueType.PERCENTAGE,
+ [],
+ Decimal("5.00"),
+ ),
+ (
+ Decimal("10.00"),
+ None,
+ 20,
+ DiscountValueType.FIXED,
+ [],
+ Decimal("10.00"),
+ ),
+ (
+ Decimal("10.00"),
+ "PL",
+ 20,
+ DiscountValueType.FIXED,
+ [],
+ Decimal("10.00"),
+ ),
+ (
+ Decimal("5.00"),
+ "PL",
+ Decimal("5.00"),
+ DiscountValueType.FIXED,
+ ["PL"],
+ Decimal("5.00"),
+ ),
+ (
+ Decimal("5.00"),
+ "PL",
+ Decimal("5.00"),
+ DiscountValueType.FIXED,
+ ["PL"],
+ Decimal("5.00"),
+ ),
],
)
def test_get_discount_for_checkout_shipping_voucher(
@@ -509,22 +546,25 @@ def test_get_discount_for_checkout_shipping_voucher(
shipping_method_data,
):
manager = get_plugins_manager()
- subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
+ tax = Decimal("1.23")
+ shipping = TaxedMoney(
+ Money(shipping_cost, "USD"), Money(shipping_cost * tax, "USD")
+ )
+ subtotal = Money(100, "USD")
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: subtotal,
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
)
monkeypatch.setattr(
"saleor.checkout.utils.is_shipping_required", lambda lines: True
)
- shipping_total = Money(shipping_cost, "USD")
checkout = Mock(
spec=Checkout,
is_shipping_required=Mock(return_value=True),
channel_id=channel_USD.id,
channel=channel_USD,
shipping_method=shipping_method,
- get_shipping_price=Mock(return_value=shipping_total),
+ get_shipping_price=Mock(return_value=shipping.gross),
shipping_address=Mock(country=Country(shipping_country_code)),
)
voucher = Voucher.objects.create(
@@ -561,19 +601,15 @@ def test_get_discount_for_checkout_shipping_voucher(
def test_get_discount_for_checkout_shipping_voucher_all_countries(
monkeypatch, channel_USD, shipping_method, shipping_method_data
):
- subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
+ subtotal = Money(100, "USD")
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: subtotal,
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
)
monkeypatch.setattr(
"saleor.checkout.utils.is_shipping_required", lambda lines: True
)
shipping_total = TaxedMoney(Money(10, "USD"), Money(10, "USD"))
- monkeypatch.setattr(
- "saleor.checkout.utils.calculations.checkout_shipping_price",
- lambda manager, checkout_info, lines, address, discounts: shipping_total,
- )
checkout = Mock(
spec=Checkout,
channel_id=channel_USD.id,
@@ -616,11 +652,11 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(
def test_get_discount_for_checkout_shipping_voucher_limited_countries(
monkeypatch, channel_USD
):
- subtotal = TaxedMoney(net=Money(100, "USD"), gross=Money(100, "USD"))
+ subtotal = Money(100, "USD")
shipping_total = TaxedMoney(net=Money(10, "USD"), gross=Money(10, "USD"))
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: subtotal,
+ "saleor.checkout.utils.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
)
checkout = Mock(
get_subtotal=Mock(return_value=subtotal),
@@ -669,7 +705,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
["US"],
None,
None,
- TaxedMoney(Money(10, "USD"), Money(10, "USD")),
+ Money(10, "USD"),
10,
"This offer is not valid in your country.",
),
@@ -681,7 +717,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
[],
None,
None,
- TaxedMoney(Money(10, "USD"), Money(10, "USD")),
+ Money(10, "USD"),
10,
"Please select a delivery method first.",
),
@@ -693,7 +729,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
[],
None,
None,
- TaxedMoney(Money(10, "USD"), Money(10, "USD")),
+ Money(10, "USD"),
10,
"Your order does not require shipping.",
),
@@ -705,7 +741,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
[],
5,
None,
- TaxedMoney(Money(2, "USD"), Money(2, "USD")),
+ Money(2, "USD"),
10,
"This offer is only valid for orders over $5.00.",
),
@@ -717,7 +753,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
[],
5,
10,
- TaxedMoney(Money(5, "USD"), Money(5, "USD")),
+ Money(5, "USD"),
9,
"This offer is only valid for orders with a minimum of 10 quantity.",
),
@@ -729,7 +765,7 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(
[],
5,
10,
- TaxedMoney(Money(2, "USD"), Money(2, "USD")),
+ Money(2, "USD"),
9,
"This offer is only valid for orders over $5.00.",
),
@@ -751,8 +787,8 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
channel_USD,
):
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: subtotal,
+ "saleor.checkout.base_calculations.base_checkout_subtotal",
+ lambda *args: subtotal,
)
monkeypatch.setattr(
"saleor.checkout.utils.is_shipping_required", lambda lines: is_shipping_required
@@ -792,7 +828,12 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
)
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(
- manager, voucher, checkout_info, [], checkout.shipping_address, None
+ manager,
+ voucher,
+ checkout_info,
+ [],
+ checkout.shipping_address,
+ None,
)
assert str(e.value) == error_msg
@@ -832,7 +873,11 @@ def test_remove_voucher_from_checkout(checkout_with_voucher, voucher_translation
def test_recalculate_checkout_discount(
- checkout_with_voucher, voucher, voucher_translation_fr, settings, channel_USD
+ checkout_with_voucher,
+ voucher,
+ voucher_translation_fr,
+ settings,
+ channel_USD,
):
settings.LANGUAGE_CODE = "fr"
voucher.channel_listings.filter(channel=channel_USD).update(discount_value=10)
@@ -848,8 +893,24 @@ def test_recalculate_checkout_discount(
assert checkout_with_voucher.discount == Money("10.00", "USD")
+def test_recalculate_checkout_discount_percentage(
+ priced_checkout_with_voucher_percentage,
+):
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(priced_checkout_with_voucher_percentage)
+ checkout_info = fetch_checkout_info(
+ priced_checkout_with_voucher_percentage, lines, [], manager
+ )
+
+ recalculate_checkout_discount(manager, checkout_info, lines, None)
+ assert priced_checkout_with_voucher_percentage.discount == Money(
+ Decimal("3.00"), "USD"
+ )
+
+
def test_recalculate_checkout_discount_with_sale(
- checkout_with_voucher_percentage, discount_info
+ checkout_with_voucher_percentage,
+ discount_info,
):
checkout = checkout_with_voucher_percentage
manager = get_plugins_manager()
@@ -858,6 +919,9 @@ def test_recalculate_checkout_discount_with_sale(
recalculate_checkout_discount(manager, checkout_info, lines, [discount_info])
assert checkout.discount == Money("1.50", "USD")
+
+ checkout.price_expiration = timezone.now()
+ checkout.save()
assert calculations.checkout_total(
manager=manager,
checkout_info=checkout_info,
@@ -917,10 +981,15 @@ 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(
@@ -956,9 +1025,13 @@ 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"
@@ -995,7 +1068,8 @@ def test_change_address_in_checkout(checkout, address):
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(
+
+ shipping_updated_fields = change_shipping_address_in_checkout(
checkout_info,
address,
lines,
@@ -1003,7 +1077,8 @@ def test_change_address_in_checkout(checkout, address):
manager,
checkout.channel.shipping_method_listings.all(),
)
- change_billing_address_in_checkout(checkout, address)
+ billing_updated_fields = change_billing_address_in_checkout(checkout, address)
+ checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)
checkout.refresh_from_db()
assert checkout.shipping_address == address
@@ -1019,7 +1094,7 @@ def test_change_address_in_checkout_to_none(checkout, address):
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(
+ shipping_updated_fields = change_shipping_address_in_checkout(
checkout_info,
None,
lines,
@@ -1027,7 +1102,8 @@ def test_change_address_in_checkout_to_none(checkout, address):
manager,
checkout.channel.shipping_method_listings.all(),
)
- change_billing_address_in_checkout(checkout, None)
+ billing_updated_fields = change_billing_address_in_checkout(checkout, None)
+ checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)
checkout.refresh_from_db()
assert checkout.shipping_address is None
@@ -1045,7 +1121,7 @@ def test_change_address_in_checkout_to_same(checkout, address):
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(
+ shipping_updated_fields = change_shipping_address_in_checkout(
checkout_info,
address,
lines,
@@ -1053,7 +1129,8 @@ def test_change_address_in_checkout_to_same(checkout, address):
manager,
checkout.channel.shipping_method_listings.all(),
)
- change_billing_address_in_checkout(checkout, address)
+ billing_updated_fields = change_billing_address_in_checkout(checkout, address)
+ checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)
checkout.refresh_from_db()
assert checkout.shipping_address.id == shipping_address_id
@@ -1071,7 +1148,7 @@ def test_change_address_in_checkout_to_other(checkout, address):
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(
+ shipping_updated_fields = change_shipping_address_in_checkout(
checkout_info,
other_address,
lines,
@@ -1079,7 +1156,8 @@ def test_change_address_in_checkout_to_other(checkout, address):
manager,
checkout.channel.shipping_method_listings.all(),
)
- change_billing_address_in_checkout(checkout, other_address)
+ billing_updated_fields = change_billing_address_in_checkout(checkout, other_address)
+ checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)
checkout.refresh_from_db()
assert checkout.shipping_address == other_address
@@ -1101,7 +1179,7 @@ def test_change_address_in_checkout_from_user_address_to_other(
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- change_shipping_address_in_checkout(
+ shipping_updated_fields = change_shipping_address_in_checkout(
checkout_info,
other_address,
lines,
@@ -1109,7 +1187,8 @@ def test_change_address_in_checkout_from_user_address_to_other(
manager,
checkout.channel.shipping_method_listings.all(),
)
- change_billing_address_in_checkout(checkout, other_address)
+ billing_updated_fields = change_billing_address_in_checkout(checkout, other_address)
+ checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)
checkout.refresh_from_db()
assert checkout.shipping_address == other_address
@@ -1181,6 +1260,7 @@ def test_add_voucher_to_checkout_fail(
checkout_info,
lines,
voucher_with_high_min_spent_amount,
+ False,
)
assert checkout_with_item.voucher_code is None
@@ -1297,7 +1377,7 @@ def test_cancel_active_payments(checkout_with_payments):
assert checkout.payments.filter(is_active=True).count() == 0
-def test_chckout_without_delivery_method_creates_empty_delivery_method(
+def test_checkout_without_delivery_method_creates_empty_delivery_method(
checkout_with_item,
):
checkout = checkout_with_item
@@ -1325,3 +1405,99 @@ def test_manage_external_shipping_id(checkout):
delete_external_shipping_id(checkout)
assert checkout.private_metadata == initial_private_metadata
+
+
+def test_checkout_total_setter():
+ # given
+ currency = "USD"
+ net_amount = Decimal(10)
+ net = Money(net_amount, currency)
+ gross_amount = Decimal(15)
+ gross = Money(gross_amount, currency)
+
+ # when
+ price = TaxedMoney(net=net, gross=gross)
+ checkout = Checkout()
+ checkout.total = price
+
+ # then
+ assert checkout.currency == currency
+ assert checkout.total_net_amount == net_amount
+ assert checkout.total.net == net
+ assert checkout.total_gross_amount == gross_amount
+ assert checkout.total.gross == gross
+ assert checkout.total.tax == gross - net
+
+
+def test_checkout_subtotal_setter():
+ # given
+ currency = "USD"
+ net_amount = Decimal(10)
+ net = Money(net_amount, currency)
+ gross_amount = Decimal(15)
+ gross = Money(gross_amount, currency)
+
+ # when
+ price = TaxedMoney(net=net, gross=gross)
+ checkout = Checkout()
+ checkout.subtotal = price
+
+ # then
+ assert checkout.currency == currency
+ assert checkout.subtotal_net_amount == net_amount
+ assert checkout.subtotal.net == net
+ assert checkout.subtotal_gross_amount == gross_amount
+ assert checkout.subtotal.gross == gross
+ assert checkout.subtotal.tax == gross - net
+
+
+def test_checkout_shipping_price_setter():
+ # given
+ currency = "USD"
+ net_amount = Decimal(10)
+ net = Money(net_amount, currency)
+ gross_amount = Decimal(15)
+ gross = Money(gross_amount, currency)
+
+ # when
+ price = TaxedMoney(net=net, gross=gross)
+ checkout = Checkout()
+ checkout.shipping_price = price
+
+ # then
+ assert checkout.currency == currency
+ assert checkout.shipping_price_net_amount == net_amount
+ assert checkout.shipping_price.net == net
+ assert checkout.shipping_price_gross_amount == gross_amount
+ assert checkout.shipping_price.gross == gross
+ assert checkout.shipping_price.tax == gross - net
+
+
+def test_checkout_line_total_price_setter():
+ # given
+ currency = "USD"
+ net_amount = Decimal(10)
+ net = Money(net_amount, currency)
+ gross_amount = Decimal(15)
+ gross = Money(gross_amount, currency)
+
+ # when
+ price = TaxedMoney(net=net, gross=gross)
+ checkout_line = CheckoutLine()
+ checkout_line.total_price = price
+
+ # then
+ assert checkout_line.currency == currency
+ assert checkout_line.total_price_net_amount == net_amount
+ assert checkout_line.total_price.net == net
+ assert checkout_line.total_price_gross_amount == gross_amount
+ assert checkout_line.total_price.gross == gross
+ assert checkout_line.total_price.tax == gross - net
+
+
+def test_checkout_has_currency(checkout):
+ assert hasattr(checkout, "currency")
+
+
+def test_checkout_line_has_currency(checkout_line):
+ assert hasattr(checkout_line, "currency")
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index eabf1cf699..701e68cbc0 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -30,10 +30,7 @@ from ..product import models as product_models
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
from ..shipping.utils import convert_to_shipping_method_data
-from ..warehouse.availability import (
- check_stock_and_preorder_quantity,
- check_stock_and_preorder_quantity_bulk,
-)
+from ..warehouse.availability import check_stock_and_preorder_quantity
from ..warehouse.models import Warehouse
from ..warehouse.reservations import reserve_stocks_and_preorders
from . import AddressType, base_calculations, calculations
@@ -59,6 +56,30 @@ if TYPE_CHECKING:
PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"
+def invalidate_checkout_prices(
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ manager: "PluginsManager",
+ discounts: Optional[Iterable["DiscountInfo"]] = None,
+ *,
+ recalculate_discount: bool = True,
+ save: bool
+) -> List[str]:
+ """Mark checkout as ready for prices recalculation."""
+ checkout = checkout_info.checkout
+
+ if recalculate_discount:
+ recalculate_checkout_discount(manager, checkout_info, lines, discounts or [])
+
+ checkout.price_expiration = timezone.now()
+ updated_fields = ["price_expiration", "last_change"]
+
+ if save:
+ checkout.save(update_fields=updated_fields)
+
+ return updated_fields
+
+
def get_user_checkout(
user: User, checkout_queryset=Checkout.objects.all()
) -> Optional[Checkout]:
@@ -140,16 +161,19 @@ def add_variant_to_checkout(
line.delete()
line = None
elif line is None:
- line = checkout.lines.create(
+ line = checkout.lines.create( # type: ignore
checkout=checkout,
variant=variant,
quantity=new_quantity,
+ currency=checkout.currency,
price_override=price_override,
)
elif new_quantity > 0:
line.quantity = new_quantity
line.save(update_fields=["quantity"])
+ # invalidate calculated prices
+ checkout.price_expiration = timezone.now()
return checkout
@@ -254,6 +278,7 @@ def _append_line_to_create(
checkout=checkout,
variant=variant,
quantity=line_data.quantity,
+ currency=checkout.currency,
price_override=line_data.custom_price,
)
)
@@ -283,19 +308,23 @@ def _check_new_checkout_address(checkout, address, address_type):
return has_address_changed, remove_old_address
-def change_billing_address_in_checkout(checkout, address):
+def change_billing_address_in_checkout(checkout, address) -> List[str]:
"""Save billing address in checkout if changed.
Remove previously saved address if not connected to any user.
+ This function does not save anything to database and
+ instead returns updated fields.
"""
changed, remove = _check_new_checkout_address(
checkout, address, AddressType.BILLING
)
+ updated_fields = []
if changed:
if remove:
checkout.billing_address.delete()
checkout.billing_address = address
- checkout.save(update_fields=["billing_address", "last_change"])
+ updated_fields = ["billing_address", "last_change"]
+ return updated_fields
def change_shipping_address_in_checkout(
@@ -309,11 +338,14 @@ def change_shipping_address_in_checkout(
"""Save shipping address in checkout if changed.
Remove previously saved address if not connected to any user.
+ This function does not save anything to database and
+ instead returns updated fields.
"""
checkout = checkout_info.checkout
changed, remove = _check_new_checkout_address(
checkout, address, AddressType.SHIPPING
)
+ updated_fields = []
if changed:
if remove:
checkout.shipping_address.delete() # type: ignore
@@ -321,7 +353,8 @@ def change_shipping_address_in_checkout(
update_checkout_info_shipping_address(
checkout_info, address, lines, discounts, manager, shipping_channel_listings
)
- checkout.save(update_fields=["shipping_address", "last_change"])
+ updated_fields = ["shipping_address", "last_change"]
+ return updated_fields
def _get_shipping_voucher_discount_for_checkout(
@@ -345,32 +378,12 @@ def _get_shipping_voucher_discount_for_checkout(
msg = "This offer is not valid in your country."
raise NotApplicable(msg)
- # the gross is taken, as net and gross are the same for base calculations
shipping_price = base_calculations.base_checkout_delivery_price(
checkout_info=checkout_info, lines=lines
- ).gross
+ )
return voucher.get_discount_amount_for(shipping_price, checkout_info.channel)
-def _get_products_voucher_discount(
- manager: PluginsManager,
- checkout_info: "CheckoutInfo",
- lines: Iterable["CheckoutLineInfo"],
- voucher,
- discounts: Optional[Iterable[DiscountInfo]] = None,
-):
- """Calculate products discount value for a voucher, depending on its type."""
- prices = None
- if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- prices = get_prices_of_discounted_specific_product(
- manager, checkout_info, lines, voucher, discounts
- )
- if not prices:
- msg = "This offer is only valid for selected items."
- raise NotApplicable(msg)
- return get_products_voucher_discount(voucher, prices, checkout_info.channel)
-
-
def get_discounted_lines(
lines: Iterable["CheckoutLineInfo"], voucher_info: "VoucherInfo"
) -> Iterable["CheckoutLineInfo"]:
@@ -422,18 +435,15 @@ def get_prices_of_discounted_specific_product(
discounted_lines: Iterable["CheckoutLineInfo"] = get_discounted_lines(
lines, voucher_info
)
- address = checkout_info.shipping_address or checkout_info.billing_address
discounts = discounts or []
for line_info in discounted_lines:
line = line_info.line
- line_unit_price = manager.calculate_checkout_line_unit_price(
- checkout_info,
- lines,
+ line_unit_price = base_calculations.calculate_base_line_unit_price(
line_info,
- address,
+ checkout_info.channel,
discounts,
- ).price_with_sale.gross
+ )
line_prices.extend([line_unit_price] * line.quantity)
return line_prices
@@ -453,17 +463,19 @@ def get_voucher_discount_for_checkout(
"""
validate_voucher_for_checkout(manager, voucher, checkout_info, lines, discounts)
if voucher.type == VoucherType.ENTIRE_ORDER:
- # the gross is taken, as net and gross are the same for base calculations
- subtotal = base_calculations.base_checkout_lines_total(
+ subtotal = base_calculations.base_checkout_subtotal(
lines,
checkout_info.channel,
checkout_info.checkout.currency,
discounts,
- ).gross
+ )
return voucher.get_discount_amount_for(subtotal, checkout_info.channel)
if voucher.type == VoucherType.SHIPPING:
return _get_shipping_voucher_discount_for_checkout(
- voucher, checkout_info, lines, address
+ voucher,
+ checkout_info,
+ lines,
+ address,
)
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
# The specific product voucher is propagated on specific line's prices
@@ -511,6 +523,31 @@ def get_voucher_for_checkout_info(
)
+def check_voucher_for_checkout(
+ voucher: Voucher,
+ manager: PluginsManager,
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Iterable[DiscountInfo],
+):
+ checkout = checkout_info.checkout
+ address = checkout_info.shipping_address or checkout_info.billing_address
+ try:
+ discount = get_voucher_discount_for_checkout(
+ manager,
+ voucher,
+ checkout_info,
+ lines,
+ address,
+ discounts,
+ )
+ return discount
+ except NotApplicable:
+ remove_voucher_from_checkout(checkout)
+ checkout_info.voucher = None
+ return None
+
+
def recalculate_checkout_discount(
manager: PluginsManager,
checkout_info: "CheckoutInfo",
@@ -524,22 +561,20 @@ def recalculate_checkout_discount(
"""
checkout = checkout_info.checkout
if voucher := checkout_info.voucher:
- address = checkout_info.shipping_address or checkout_info.billing_address
- try:
- discount = get_voucher_discount_for_checkout(
- manager, voucher, checkout_info, lines, address, discounts
- )
- except NotApplicable:
- remove_voucher_from_checkout(checkout)
- checkout_info.voucher = None
- else:
- # the gross is taken, as net and gross are the same for base calculations
- subtotal = base_calculations.base_checkout_lines_total(
+ discount = check_voucher_for_checkout(
+ voucher,
+ manager,
+ checkout_info,
+ lines,
+ discounts,
+ )
+ if discount:
+ subtotal = base_calculations.base_checkout_subtotal(
lines,
checkout_info.channel,
checkout_info.checkout.currency,
discounts,
- ).gross
+ )
checkout.discount = (
min(discount, subtotal)
if voucher.type != VoucherType.SHIPPING
@@ -577,7 +612,11 @@ def add_promo_code_to_checkout(
"""
if promo_code_is_voucher(promo_code):
add_voucher_code_to_checkout(
- manager, checkout_info, lines, promo_code, discounts
+ manager,
+ checkout_info,
+ lines,
+ promo_code,
+ discounts,
)
elif promo_code_is_gift_card(promo_code):
user_email = cast(str, checkout_info.get_customer_email())
@@ -609,7 +648,13 @@ def add_voucher_code_to_checkout(
except Voucher.DoesNotExist:
raise InvalidPromoCode()
try:
- add_voucher_to_checkout(manager, checkout_info, lines, voucher, discounts)
+ add_voucher_to_checkout(
+ manager,
+ checkout_info,
+ lines,
+ voucher,
+ discounts,
+ )
except NotApplicable:
raise ValidationError(
{
@@ -635,7 +680,12 @@ def add_voucher_to_checkout(
checkout = checkout_info.checkout
address = checkout_info.shipping_address or checkout_info.billing_address
discount = get_voucher_discount_for_checkout(
- manager, voucher, checkout_info, lines, address, discounts
+ manager,
+ voucher,
+ checkout_info,
+ lines,
+ address,
+ discounts,
)
checkout.voucher_code = voucher.code
checkout.discount_name = voucher.name
@@ -655,20 +705,33 @@ def add_voucher_to_checkout(
checkout_info.voucher = voucher
-def remove_promo_code_from_checkout(checkout_info: "CheckoutInfo", promo_code: str):
- """Remove gift card or voucher data from checkout."""
+def remove_promo_code_from_checkout(
+ checkout_info: "CheckoutInfo", promo_code: str
+) -> bool:
+ """Remove gift card or voucher data from checkout.
+
+ Return information whether promo code was removed.
+ """
if promo_code_is_voucher(promo_code):
- remove_voucher_code_from_checkout(checkout_info, promo_code)
+ return remove_voucher_code_from_checkout(checkout_info, promo_code)
elif promo_code_is_gift_card(promo_code):
- remove_gift_card_code_from_checkout(checkout_info.checkout, promo_code)
+ return remove_gift_card_code_from_checkout(checkout_info.checkout, promo_code)
+ return False
-def remove_voucher_code_from_checkout(checkout_info: "CheckoutInfo", voucher_code: str):
- """Remove voucher data from checkout by code."""
+def remove_voucher_code_from_checkout(
+ checkout_info: "CheckoutInfo", voucher_code: str
+) -> bool:
+ """Remove voucher data from checkout by code.
+
+ Return information whether promo code was removed.
+ """
existing_voucher = checkout_info.voucher
if existing_voucher and existing_voucher.code == voucher_code:
remove_voucher_from_checkout(checkout_info.checkout)
checkout_info.voucher = None
+ return True
+ return False
def remove_voucher_from_checkout(checkout: Checkout):
@@ -692,7 +755,7 @@ def remove_voucher_from_checkout(checkout: Checkout):
def get_valid_internal_shipping_methods_for_checkout(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
- subtotal: "TaxedMoney",
+ subtotal: "Money",
shipping_channel_listings: Iterable["ShippingMethodChannelListing"],
country_code: Optional[str] = None,
) -> List[ShippingMethodData]:
@@ -704,7 +767,7 @@ def get_valid_internal_shipping_methods_for_checkout(
shipping_methods = ShippingMethod.objects.applicable_shipping_methods_for_instance(
checkout_info.checkout,
channel_id=checkout_info.checkout.channel_id,
- price=subtotal.gross,
+ price=subtotal,
country_code=country_code,
lines=lines,
)
@@ -779,15 +842,12 @@ def is_fully_paid(
payments = [payment for payment in checkout.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
address = checkout_info.shipping_address or checkout_info.billing_address
- checkout_total = (
- calculations.checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- discounts=discounts,
- )
- - checkout.get_total_gift_cards_balance()
+ checkout_total = calculations.calculate_checkout_total_with_gift_cards(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
)
checkout_total = max(
checkout_total, zero_taxed_money(checkout_total.currency)
diff --git a/saleor/core/permissions/enums.py b/saleor/core/permissions/enums.py
index 2ad4a74807..408846a0e9 100644
--- a/saleor/core/permissions/enums.py
+++ b/saleor/core/permissions/enums.py
@@ -44,6 +44,7 @@ class MenuPermissions(BasePermissionEnum):
class CheckoutPermissions(BasePermissionEnum):
MANAGE_CHECKOUTS = "checkout.manage_checkouts"
HANDLE_CHECKOUTS = "checkout.handle_checkouts"
+ HANDLE_TAXES = "checkout.handle_taxes"
class OrderPermissions(BasePermissionEnum):
diff --git a/saleor/core/prices.py b/saleor/core/prices.py
index a68bf3c256..efc2eb77e2 100644
--- a/saleor/core/prices.py
+++ b/saleor/core/prices.py
@@ -1,16 +1,16 @@
from decimal import Decimal
-from typing import TYPE_CHECKING, Iterable, Union
+from typing import TYPE_CHECKING, Iterable, TypeVar
from babel.numbers import get_currency_precision
+from prices import Money, TaxedMoney, TaxedMoneyRange
if TYPE_CHECKING:
from django.db.models import Model
- from prices import Money, TaxedMoney, TaxedMoneyRange
-MoneyTypes = Union["TaxedMoney", "Money", Decimal, "TaxedMoneyRange"]
+PriceType = TypeVar("PriceType", TaxedMoney, Money, Decimal, TaxedMoneyRange)
-def quantize_price(price: MoneyTypes, currency: str) -> MoneyTypes:
+def quantize_price(price: PriceType, currency: str) -> PriceType:
precision = get_currency_precision(currency)
number_places = Decimal(10) ** -precision
return price.quantize(number_places)
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index 713ef8dbf7..44f4ab2056 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -1,5 +1,6 @@
from dataclasses import dataclass
-from typing import Union
+from decimal import Decimal
+from typing import List, Union
from django.contrib.sites.models import Site
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -57,3 +58,18 @@ class TaxType:
code: str
description: str
+
+
+@dataclass(frozen=True)
+class TaxLineData:
+ tax_rate: Decimal
+ total_gross_amount: Decimal
+ total_net_amount: Decimal
+
+
+@dataclass(frozen=True)
+class TaxData:
+ shipping_price_gross_amount: Decimal
+ shipping_price_net_amount: Decimal
+ shipping_tax_rate: Decimal
+ lines: List[TaxLineData]
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.py
new file mode 100644
index 0000000000..8144fba95f
--- /dev/null
+++ b/saleor/core/tests/test_taxes.py
@@ -0,0 +1,115 @@
+import pytest
+
+from ...app.models import App
+from ...plugins.webhook.utils import get_current_tax_app
+from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ...webhook.models import Webhook, WebhookEvent
+from ..permissions import (
+ CheckoutPermissions,
+ OrderPermissions,
+ get_permissions_from_codenames,
+)
+
+
+def app_factory():
+ def factory(name, is_active, webhook_event_types, permissions):
+ app = App.objects.create(name=name, is_active=is_active)
+ webhook = Webhook.objects.create(
+ name=f"{name} Webhook",
+ app=app,
+ target_url="https://test.webhook.url",
+ )
+ for event_type in webhook_event_types:
+ WebhookEvent.objects.create(
+ webhook=webhook,
+ event_type=event_type,
+ )
+ app.permissions.add(
+ *get_permissions_from_codenames([p.codename for p in permissions])
+ )
+ return app
+
+ return factory
+
+
+def tax_app_factory(app_factory):
+ def factory(name, is_active=True, webhook_event_types=None, permissions=None):
+ if webhook_event_types is None:
+ webhook_event_types = [
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ ]
+ if permissions is None:
+ permissions = [CheckoutPermissions.HANDLE_TAXES]
+ return app_factory(
+ name=name,
+ is_active=is_active,
+ webhook_event_types=webhook_event_types,
+ permissions=permissions,
+ )
+
+ return factory
+
+
+def tax_app(tax_app_factory):
+ return tax_app_factory(
+ name="Tax App",
+ is_active=True,
+ )
+
+
+def test_get_current_tax_app(tax_app):
+ assert tax_app == get_current_tax_app()
+
+
+def test_get_current_tax_app_multiple_apps(app_factory, tax_app_factory):
+ # given
+ tax_app_factory(
+ name="A Tax App",
+ )
+ tax_app_factory(
+ name="Z Tax App",
+ )
+ expected_app = tax_app_factory(
+ name="Tax App",
+ )
+ app_factory(
+ name="Non Tax App",
+ is_active=True,
+ webhook_event_types=[
+ WebhookEventAsyncType.ORDER_UPDATED,
+ ],
+ permissions=[
+ OrderPermissions.MANAGE_ORDERS,
+ ],
+ )
+ tax_app_factory(name="Unauthorized Tax App", permissions=[])
+ tax_app_factory(
+ name="Partial Tax App 2",
+ webhook_event_types=[
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ ],
+ )
+ tax_app_factory(
+ name="Partial Tax App 1",
+ webhook_event_types=[
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ ],
+ )
+ tax_app_factory(
+ name="Inactive Tax App",
+ is_active=False,
+ )
+
+ # when
+ app = get_current_tax_app()
+
+ # then
+ assert expected_app == app
+
+
+def test_get_current_tax_app_no_app():
+ assert get_current_tax_app() is None
diff --git a/saleor/core/utils/anonymization.py b/saleor/core/utils/anonymization.py
index 2245874a33..2f5620043d 100644
--- a/saleor/core/utils/anonymization.py
+++ b/saleor/core/utils/anonymization.py
@@ -1,6 +1,6 @@
import copy
import logging
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Dict
from faker import Faker
@@ -42,6 +42,11 @@ def generate_fake_user() -> "User":
return fake_user
+def generate_fake_metadata() -> Dict[str, str]:
+ """Generate a fake metadata/private metadata dictionary."""
+ return fake.pydict(value_types=str)
+
+
def anonymize_order(order: "Order") -> "Order":
"""Generate an anonymized version of the provided order.
@@ -56,8 +61,8 @@ def anonymize_order(order: "Order") -> "Order":
anonymized_order.shipping_address = generate_fake_address()
anonymized_order.billing_address = generate_fake_address()
anonymized_order.customer_note = fake.paragraph()
- anonymized_order.metadata = fake.pystruct(count=1)
- anonymized_order.private_metadata = fake.pystruct(count=1)
+ anonymized_order.metadata = generate_fake_metadata()
+ anonymized_order.private_metadata = generate_fake_metadata()
return anonymized_order
@@ -75,6 +80,6 @@ def anonymize_checkout(checkout: "Checkout") -> "Checkout":
anonymized_checkout.shipping_address = generate_fake_address()
anonymized_checkout.billing_address = generate_fake_address()
anonymized_checkout.note = fake.paragraph()
- anonymized_checkout.metadata = fake.pystruct(count=1)
- anonymized_checkout.private_metadata = fake.pystruct(count=1)
+ anonymized_checkout.metadata = generate_fake_metadata()
+ anonymized_checkout.private_metadata = generate_fake_metadata()
return anonymized_checkout
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 7d0c219032..92dcd3d57e 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -13,12 +13,11 @@ from django.utils import timezone
from django_countries.fields import CountryField
from django_prices.models import MoneyField
from django_prices.templatetags.prices import amount
-from prices import Money, TaxedMoney, fixed_discount, percentage_discount
+from prices import Money, fixed_discount, percentage_discount
from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.permissions import DiscountPermissions
-from ..core.taxes import display_gross_prices
from ..core.utils.translations import Translation, TranslationProxy
from . import DiscountValueType, OrderDiscountType, VoucherType
@@ -137,8 +136,7 @@ class Voucher(ModelWithMetadata):
return price
return price - after_discount
- def validate_min_spent(self, value: TaxedMoney, channel: Channel):
- value = value.gross if display_gross_prices() else value.net
+ def validate_min_spent(self, value: Money, channel: Channel):
voucher_channel_listing = self.channel_listings.filter(channel=channel).first()
if not voucher_channel_listing:
raise NotApplicable("This voucher is not assigned to this channel")
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 60216f2b7b..09e3f0e026 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -26,12 +26,7 @@ from ..utils import (
)
-def test_valid_voucher_min_spent_amount_with_display_gross_prices(
- channel_USD, site_settings
-):
- site_settings.display_gross_prices = True
- site_settings.save()
-
+def test_valid_voucher_min_spent_amount(channel_USD):
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
@@ -43,17 +38,12 @@ def test_valid_voucher_min_spent_amount_with_display_gross_prices(
discount=Money(10, "USD"),
min_spent=Money(7, "USD"),
)
- value = TaxedMoney(net=Money(5, "USD"), gross=Money(7, "USD"))
+ value = Money(7, "USD")
voucher.validate_min_spent(value, channel_USD)
-def test_valid_voucher_min_spent_amount_without_display_gross_prices(
- channel_USD, site_settings
-):
- site_settings.display_gross_prices = False
- site_settings.save()
-
+def test_valid_voucher_min_spent_amount_not_reached(channel_USD):
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
@@ -65,7 +55,7 @@ def test_valid_voucher_min_spent_amount_without_display_gross_prices(
discount=Money(10, "USD"),
min_spent=Money(7, "USD"),
)
- value = TaxedMoney(net=Money(5, "USD"), gross=Money(7, "USD"))
+ value = Money(5, "USD")
with pytest.raises(NotApplicable):
voucher.validate_min_spent(value, channel_USD)
@@ -512,9 +502,8 @@ def test_validate_voucher(
min_spent_amount=min_spent_amount,
)
total_price = Money(total, "USD")
- price = TaxedMoney(gross=total_price, net=total_price)
validate_voucher(
- voucher, price, total_quantity, "[email protected]", channel_USD, None
+ voucher, total_price, total_quantity, "[email protected]", channel_USD, None
)
@@ -607,11 +596,10 @@ def test_validate_voucher_not_applicable(
min_spent_amount=min_spent_amount,
)
total_price = Money(total, "USD")
- price = TaxedMoney(net=total_price, gross=total_price)
with pytest.raises(NotApplicable):
validate_voucher(
- voucher, price, total_quantity, "[email protected]", channel_USD, None
+ voucher, total_price, total_quantity, "[email protected]", channel_USD, None
)
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 51c2f6d266..da074ce8b6 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -19,7 +19,7 @@ from django.utils import timezone
from prices import Money, TaxedMoney
from ..channel.models import Channel
-from ..core.taxes import zero_money
+from ..core.taxes import include_taxes_in_prices, zero_money
from . import DiscountInfo
from .models import NotApplicable, Sale, SaleChannelListing, VoucherCustomer
@@ -199,7 +199,7 @@ def validate_voucher_for_checkout(
from ..checkout.utils import calculate_checkout_quantity
quantity = calculate_checkout_quantity(lines)
- subtotal = base_calculations.base_checkout_lines_total(
+ subtotal = base_calculations.base_checkout_subtotal(
lines,
checkout_info.channel,
checkout_info.checkout.currency,
@@ -223,8 +223,9 @@ def validate_voucher_in_order(order: "Order"):
customer_email = order.get_customer_email()
if not order.voucher:
return
+ value = subtotal.gross if include_taxes_in_prices() else subtotal.net
validate_voucher(
- order.voucher, subtotal, quantity, customer_email, order.channel, order.user
+ order.voucher, value, quantity, customer_email, order.channel, order.user
)
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index d73267a5b0..0d27c67a32 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -56,11 +56,16 @@ def add_gift_card_code_to_checkout(
def remove_gift_card_code_from_checkout(checkout: Checkout, gift_card_code: str):
- """Remove gift card data from checkout by code."""
+ """Remove gift card data from checkout by code.
+
+ Return information whether promo code was removed.
+ """
gift_card = checkout.gift_cards.filter(code=gift_card_code).first()
if gift_card:
checkout.gift_cards.remove(gift_card)
checkout.save(update_fields=["last_change"])
+ return True
+ return False
def deactivate_gift_card(gift_card: GiftCard):
diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
index 6cc77b1793..b2e9af88c7 100644
--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py
@@ -8,7 +8,7 @@ from ....checkout.fetch import (
fetch_checkout_lines,
update_delivery_method_lists_for_checkout_info,
)
-from ....checkout.utils import add_promo_code_to_checkout
+from ....checkout.utils import add_promo_code_to_checkout, invalidate_checkout_prices
from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
from ...core.mutations import BaseMutation
from ...core.scalars import UUID
@@ -105,5 +105,14 @@ class CheckoutAddPromoCode(BaseMutation):
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
+ invalidate_checkout_prices(
+ checkout_info,
+ lines,
+ manager,
+ discounts,
+ recalculate_discount=False,
+ save=True,
+ )
manager.checkout_updated(checkout)
+
return CheckoutAddPromoCode(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
index ecd0bfbc37..8a07ec0ee6 100644
--- a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py
@@ -2,7 +2,11 @@ import graphene
from ....checkout import AddressType
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.utils import change_billing_address_in_checkout
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.utils import (
+ change_billing_address_in_checkout,
+ invalidate_checkout_prices,
+)
from ....core.tracing import traced_atomic_transaction
from ...account.types import AddressInput
from ...core.descriptions import (
@@ -88,6 +92,26 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
)
with traced_atomic_transaction():
billing_address.save()
- change_billing_address_in_checkout(checkout, billing_address)
+ change_address_updated_fields = change_billing_address_in_checkout(
+ checkout, billing_address
+ )
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(
+ checkout, lines, info.context.discounts, info.context.plugins
+ )
+ invalidate_prices_updated_fields = invalidate_checkout_prices(
+ checkout_info,
+ lines,
+ info.context.plugins,
+ info.context.discounts,
+ recalculate_discount=False,
+ save=False,
+ )
+ checkout.save(
+ update_fields=change_address_updated_fields
+ + invalidate_prices_updated_fields
+ )
+
info.context.plugins.checkout_updated(checkout)
+
return CheckoutBillingAddressUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
index 2d949d4059..327f12dba4 100644
--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py
@@ -1,16 +1,22 @@
-from typing import Optional
+from typing import Iterable, Optional
import graphene
from django.core.exceptions import ValidationError
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.fetch import (
+ CheckoutInfo,
+ CheckoutLineInfo,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
from ....checkout.utils import (
delete_external_shipping_id,
+ invalidate_checkout_prices,
is_shipping_required,
- recalculate_checkout_discount,
set_external_shipping_id,
)
+from ....discount import DiscountInfo
from ....plugins.webhook.utils import APP_ID_PREFIX
from ....shipping import interface as shipping_interface
from ....shipping import models as shipping_models
@@ -84,14 +90,13 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
cls._update_delivery_method(
manager,
- checkout,
+ checkout_info,
+ lines,
+ info.context.discounts,
shipping_method=shipping_method,
external_shipping_method=None,
collection_point=None,
)
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
- )
return CheckoutDeliveryMethodUpdate(checkout=checkout)
@classmethod
@@ -120,14 +125,13 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
cls._update_delivery_method(
manager,
- checkout,
+ checkout_info,
+ lines,
+ info.context.discounts,
shipping_method=None,
external_shipping_method=delivery_method,
collection_point=None,
)
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
- )
return CheckoutDeliveryMethodUpdate(checkout=checkout)
@classmethod
@@ -149,7 +153,9 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
)
cls._update_delivery_method(
manager,
- checkout,
+ checkout_info,
+ lines,
+ info.context.discounts,
shipping_method=None,
external_shipping_method=None,
collection_point=collection_point,
@@ -187,12 +193,15 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
@staticmethod
def _update_delivery_method(
manager,
- checkout: Checkout,
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Iterable["DiscountInfo"],
*,
shipping_method: Optional[ShippingMethod],
external_shipping_method: Optional[shipping_interface.ShippingMethodData],
collection_point: Optional[Warehouse]
) -> None:
+ checkout = checkout_info.checkout
if external_shipping_method:
set_external_shipping_id(
checkout=checkout, app_shipping_id=external_shipping_method.id
@@ -201,13 +210,16 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):
delete_external_shipping_id(checkout=checkout)
checkout.shipping_method = shipping_method
checkout.collection_point = collection_point
+ invalidate_prices_updated_fields = invalidate_checkout_prices(
+ checkout_info, lines, manager, discounts or [], save=False
+ )
checkout.save(
update_fields=[
"private_metadata",
"shipping_method",
"collection_point",
- "last_change",
]
+ + invalidate_prices_updated_fields
)
manager.checkout_updated(checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_line_delete.py b/saleor/graphql/checkout/mutations/checkout_line_delete.py
index 23f431e86c..33ad947b3c 100644
--- a/saleor/graphql/checkout/mutations/checkout_line_delete.py
+++ b/saleor/graphql/checkout/mutations/checkout_line_delete.py
@@ -2,7 +2,7 @@ import graphene
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ....checkout.utils import recalculate_checkout_discount
+from ....checkout.utils import invalidate_checkout_prices
from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
from ...core.mutations import BaseMutation
from ...core.scalars import UUID
@@ -62,8 +62,9 @@ class CheckoutLineDelete(BaseMutation):
checkout, lines, info.context.discounts, manager
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
+ invalidate_checkout_prices(
+ checkout_info, lines, manager, info.context.discounts, save=True
)
manager.checkout_updated(checkout)
+
return CheckoutLineDelete(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index f7eb3fe9a9..46c6273e43 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -6,7 +6,7 @@ from ....checkout.fetch import (
fetch_checkout_lines,
update_delivery_method_lists_for_checkout_info,
)
-from ....checkout.utils import add_variants_to_checkout, recalculate_checkout_discount
+from ....checkout.utils import add_variants_to_checkout, invalidate_checkout_prices
from ....warehouse.reservations import get_reservation_length, is_reservation_enabled
from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
from ...core.mutations import BaseMutation
@@ -192,8 +192,7 @@ class CheckoutLinesAdd(BaseMutation):
replace,
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
- )
+ invalidate_checkout_prices(checkout_info, lines, manager, discounts, save=True)
manager.checkout_updated(checkout)
+
return CheckoutLinesAdd(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_delete.py b/saleor/graphql/checkout/mutations/checkout_lines_delete.py
index f156579929..a9cd55d1e9 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_delete.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_delete.py
@@ -3,7 +3,7 @@ from django.core.exceptions import ValidationError
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ....checkout.utils import recalculate_checkout_discount
+from ....checkout.utils import invalidate_checkout_prices
from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
from ...core.mutations import BaseMutation
from ...core.scalars import UUID
@@ -81,8 +81,9 @@ class CheckoutLinesDelete(BaseMutation):
checkout, lines, info.context.discounts, manager
)
update_checkout_shipping_method_if_invalid(checkout_info, lines)
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
+ invalidate_checkout_prices(
+ checkout_info, lines, manager, info.context.discounts, save=True
)
manager.checkout_updated(checkout)
+
return CheckoutLinesDelete(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
index 68bfe5e75f..7c28429a24 100644
--- a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py
@@ -6,8 +6,9 @@ from graphql.error import GraphQLError
from ....checkout import models
from ....checkout.error_codes import CheckoutErrorCode
-from ....checkout.fetch import fetch_checkout_info
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import (
+ invalidate_checkout_prices,
remove_promo_code_from_checkout,
remove_voucher_from_checkout,
)
@@ -86,12 +87,27 @@ class CheckoutRemovePromoCode(BaseMutation):
checkout_info = fetch_checkout_info(
checkout, [], info.context.discounts, manager
)
+
+ removed = False
if promo_code:
- remove_promo_code_from_checkout(checkout_info, promo_code)
+ removed = remove_promo_code_from_checkout(checkout_info, promo_code)
else:
- cls.remove_promo_code_by_id(info, checkout, object_type, promo_code_pk)
+ removed = cls.remove_promo_code_by_id(
+ info, checkout, object_type, promo_code_pk
+ )
+
+ if removed:
+ lines, _ = fetch_checkout_lines(checkout)
+ invalidate_checkout_prices(
+ checkout_info,
+ lines,
+ manager,
+ info.context.discounts,
+ recalculate_discount=False,
+ save=True,
+ )
+ manager.checkout_updated(checkout)
- manager.checkout_updated(checkout)
return CheckoutRemovePromoCode(checkout=checkout)
@staticmethod
@@ -126,7 +142,13 @@ class CheckoutRemovePromoCode(BaseMutation):
@classmethod
def remove_promo_code_by_id(
cls, info, checkout: models.Checkout, object_type: str, promo_code_pk: int
- ):
+ ) -> bool:
+ """Detach promo code from the checkout based on the id.
+
+ Return a boolean value that indicates whether this function changed
+ the checkout object which then controls whether hooks such as
+ `checkout_updated` are triggered.
+ """
if object_type == str(Voucher) and checkout.voucher_code is not None:
node = cls._get_node_by_pk(info, graphene_type=Voucher, pk=promo_code_pk)
if node is None:
@@ -140,5 +162,9 @@ class CheckoutRemovePromoCode(BaseMutation):
)
if checkout.voucher_code == node.code:
remove_voucher_from_checkout(checkout)
+ return True
else:
checkout.gift_cards.remove(promo_code_pk)
+ return True
+
+ return False
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
index 143deb11db..b3f113d1d1 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py
@@ -12,8 +12,8 @@ from ....checkout.fetch import (
)
from ....checkout.utils import (
change_shipping_address_in_checkout,
+ invalidate_checkout_prices,
is_shipping_required,
- recalculate_checkout_discount,
)
from ....core.tracing import traced_atomic_transaction
from ....product import models as product_models
@@ -165,9 +165,10 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
update_checkout_shipping_method_if_invalid(checkout_info, lines)
+ shipping_address_updated_fields = []
with traced_atomic_transaction():
shipping_address_instance.save()
- change_shipping_address_in_checkout(
+ shipping_address_updated_fields = change_shipping_address_in_checkout(
checkout_info,
shipping_address_instance,
lines,
@@ -175,7 +176,14 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
manager,
shipping_channel_listings,
)
- recalculate_checkout_discount(manager, checkout_info, lines, discounts)
+ invalidate_prices_updated_fields = invalidate_checkout_prices(
+ checkout_info, lines, manager, discounts, save=False
+ )
+ checkout.save(
+ update_fields=shipping_address_updated_fields
+ + invalidate_prices_updated_fields
+ )
manager.checkout_updated(checkout)
+
return CheckoutShippingAddressUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
index a8b54b3793..5ff1a63129 100644
--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py
@@ -7,8 +7,8 @@ from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import (
delete_external_shipping_id,
+ invalidate_checkout_prices,
is_shipping_required,
- recalculate_checkout_discount,
set_external_shipping_id,
)
from ....plugins.webhook.utils import APP_ID_PREFIX
@@ -174,13 +174,17 @@ class CheckoutShippingMethodUpdate(BaseMutation):
delete_external_shipping_id(checkout=checkout)
checkout.shipping_method = shipping_method
+ invalidate_prices_updated_fields = invalidate_checkout_prices(
+ checkout_info, lines, manager, info.context.discounts, save=False
+ )
checkout.save(
- update_fields=["private_metadata", "shipping_method", "last_change"]
+ update_fields=[
+ "private_metadata",
+ "shipping_method",
+ ]
+ + invalidate_prices_updated_fields
)
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
- )
manager.checkout_updated(checkout)
return CheckoutShippingMethodUpdate(checkout=checkout)
@@ -200,12 +204,16 @@ class CheckoutShippingMethodUpdate(BaseMutation):
set_external_shipping_id(checkout=checkout, app_shipping_id=delivery_method.id)
checkout.shipping_method = None
- checkout.save(
- update_fields=["private_metadata", "shipping_method", "last_change"]
+ invalidate_prices_updated_fields = invalidate_checkout_prices(
+ checkout_info, lines, manager, info.context.discounts, save=False
)
-
- recalculate_checkout_discount(
- manager, checkout_info, lines, info.context.discounts
+ checkout.save(
+ update_fields=[
+ "private_metadata",
+ "shipping_method",
+ ]
+ + invalidate_prices_updated_fields
)
manager.checkout_updated(checkout)
+
return CheckoutShippingMethodUpdate(checkout=checkout)
diff --git a/saleor/graphql/checkout/tests/benchmark/conftest.py b/saleor/graphql/checkout/tests/benchmark/conftest.py
index ec77f6ad8c..5b9450fca7 100644
--- a/saleor/graphql/checkout/tests/benchmark/conftest.py
+++ b/saleor/graphql/checkout/tests/benchmark/conftest.py
@@ -46,10 +46,16 @@ def checkout_with_variants_for_cc(checkout_for_cc, stocks_for_cc, product_varian
CheckoutLine.objects.bulk_create(
[
CheckoutLine(
- checkout=checkout_for_cc, variant=product_variant_list[0], quantity=1
+ checkout=checkout_for_cc,
+ variant=product_variant_list[0],
+ quantity=1,
+ currency="USD",
),
CheckoutLine(
- checkout=checkout_for_cc, variant=product_variant_list[1], quantity=1
+ checkout=checkout_for_cc,
+ variant=product_variant_list[1],
+ quantity=1,
+ currency="USD",
),
]
)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index df778a8fad..a41c39d117 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -389,7 +389,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(53):
+ with django_assert_num_queries(55):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -407,7 +407,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(53):
+ with django_assert_num_queries(55):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -656,7 +656,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(56):
+ with django_assert_num_queries(54):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -670,7 +670,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(56):
+ with django_assert_num_queries(54):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -862,9 +862,10 @@ def test_add_checkout_lines_with_external_shipping(
api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
)
assert not response["data"]["checkoutLinesAdd"]["errors"]
- # One api call:
+ # Two api calls:
# - post-mutate() logic used to validate currently selected method
- assert mock_send_request.call_count == 1
+ # - fetch_checkout_prices_if_expired - calculating all prices for checkout
+ assert mock_send_request.call_count == 2
@pytest.mark.django_db
@@ -911,7 +912,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(55):
+ with django_assert_num_queries(53):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -924,7 +925,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(55):
+ with django_assert_num_queries(53):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
diff --git a/saleor/graphql/checkout/tests/benchmark/test_homepage.py b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
index 6e75a4d084..caf8f7d387 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_homepage.py
@@ -1,6 +1,7 @@
from unittest.mock import patch
import pytest
+from django.utils import timezone
from .....checkout.utils import set_external_shipping_id
from ....tests.utils import get_graphql_content
@@ -193,3 +194,77 @@ def test_user_checkout_details_with_external_shipping_method(
# then
assert mock_send_request.call_count == 1
+
+
[email protected]_queries(autouse=False)
+@patch("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_user_checkout_details_with_tax_app(
+ mock_send_request,
+ user_api_client,
+ customer_checkout,
+ tax_app,
+ settings,
+ count_queries,
+):
+ # given
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ mock_json_response = {
+ "currency": "PLN",
+ "total_net_amount": 1080,
+ "total_gross_amount": 1200,
+ "subtotal_net_amount": 1000,
+ "subtotal_gross_amount": 1100,
+ "shipping_price_gross_amount": 100.0,
+ "shipping_price_net_amount": 80.00,
+ "shipping_tax_rate": 0.25,
+ "lines": [
+ {
+ "id": line.pk,
+ "currency": "PLN",
+ "unit_net_amount": 12.34,
+ "unit_gross_amount": 12.34,
+ "total_gross_amount": 12.34,
+ "total_net_amount": 12.34,
+ "tax_rate": 0.23,
+ }
+ for line in customer_checkout.lines.all()
+ ],
+ }
+ mock_send_request.return_value = mock_json_response
+ query = """
+ fragment Price on TaxedMoney {
+ gross {
+ amount
+ currency
+ }
+ net {
+ amount
+ currency
+ }
+ }
+ query {
+ me {
+ checkout {
+ totalPrice {
+ ...Price
+ }
+ subtotalPrice {
+ ...Price
+ }
+ shippingPrice {
+ ...Price
+ }
+ }
+ }
+ }
+ """
+ customer_checkout.price_expiration = timezone.now()
+ customer_checkout.save()
+
+ # when
+ get_graphql_content(user_api_client.post_graphql(query))
+
+ # then
+ customer_checkout.refresh_from_db()
+ assert mock_send_request.call_count == 1
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index 630ae89d81..8e74906c81 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -4,13 +4,13 @@ from unittest import mock
import graphene
import pytest
+from django.utils import timezone
from prices import Money
-from .....checkout import calculations
+from .....checkout import base_calculations, calculations
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import add_variant_to_checkout, set_external_shipping_id
-from .....core.taxes import TaxedMoney
from .....discount import VoucherType
from .....plugins.manager import get_plugins_manager
from .....warehouse.models import Stock
@@ -54,6 +54,11 @@ MUTATION_CHECKOUT_ADD_PROMO_CODE = """
amount
}
}
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
}
}
}
@@ -208,10 +213,8 @@ def test_checkout_add_voucher_code_with_display_gross_prices(
voucher_channel_listing.save()
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: TaxedMoney(
- Money(95, "USD"), Money(100, "USD")
- ),
+ "saleor.checkout.utils.base_calculations.base_checkout_subtotal",
+ lambda *args: Money(100, "USD"),
)
variables = {
@@ -241,10 +244,8 @@ def test_checkout_add_voucher_code_without_display_gross_prices(
voucher_channel_listing.save()
monkeypatch.setattr(
- "saleor.checkout.utils.base_calculations.base_checkout_lines_total",
- lambda checkout_lines, channel, currency, discounts: TaxedMoney(
- Money(95, "USD"), Money(100, "USD")
- ),
+ "saleor.checkout.utils.base_calculations.base_checkout_subtotal",
+ lambda *args: Money(95, "USD"),
)
variables = {
@@ -288,6 +289,7 @@ def test_checkout_add_voucher_code_checkout_with_sale(
subtotal = calculations.checkout_subtotal(
manager=manager, checkout_info=checkout_info, lines=lines, address=address
)
+ checkout_info.checkout.price_expiration = timezone.now()
subtotal_discounted = calculations.checkout_subtotal(
manager=manager,
checkout_info=checkout_info,
@@ -328,6 +330,7 @@ def test_checkout_add_specific_product_voucher_code_checkout_with_sale(
lines=lines,
address=checkout.shipping_address,
)
+ checkout.price_expiration = timezone.now()
checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)
subtotal_discounted = calculations.checkout_subtotal(
manager=manager,
@@ -387,6 +390,7 @@ def test_checkout_add_products_voucher_code_checkout_with_sale(
address=checkout.shipping_address,
)
+ checkout.price_expiration = timezone.now()
checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)
subtotal_discounted = calculations.checkout_subtotal(
manager=manager,
@@ -442,6 +446,7 @@ def test_checkout_add_collection_voucher_code_checkout_with_sale(
lines=lines,
address=checkout.shipping_address,
)
+ checkout.price_expiration = timezone.now()
checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)
subtotal_discounted = calculations.checkout_subtotal(
manager=manager,
@@ -498,6 +503,7 @@ def test_checkout_add_category_code_checkout_with_sale(
lines=lines,
address=checkout.shipping_address,
)
+ checkout.price_expiration = timezone.now()
checkout_info = fetch_checkout_info(checkout, lines, [discount_info], manager)
subtotal_discounted = calculations.checkout_subtotal(
manager=manager,
@@ -711,14 +717,12 @@ def test_checkout_get_total_with_many_gift_card(
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout_with_gift_card)
checkout_info = fetch_checkout_info(checkout_with_gift_card, lines, [], manager)
- taxed_total = calculations.checkout_total(
+ taxed_total = calculations.calculate_checkout_total_with_gift_cards(
manager=manager,
checkout_info=checkout_info,
lines=lines,
address=checkout_with_gift_card.shipping_address,
)
- taxed_total.gross -= checkout_with_gift_card.get_total_gift_cards_balance()
- taxed_total.net -= checkout_with_gift_card.get_total_gift_cards_balance()
total_with_gift_card = (
taxed_total.gross.amount - gift_card_created_by_staff.current_balance_amount
)
@@ -849,6 +853,7 @@ def test_checkout_add_promo_code_invalidate_shipping_method(
checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
variant = variant_with_many_stocks_different_shipping_zones
add_variant_to_checkout(checkout_info, variant, 5)
+ checkout.save()
# Apply voucher
variables = {"id": to_global_id_or_none(checkout), "promoCode": voucher.code}
@@ -972,3 +977,31 @@ def test_checkout_add_shipping_voucher_do_not_invalidate_shipping_method(
assert data["checkout"]["shippingMethod"]["id"] == graphene.Node.to_global_id(
"ShippingMethod", shipping_method.id
)
+
+
+def test_checkout_add_voucher_code_invalidates_price(
+ api_client, checkout_with_item, voucher
+):
+ # given
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+ subtotal = base_calculations.base_checkout_subtotal(
+ lines,
+ checkout_info.channel,
+ checkout_info.checkout.currency,
+ )
+ expected_total = subtotal.amount - voucher.channel_listings.get().discount.amount
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "promoCode": voucher.code,
+ }
+
+ # when
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ # then
+ assert not data["errors"]
+ assert data["checkout"]["voucherCode"] == voucher.code
+ assert data["checkout"]["subtotalPrice"]["gross"]["amount"] == subtotal.amount
+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
index 030a7a7eff..525c434f02 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py
@@ -1,5 +1,8 @@
+from unittest import mock
+
import pytest
+from .....checkout.utils import invalidate_checkout_prices
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -138,8 +141,16 @@ def test_checkout_billing_address_update_by_id_without_street_address_2(
assert checkout.billing_address.city == billing_address["city"].upper()
+ "saleor.graphql.checkout.mutations.checkout_billing_address_update."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_billing_address_update(
- user_api_client, checkout_with_item, graphql_address_data
+ mocked_invalidate_checkout_prices,
+ user_api_client,
+ checkout_with_item,
+ graphql_address_data,
):
checkout = checkout_with_item
assert checkout.shipping_address is None
@@ -186,6 +197,7 @@ def test_checkout_billing_address_update(
assert checkout.billing_address.country == billing_address["country"]
assert checkout.billing_address.city == billing_address["city"].upper()
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
@pytest.mark.parametrize(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index 7dfdba872c..c7a351017c 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -1915,17 +1915,11 @@ def test_complete_checkout_raises_error_for_local_stock(
update_fields=["collection_point", "shipping_address", "billing_address"]
)
- manager = get_plugins_manager()
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- total = calculations.checkout_total(
- manager=manager, checkout_info=checkout_info, lines=lines, address=address
- )
payment = payment_dummy
payment.is_active = True
payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
+ payment.total = Decimal("20")
+ payment.currency = checkout.currency
payment.checkout = checkout
payment.save()
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
index ccb174db6c..cf218d861d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py
@@ -7,7 +7,7 @@ import pytest
from .....account.models import Address
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout_prices
from .....plugins.manager import get_plugins_manager
from .....shipping import models as shipping_models
from .....shipping.utils import convert_to_shipping_method_data
@@ -60,7 +60,13 @@ MUTATION_UPDATE_DELIVERY_METHOD = """
"saleor.graphql.checkout.mutations.checkout_delivery_method_update."
"clean_delivery_method"
)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_delivery_method_update(
+ mock_invalidate_checkout_prices,
mock_clean_delivery,
api_client,
delivery_method,
@@ -101,6 +107,7 @@ def test_checkout_delivery_method_update(
if is_valid_delivery_method:
assert not errors
assert getattr(checkout, attribute_name) == delivery_method
+ assert mock_invalidate_checkout_prices.call_count == 1
else:
assert len(errors) == 1
assert errors[0]["field"] == "deliveryMethodId"
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
index 7b935a375c..b1320c0706 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
@@ -2,12 +2,13 @@ from unittest import mock
import graphene
-from .....checkout import calculations
+from .....checkout import base_calculations
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import (
add_variant_to_checkout,
add_voucher_to_checkout,
calculate_checkout_quantity,
+ invalidate_checkout_prices,
)
from .....plugins.manager import get_plugins_manager
from .....warehouse.models import Reservation
@@ -41,7 +42,13 @@ MUTATION_CHECKOUT_LINE_DELETE = """
"update_checkout_shipping_method_if_invalid",
wraps=update_checkout_shipping_method_if_invalid,
)
+ "saleor.graphql.checkout.mutations.checkout_line_delete."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_line_delete(
+ mocked_invalidate_checkout_prices,
mocked_update_shipping_method,
user_api_client,
checkout_line_with_reservation_in_many_stocks,
@@ -72,6 +79,7 @@ def test_checkout_line_delete(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
def test_checkout_lines_delete_with_not_applicable_voucher(
@@ -80,14 +88,13 @@ def test_checkout_lines_delete_with_not_applicable_voucher(
manager = get_plugins_manager()
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
- subtotal = calculations.checkout_subtotal(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=checkout_with_item.shipping_address,
+ subtotal = base_calculations.base_checkout_subtotal(
+ lines,
+ checkout_info.channel,
+ checkout_info.checkout.currency,
)
voucher.channel_listings.filter(channel=channel_USD).update(
- min_spent_amount=subtotal.gross.amount
+ min_spent_amount=subtotal.amount
)
checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 5b27d7fe4d..34a984aaaf 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -10,7 +10,7 @@ from django.utils import timezone
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
-from .....checkout.utils import calculate_checkout_quantity
+from .....checkout.utils import calculate_checkout_quantity, invalidate_checkout_prices
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing
from .....warehouse import WarehouseClickAndCollectOption
@@ -49,8 +49,17 @@ MUTATION_CHECKOUT_LINES_ADD = """
"update_checkout_shipping_method_if_invalid",
wraps=update_checkout_shipping_method_if_invalid,
)
+ "saleor.graphql.checkout.mutations.checkout_lines_add."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_lines_add(
- mocked_update_shipping_method, user_api_client, checkout_with_item, stock
+ mocked_invalidate_checkout_prices,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_item,
+ stock,
):
variant = stock.product_variant
checkout = checkout_with_item
@@ -82,6 +91,7 @@ def test_checkout_lines_add(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
def test_checkout_lines_add_with_reservations(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
index 4426159c53..0e297cb9bd 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py
@@ -4,6 +4,7 @@ import graphene
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.utils import invalidate_checkout_prices
from .....plugins.manager import get_plugins_manager
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -38,8 +39,16 @@ MUTATION_CHECKOUT_LINES_DELETE = """
"update_checkout_shipping_method_if_invalid",
wraps=update_checkout_shipping_method_if_invalid,
)
+ "saleor.graphql.checkout.mutations.checkout_lines_delete."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_lines_delete(
- mocked_update_shipping_method, user_api_client, checkout_with_items
+ mocked_invalidate_checkout_prices,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_items,
):
checkout = checkout_with_items
checkout_lines_count = checkout.lines.count()
@@ -67,6 +76,7 @@ def test_checkout_lines_delete(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
def test_checkout_lines_delete_invalid_checkout_id(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 1202338080..044ff56356 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -9,7 +9,11 @@ from django.utils import timezone
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
-from .....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
+from .....checkout.utils import (
+ add_variant_to_checkout,
+ calculate_checkout_quantity,
+ invalidate_checkout_prices,
+)
from .....plugins.manager import get_plugins_manager
from .....product.models import ProductChannelListing
from .....warehouse.models import Reservation, Stock
@@ -59,8 +63,16 @@ MUTATION_CHECKOUT_LINES_UPDATE = """
"update_checkout_shipping_method_if_invalid",
wraps=update_checkout_shipping_method_if_invalid,
)
+ "saleor.graphql.checkout.mutations.checkout_lines_add."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_lines_update(
- mocked_update_shipping_method, user_api_client, checkout_with_item
+ mocked_invalidate_checkout_prices,
+ mocked_update_shipping_method,
+ user_api_client,
+ checkout_with_item,
):
checkout = checkout_with_item
lines, _ = fetch_checkout_lines(checkout)
@@ -95,6 +107,7 @@ def test_checkout_lines_update(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
def test_checkout_lines_update_checkout_with_voucher(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
index 6fc796ca25..3c347f427b 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py
@@ -1,6 +1,12 @@
+from datetime import timedelta
+
import graphene
+from django.utils import timezone
+from .....checkout import base_calculations
from .....checkout.error_codes import CheckoutErrorCode
+from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....plugins.manager import get_plugins_manager
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -20,6 +26,16 @@ MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """
id
last4CodeChars
}
+ totalPrice {
+ gross {
+ amount
+ }
+ }
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
}
}
}
@@ -116,6 +132,8 @@ def test_checkout_remove_one_of_gift_cards(
def test_checkout_remove_promo_code_invalid_promo_code(api_client, checkout_with_item):
+ checkout_with_item.price_expiration = timezone.now() + timedelta(days=2)
+ checkout_with_item.save(update_fields=["price_expiration"])
previous_checkout_last_change = checkout_with_item.last_change
variables = {
"id": to_global_id_or_none(checkout_with_item),
@@ -191,7 +209,7 @@ def test_checkout_remove_promo_code_id_and_code_given(
assert checkout_with_voucher.voucher_code is not None
variables = {
- "token": checkout_with_voucher.token,
+ "id": to_global_id_or_none(checkout_with_voucher),
"promoCode": checkout_with_voucher.voucher_code,
"promoCodeId": graphene.Node.to_global_id("GiftCard", gift_card.id),
}
@@ -208,7 +226,7 @@ def test_checkout_remove_promo_code_no_id_and_code_given(
assert checkout_with_voucher.voucher_code is not None
variables = {
- "token": checkout_with_voucher.token,
+ "id": to_global_id_or_none(checkout_with_voucher),
}
data = _mutate_checkout_remove_promo_code(api_client, variables)
@@ -223,7 +241,7 @@ def test_checkout_remove_promo_code_id_does_not_exist(
assert checkout_with_voucher.voucher_code is not None
variables = {
- "token": checkout_with_voucher.token,
+ "id": to_global_id_or_none(checkout_with_voucher),
"promoCodeId": "Abc",
}
@@ -240,7 +258,7 @@ def test_checkout_remove_promo_code_invalid_object_type(
assert checkout_with_voucher.voucher_code is not None
variables = {
- "token": checkout_with_voucher.token,
+ "id": to_global_id_or_none(checkout_with_voucher),
"promoCodeId": graphene.Node.to_global_id("Product", gift_card.id),
}
@@ -249,3 +267,33 @@ def test_checkout_remove_promo_code_invalid_object_type(
assert data["errors"]
assert data["errors"][0]["code"] == CheckoutErrorCode.NOT_FOUND.name
assert data["errors"][0]["field"] == "promoCodeId"
+
+
+def test_checkout_remove_voucher_code_invalidates_price(
+ api_client, checkout_with_item, voucher
+):
+ # given
+ checkout_with_item.price_expiration = timezone.now() + timedelta(days=2)
+ checkout_with_item.voucher_code = voucher.code
+ checkout_with_item.save(update_fields=["voucher_code", "price_expiration"])
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+ subtotal = base_calculations.base_checkout_subtotal(
+ lines,
+ checkout_info.channel,
+ checkout_info.checkout.currency,
+ )
+ expected_total = subtotal.amount
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "promoCode": voucher.code,
+ }
+
+ # when
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ # then
+ assert not data["errors"]
+ assert data["checkout"]["subtotalPrice"]["gross"]["amount"] == subtotal.amount
+ assert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
index 7df3fcca0b..3e36090849 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py
@@ -8,7 +8,11 @@ from django.utils import timezone
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
-from .....checkout.utils import add_variant_to_checkout, add_voucher_to_checkout
+from .....checkout.utils import (
+ add_variant_to_checkout,
+ add_voucher_to_checkout,
+ invalidate_checkout_prices,
+)
from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....warehouse.models import Reservation, Stock
@@ -49,7 +53,13 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE = """
"update_checkout_shipping_method_if_invalid",
wraps=update_checkout_shipping_method_if_invalid,
)
+ "saleor.graphql.checkout.mutations.checkout_shipping_address_update."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_shipping_address_update(
+ mocked_invalidate_checkout_prices,
mocked_update_shipping_method,
user_api_client,
checkout_with_item,
@@ -89,6 +99,7 @@ def test_checkout_shipping_address_update(
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
@mock.patch(
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
index 328445372c..1b141e7aba 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py
@@ -11,7 +11,7 @@ from .....checkout.fetch import (
fetch_checkout_lines,
get_delivery_method_info,
)
-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID
+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout_prices
from .....plugins.base_plugin import ExcludedShippingMethod
from .....plugins.manager import get_plugins_manager
from .....shipping import models as shipping_models
@@ -43,7 +43,13 @@ MUTATION_UPDATE_SHIPPING_METHOD = """
"saleor.graphql.checkout.mutations.checkout_shipping_method_update."
"clean_delivery_method"
)
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
def test_checkout_shipping_method_update(
+ mocked_invalidate_checkout_prices,
mock_clean_shipping,
staff_api_client,
shipping_method,
@@ -86,6 +92,7 @@ def test_checkout_shipping_method_update(
assert data["checkout"]["token"] == str(checkout.token)
assert checkout.shipping_method == shipping_method
assert checkout.last_change != previous_last_change
+ assert mocked_invalidate_checkout_prices.call_count == 1
else:
assert len(errors) == 1
assert errors[0]["field"] == "shippingMethod"
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 4a6e0523e3..9ec99ca439 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -1389,7 +1389,7 @@ def test_checkout_prices(user_api_client, checkout_with_item):
lines=lines,
checkout_line_info=line_info,
discounts=[],
- ).price_with_discounts
+ )
assert (
data["lines"][0]["unitPrice"]["gross"]["amount"]
== line_total_price.gross.amount / line_info.line.quantity
@@ -1446,7 +1446,7 @@ def test_checkout_prices_checkout_with_custom_prices(
)
assert (
data["totalPrice"]["gross"]["amount"]
- == checkout_line.quantity * price_override + shipping_price.gross.amount
+ == checkout_line.quantity * price_override + shipping_price.amount
)
assert (
data["subtotalPrice"]["gross"]["amount"]
@@ -1508,7 +1508,7 @@ def test_checkout_prices_with_sales(user_api_client, checkout_with_item, discoun
lines=lines,
checkout_line_info=line_info,
discounts=[discount_info],
- ).price_with_discounts
+ )
assert (
data["lines"][0]["unitPrice"]["gross"]["amount"]
== line_total_price.gross.amount / line_info.line.quantity
@@ -1572,17 +1572,12 @@ def test_checkout_prices_with_specific_voucher(
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
assert line_info.line.quantity > 0
- line_total_prices = calculations.checkout_line_total(
+ line_total_price = calculations.checkout_line_total(
manager=manager,
checkout_info=checkout_info,
lines=lines,
checkout_line_info=line_info,
)
- assert (
- line_total_prices.price_with_discounts != line_total_prices.undiscounted_price
- )
- assert line_total_prices.price_with_discounts != line_total_prices.price_with_sale
- line_total_price = line_total_prices.price_with_discounts
assert (
data["lines"][0]["unitPrice"]["gross"]["amount"]
== line_total_price.gross.amount / line_info.line.quantity
@@ -1644,17 +1639,12 @@ def test_checkout_prices_with_voucher_once_per_order(
assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)
line_info = lines[0]
assert line_info.line.quantity > 0
- line_total_prices = calculations.checkout_line_total(
+ line_total_price = calculations.checkout_line_total(
manager=manager,
checkout_info=checkout_info,
lines=lines,
checkout_line_info=line_info,
)
- assert (
- line_total_prices.price_with_discounts != line_total_prices.undiscounted_price
- )
- assert line_total_prices.price_with_discounts != line_total_prices.price_with_sale
- line_total_price = line_total_prices.price_with_discounts
assert data["lines"][0]["unitPrice"]["gross"]["amount"] == float(
quantize_price(
line_total_price.gross.amount / line_info.line.quantity, checkout.currency
diff --git a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
new file mode 100644
index 0000000000..5b342b6f19
--- /dev/null
+++ b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py
@@ -0,0 +1,407 @@
+from datetime import timedelta
+from unittest import mock
+from unittest.mock import patch
+
+import graphene
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....checkout.utils import invalidate_checkout_prices
+from ....plugins.manager import get_plugins_manager
+from ...tests.utils import get_graphql_content
+
+ADD_CHECKOUT_LINES = """
+mutation addCheckoutLines($checkoutId: ID!, $line: CheckoutLineInput!) {
+ checkoutLinesAdd(checkoutId: $checkoutId, lines: [$line]) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout_prices"
+)
+def test_checkout_lines_add_invalidate_prices(
+ mocked_function,
+ api_client,
+ checkout_with_items,
+ stock,
+):
+ # given
+ manager = get_plugins_manager()
+ query = ADD_CHECKOUT_LINES
+ variables = {
+ "checkoutId": graphene.Node.to_global_id("Checkout", checkout_with_items.pk),
+ "line": {
+ "quantity": 1,
+ "variantId": graphene.Node.to_global_id(
+ "ProductVariant", stock.product_variant.pk
+ ),
+ },
+ }
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ assert not response["data"]["checkoutLinesAdd"]["errors"]
+ checkout_with_items.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ mocked_function.assert_called_once_with(
+ checkout_info, lines, mock.ANY, [], save=True
+ )
+
+
+UPDATE_CHECKOUT_LINES = """
+mutation updateCheckoutLines($token: UUID!, $line: CheckoutLineUpdateInput!) {
+ checkoutLinesUpdate(token: $token, lines: [$line]) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout_prices"
+)
+def test_checkout_lines_update_invalidate_prices(
+ mocked_function,
+ api_client,
+ checkout_with_items,
+ stock,
+):
+ # given
+ manager = get_plugins_manager()
+ query = UPDATE_CHECKOUT_LINES
+ variables = {
+ "token": checkout_with_items.token,
+ "line": {
+ "quantity": 1,
+ "variantId": graphene.Node.to_global_id(
+ "ProductVariant", stock.product_variant.pk
+ ),
+ },
+ }
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ assert not response["data"]["checkoutLinesUpdate"]["errors"]
+ checkout_with_items.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ mocked_function.assert_called_once_with(
+ checkout_info, lines, mock.ANY, [], save=True
+ )
+
+
+DELETE_CHECKOUT_LINES = """
+mutation deleteCheckoutLines($token: UUID!, $lineId: ID!){
+ checkoutLinesDelete(token: $token, linesIds: [$lineId]) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout_prices"
+)
+def test_checkout_lines_delete_invalidate_prices(
+ mocked_function,
+ api_client,
+ checkout_with_items,
+):
+ # given
+ manager = get_plugins_manager()
+ query = DELETE_CHECKOUT_LINES
+ variables = {
+ "token": checkout_with_items.token,
+ "lineId": graphene.Node.to_global_id(
+ "CheckoutLine", checkout_with_items.lines.first().pk
+ ),
+ }
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ assert not response["data"]["checkoutLinesDelete"]["errors"]
+ checkout_with_items.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ mocked_function.assert_called_once_with(
+ checkout_info, lines, mock.ANY, [], save=True
+ )
+
+
+DELETE_CHECKOUT_LINE = """
+mutation deleteCheckoutLine($token: UUID!, $lineId: ID!){
+ checkoutLineDelete(token: $token, lineId: $lineId) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout_prices"
+)
+def test_checkout_line_delete_invalidate_prices(
+ mocked_function,
+ api_client,
+ checkout_with_items,
+):
+ # given
+ manager = get_plugins_manager()
+ query = DELETE_CHECKOUT_LINE
+ variables = {
+ "token": checkout_with_items.token,
+ "lineId": graphene.Node.to_global_id(
+ "CheckoutLine", checkout_with_items.lines.first().pk
+ ),
+ }
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ assert not response["data"]["checkoutLineDelete"]["errors"]
+ checkout_with_items.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ mocked_function.assert_called_once_with(
+ checkout_info, lines, mock.ANY, [], save=True
+ )
+
+
+UPDATE_CHECKOUT_SHIPPING_ADDRESS = """
+mutation UpdateCheckoutShippingAddress($token: UUID!, $address: AddressInput!) {
+ checkoutShippingAddressUpdate(token: $token, shippingAddress: $address) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_shipping_address_update"
+ ".invalidate_checkout_prices"
+)
+def test_checkout_shipping_address_update_invalidate_prices(
+ mocked_function,
+ api_client,
+ checkout_with_items,
+ graphql_address_data,
+ plugins_manager,
+):
+ # given
+ manager = get_plugins_manager()
+ query = UPDATE_CHECKOUT_SHIPPING_ADDRESS
+ variables = {
+ "token": checkout_with_items.token,
+ "address": graphql_address_data,
+ }
+ mocked_function.return_value = []
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ assert not response["data"]["checkoutShippingAddressUpdate"]["errors"]
+ checkout_with_items.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ mocked_function.assert_called_once_with(
+ checkout_info, lines, mock.ANY, [], save=False
+ )
+
+
+UPDATE_CHECKOUT_BILLING_ADDRESS = """
+mutation UpdateCheckoutBillingAddress($token: UUID!, $address: AddressInput!) {
+ checkoutBillingAddressUpdate(token: $token, billingAddress: $address) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.checkout.mutations.checkout_billing_address_update"
+ ".invalidate_checkout_prices"
+)
+def test_checkout_billing_address_update_invalidate_prices(
+ mocked_function,
+ api_client,
+ checkout_with_items,
+ graphql_address_data,
+):
+ # given
+ manager = get_plugins_manager()
+ query = UPDATE_CHECKOUT_BILLING_ADDRESS
+ variables = {
+ "token": checkout_with_items.token,
+ "address": graphql_address_data,
+ }
+ mocked_function.return_value = []
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ assert not response["data"]["checkoutBillingAddressUpdate"]["errors"]
+ checkout_with_items.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+ mocked_function.assert_called_once_with(
+ checkout_info, lines, mock.ANY, [], recalculate_discount=False, save=False
+ )
+
+
+UPDATE_CHECKOUT_SHIPPING_METHOD = """
+mutation updateCheckoutShippingOptions($token: UUID!, $shippingMethodId: ID!) {
+ checkoutShippingMethodUpdate(token: $token, shippingMethodId: $shippingMethodId) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+ "saleor.graphql.checkout.mutations.checkout_shipping_method_update."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
+def test_checkout_shipping_method_update_invalidate_prices(
+ mocked_invalidate_checkout_prices,
+ api_client,
+ checkout_with_shipping_address,
+ shipping_method,
+):
+ # given
+ checkout = checkout_with_shipping_address
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
+ query = UPDATE_CHECKOUT_SHIPPING_METHOD
+ variables = {
+ "token": checkout.token,
+ "shippingMethodId": graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ ),
+ }
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ checkout.refresh_from_db()
+ assert not response["data"]["checkoutShippingMethodUpdate"]["errors"]
+ assert mocked_invalidate_checkout_prices.call_count == 1
+
+
+UPDATE_CHECKOUT_DELIVERY_METHOD = """
+mutation updateCheckoutDeliveryOptions($token: UUID!, $deliveryMethodId: ID!) {
+ checkoutDeliveryMethodUpdate(token: $token, deliveryMethodId: $deliveryMethodId) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+ "saleor.graphql.checkout.mutations.checkout_delivery_method_update."
+ "invalidate_checkout_prices",
+ wraps=invalidate_checkout_prices,
+)
+def test_checkout_delivery_method_update_invalidate_prices(
+ mocked_invalidate_checkout_prices,
+ api_client,
+ checkout_with_shipping_address_for_cc,
+ warehouses_for_cc,
+):
+ checkout = checkout_with_shipping_address_for_cc
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
+ query = UPDATE_CHECKOUT_DELIVERY_METHOD
+ variables = {
+ "token": checkout.token,
+ "deliveryMethodId": graphene.Node.to_global_id(
+ "Warehouse", warehouses_for_cc[1].pk
+ ),
+ }
+
+ # when
+ response = get_graphql_content(api_client.post_graphql(query, variables))
+
+ # then
+ checkout.refresh_from_db()
+ assert not response["data"]["checkoutDeliveryMethodUpdate"]["errors"]
+ assert mocked_invalidate_checkout_prices.call_count == 1
+
+
+@freeze_time("2020-12-12 12:00:00")
+def test_invalidate_checkout_prices_with_save(checkout, plugins_manager):
+ # given
+ checkout.price_expiration = timezone.now() + timedelta(minutes=5)
+ checkout.save(update_fields=["price_expiration"])
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+
+ # when
+ updated_fields = invalidate_checkout_prices(
+ checkout_info, lines, plugins_manager, [], save=True
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now()
+ assert updated_fields == ["price_expiration", "last_change"]
+
+
+@freeze_time("2020-12-12 12:00:00")
+def test_invalidate_checkout_prices_without_save(checkout, plugins_manager):
+ # given
+ original_expiration = checkout.price_expiration = timezone.now() + timedelta(
+ minutes=5
+ )
+ checkout.save(update_fields=["price_expiration"])
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugins_manager)
+
+ # when
+ updated_fields = invalidate_checkout_prices(
+ checkout_info, lines, plugins_manager, [], save=False
+ )
+
+ # then
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == original_expiration
+ assert updated_fields == ["price_expiration", "last_change"]
diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
index f8e037e410..b50443e71e 100644
--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
@@ -81,7 +81,7 @@ def test_checkout_totals_use_discounts(
lines=lines,
checkout_line_info=checkout_line_info,
discounts=discounts,
- ).price_with_sale
+ )
assert data["lines"][0]["totalPrice"]["gross"]["amount"] == line_total.gross.amount
@@ -95,6 +95,11 @@ query getCheckout($id: ID) {
amount
}
}
+ subtotalPrice {
+ gross {
+ amount
+ }
+ }
}
}
"""
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 0d14b83448..46e4425ef9 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -2,6 +2,10 @@ import graphene
from promise import Promise
from ...checkout import calculations, models
+from ...checkout.base_calculations import (
+ calculate_undiscounted_base_line_total_price,
+ calculate_undiscounted_base_line_unit_price,
+)
from ...checkout.utils import get_valid_collection_points_for_checkout
from ...core.permissions import (
AccountPermissions,
@@ -128,8 +132,6 @@ class CheckoutLine(ModelObjectType):
@staticmethod
def resolve_unit_price(root, info):
- # Temporary solution in new tax interface introduced in PR#9526
- # this value will be denormalized and store in checkout line.
def with_checkout(checkout):
discounts = DiscountsByDateTimeLoader(info.context).load(
info.context.request_time
@@ -149,17 +151,13 @@ class CheckoutLine(ModelObjectType):
) = data
for line_info in lines:
if line_info.line.pk == root.pk:
- address = (
- checkout_info.shipping_address
- or checkout_info.billing_address
- )
- return info.context.plugins.calculate_checkout_line_unit_price(
+ return calculations.checkout_line_unit_price(
+ manager=info.context.plugins,
checkout_info=checkout_info,
lines=lines,
checkout_line_info=line_info,
- address=address,
discounts=discounts,
- ).price_with_discounts
+ )
return None
return Promise.all(
@@ -178,12 +176,7 @@ class CheckoutLine(ModelObjectType):
@staticmethod
def resolve_undiscounted_unit_price(root, info):
- # Temporary solution in new tax interface introduced in PR#9526
- # this value will be denormalized and store in checkout line.
def with_checkout(checkout):
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
@@ -193,38 +186,19 @@ class CheckoutLine(ModelObjectType):
def calculate_undiscounted_unit_price(data):
(
- discounts,
checkout_info,
lines,
) = data
for line_info in lines:
if line_info.line.pk == root.pk:
- address = (
- checkout_info.shipping_address
- or checkout_info.billing_address
- )
- include_taxes_in_prices = (
- info.context.site.settings.include_taxes_in_prices
- )
- undiscounted_price = (
- info.context.plugins.calculate_checkout_line_unit_price(
- checkout_info=checkout_info,
- lines=lines,
- checkout_line_info=line_info,
- address=address,
- discounts=discounts,
- ).undiscounted_price
- )
- return (
- undiscounted_price.gross
- if include_taxes_in_prices
- else undiscounted_price.net
+ return calculate_undiscounted_base_line_unit_price(
+ line_info, checkout_info.channel
)
+
return None
return Promise.all(
[
- discounts,
checkout_info,
lines,
]
@@ -258,17 +232,13 @@ class CheckoutLine(ModelObjectType):
) = data
for line_info in lines:
if line_info.line.pk == root.pk:
- address = (
- checkout_info.shipping_address
- or checkout_info.billing_address
- )
- return info.context.plugins.calculate_checkout_line_total(
+ return calculations.checkout_line_total(
+ manager=info.context.plugins,
checkout_info=checkout_info,
lines=lines,
checkout_line_info=line_info,
- address=address,
discounts=discounts,
- ).price_with_discounts
+ )
return None
return Promise.all(
@@ -287,12 +257,7 @@ class CheckoutLine(ModelObjectType):
@staticmethod
def resolve_undiscounted_total_price(root, info):
- # Temporary solution in new tax interface introduced in PR#9526
- # this value will be denormalized and store in checkout line.
def with_checkout(checkout):
- discounts = DiscountsByDateTimeLoader(info.context).load(
- info.context.request_time
- )
checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
checkout.token
)
@@ -302,38 +267,18 @@ class CheckoutLine(ModelObjectType):
def calculate_undiscounted_total_price(data):
(
- discounts,
checkout_info,
lines,
) = data
for line_info in lines:
if line_info.line.pk == root.pk:
- address = (
- checkout_info.shipping_address
- or checkout_info.billing_address
- )
- include_taxes_in_prices = (
- info.context.site.settings.include_taxes_in_prices
- )
- undiscounted_price = (
- info.context.plugins.calculate_checkout_line_total(
- checkout_info=checkout_info,
- lines=lines,
- checkout_line_info=line_info,
- address=address,
- discounts=discounts,
- ).undiscounted_price
- )
- return (
- undiscounted_price.gross
- if include_taxes_in_prices
- else undiscounted_price.net
+ return calculate_undiscounted_base_line_total_price(
+ line_info, checkout_info.channel
)
return None
return Promise.all(
[
- discounts,
checkout_info,
lines,
]
@@ -582,15 +527,12 @@ class Checkout(ModelObjectType):
def resolve_total_price(root: models.Checkout, info):
def calculate_total_price(data):
address, lines, checkout_info, discounts = data
- taxed_total = (
- calculations.checkout_total(
- manager=info.context.plugins,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- discounts=discounts,
- )
- - root.get_total_gift_cards_balance()
+ taxed_total = calculations.calculate_checkout_total_with_gift_cards(
+ manager=info.context.plugins,
+ checkout_info=checkout_info,
+ lines=lines,
+ address=address,
+ discounts=discounts,
)
return max(taxed_total, zero_taxed_money(root.currency))
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 6660b2497c..00798a0e02 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -8,6 +8,7 @@ from ....core.taxes import zero_taxed_money
from ....core.tracing import traced_atomic_transaction
from ....order import OrderStatus, models
from ....order.actions import order_created
+from ....order.calculations import fetch_order_prices_if_expired
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderInfo, OrderLineInfo
from ....order.search import prepare_order_search_vector_value
@@ -67,6 +68,7 @@ class DraftOrderComplete(BaseMutation):
only_type=Order,
qs=models.Order.objects.prefetch_related("lines__variant"),
)
+ order, _ = fetch_order_prices_if_expired(order, manager)
cls.validate_order(order)
country = get_order_country(order)
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 6e0dd316ec..fa3130a0b5 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -13,7 +13,11 @@ from ....core.utils.url import validate_storefront_url
from ....order import OrderOrigin, OrderStatus, events, models
from ....order.error_codes import OrderErrorCode
from ....order.search import update_order_search_vector
-from ....order.utils import add_variant_to_order, recalculate_order, update_order_prices
+from ....order.utils import (
+ add_variant_to_order,
+ invalidate_order_prices,
+ recalculate_order_weight,
+)
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...channel.types import Channel
@@ -255,11 +259,11 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
)
@classmethod
- def _commit_changes(cls, info, instance, cleaned_input, new_instance):
+ def _commit_changes(cls, info, instance, cleaned_input, is_new_instance):
super().save(info, instance, cleaned_input)
# Create draft created event if the instance is from scratch
- if new_instance:
+ if is_new_instance:
events.draft_order_created_event(
order=instance, user=info.context.user, app=info.context.app
)
@@ -269,37 +273,24 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
)
@classmethod
- def _refresh_lines_unit_price(cls, info, instance, cleaned_input, new_instance):
- if new_instance:
- # It is a new instance, all new lines have already updated prices.
- return
- shipping_address = cleaned_input.get("shipping_address")
- if shipping_address and instance.is_shipping_required():
- update_order_prices(
- instance,
- info.context.plugins,
- info.context.site.settings.include_taxes_in_prices,
- )
- billing_address = cleaned_input.get("billing_address")
- if billing_address and not instance.is_shipping_required():
- update_order_prices(
- instance,
- info.context.plugins,
- info.context.site.settings.include_taxes_in_prices,
- )
+ def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
+ # Force price recalculation for all new instances
+ return is_new_instance
@classmethod
def save(cls, info, instance, cleaned_input):
- return cls._save_draft_order(info, instance, cleaned_input, new_instance=True)
+ return cls._save_draft_order(
+ info, instance, cleaned_input, is_new_instance=True
+ )
@classmethod
@traced_atomic_transaction()
- def _save_draft_order(cls, info, instance, cleaned_input, *, new_instance):
+ def _save_draft_order(cls, info, instance, cleaned_input, *, is_new_instance):
# Process addresses
cls._save_addresses(info, instance, cleaned_input)
# Save any changes create/update the draft
- cls._commit_changes(info, instance, cleaned_input, new_instance)
+ cls._commit_changes(info, instance, cleaned_input, is_new_instance)
try:
# Process any lines to add
@@ -309,15 +300,13 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
cleaned_input.get("quantities"),
cleaned_input.get("variants"),
)
-
- cls._refresh_lines_unit_price(info, instance, cleaned_input, new_instance)
except TaxError as tax_error:
raise ValidationError(
"Unable to calculate taxes - %s" % str(tax_error),
code=OrderErrorCode.TAX_ERROR.value,
)
- if new_instance:
+ if is_new_instance:
transaction.on_commit(
lambda: info.context.plugins.draft_order_created(instance)
)
@@ -328,5 +317,11 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
)
# Post-process the results
- recalculate_order(instance)
- update_order_search_vector(instance)
+ updated_fields = ["weight", "search_vector", "updated_at"]
+ if cls.should_invalidate_prices(instance, cleaned_input, is_new_instance):
+ invalidate_order_prices(instance)
+ updated_fields.append("should_refresh_prices")
+ recalculate_order_weight(instance)
+ update_order_search_vector(instance, save=False)
+
+ instance.save(update_fields=updated_fields)
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
index 561842abd5..9f4def7efe 100644
--- a/saleor/graphql/order/mutations/draft_order_update.py
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -41,6 +41,19 @@ class DraftOrderUpdate(DraftOrderCreate):
)
return instance
+ @classmethod
+ def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
+ return any(
+ cleaned_input.get(field) is not None
+ for field in [
+ "shipping_address",
+ "billing_address",
+ "shipping_method",
+ ]
+ )
+
@classmethod
def save(cls, info, instance, cleaned_input):
- return cls._save_draft_order(info, instance, cleaned_input, new_instance=False)
+ return cls._save_draft_order(
+ info, instance, cleaned_input, is_new_instance=False
+ )
diff --git a/saleor/graphql/order/mutations/order_discount_add.py b/saleor/graphql/order/mutations/order_discount_add.py
index 34eb96c84a..6fbcd83645 100644
--- a/saleor/graphql/order/mutations/order_discount_add.py
+++ b/saleor/graphql/order/mutations/order_discount_add.py
@@ -4,6 +4,7 @@ from django.core.exceptions import ValidationError
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events
+from ....order.calculations import fetch_order_prices_if_expired
from ....order.error_codes import OrderErrorCode
from ....order.utils import create_order_discount_for_order, get_order_discounts
from ...core.types import OrderError
@@ -50,6 +51,7 @@ class OrderDiscountAdd(OrderDiscountCommon):
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
+ manager = info.context.plugins
order = cls.get_node_or_error(info, data.get("order_id"), only_type=Order)
input = data.get("input", {})
cls.validate(info, order, input)
@@ -62,6 +64,11 @@ class OrderDiscountAdd(OrderDiscountCommon):
order, reason, value_type, value
)
+ # Calling refreshing prices because it's set proper discount amount on
+ # on OrderDiscount.
+ order, _ = fetch_order_prices_if_expired(order, manager, force_update=True)
+ order_discount.refresh_from_db()
+
events.order_discount_added_event(
order=order,
user=info.context.user,
diff --git a/saleor/graphql/order/mutations/order_discount_common.py b/saleor/graphql/order/mutations/order_discount_common.py
index 4e951a778d..e8777e498c 100644
--- a/saleor/graphql/order/mutations/order_discount_common.py
+++ b/saleor/graphql/order/mutations/order_discount_common.py
@@ -2,9 +2,7 @@ import graphene
from django.core.exceptions import ValidationError
from prices import Money
-from ....order import models
from ....order.error_codes import OrderErrorCode
-from ....order.utils import recalculate_order_discounts, recalculate_order_prices
from ...core.mutations import BaseMutation
from ...core.scalars import PositiveDecimal
from ...discount.enums import DiscountValueTypeEnum
@@ -61,18 +59,3 @@ class OrderDiscountCommon(BaseMutation):
elif value > 100:
error_msg = f"The percentage value ({value}) cannot be higher than 100."
raise cls._validation_error_for_input_value(error_msg)
-
- @classmethod
- def recalculate_order(cls, order: models.Order):
- """Recalculate order data and save them."""
- recalculate_order_prices(order)
- recalculate_order_discounts(order)
- order.save(
- update_fields=[
- "total_net_amount",
- "total_gross_amount",
- "undiscounted_total_net_amount",
- "undiscounted_total_gross_amount",
- "updated_at",
- ]
- )
diff --git a/saleor/graphql/order/mutations/order_discount_delete.py b/saleor/graphql/order/mutations/order_discount_delete.py
index eadc5f32d5..ee5723402e 100644
--- a/saleor/graphql/order/mutations/order_discount_delete.py
+++ b/saleor/graphql/order/mutations/order_discount_delete.py
@@ -4,7 +4,7 @@ from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.search import update_order_search_vector
-from ....order.utils import remove_order_discount_from_order
+from ....order.utils import invalidate_order_prices, remove_order_discount_from_order
from ...core.types import OrderError
from ..types import Order
from .order_discount_common import OrderDiscountCommon
@@ -43,7 +43,9 @@ class OrderDiscountDelete(OrderDiscountCommon):
order.refresh_from_db()
- cls.recalculate_order(order)
- update_order_search_vector(order)
-
+ update_order_search_vector(order, save=False)
+ invalidate_order_prices(order)
+ order.save(
+ update_fields=["should_refresh_prices", "search_vector", "updated_at"]
+ )
return OrderDiscountDelete(order=order)
diff --git a/saleor/graphql/order/mutations/order_discount_update.py b/saleor/graphql/order/mutations/order_discount_update.py
index a243e02ff9..ff35846029 100644
--- a/saleor/graphql/order/mutations/order_discount_update.py
+++ b/saleor/graphql/order/mutations/order_discount_update.py
@@ -5,6 +5,7 @@ import graphene
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events
+from ....order.calculations import fetch_order_prices_if_expired
from ...core.types import OrderError
from ..types import Order
from .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput
@@ -39,6 +40,7 @@ class OrderDiscountUpdate(OrderDiscountCommon):
@classmethod
@traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
+ manager = info.context.plugins
order_discount = cls.get_node_or_error(
info, data.get("discount_id"), only_type="OrderDiscount"
)
@@ -56,14 +58,14 @@ class OrderDiscountUpdate(OrderDiscountCommon):
order_discount.value = value
order_discount.value_type = value_type
order_discount.save()
-
- cls.recalculate_order(order)
-
if (
order_discount_before_update.value_type != value_type
or order_discount_before_update.value != value
):
# call update event only when we changed the type or value of the discount
+ # Calling refreshing prices because it's set proper discount amount on
+ # on OrderDiscount.
+ fetch_order_prices_if_expired(order, manager, force_update=True)
order_discount.refresh_from_db()
events.order_discount_updated_event(
order=order,
diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.py
index 09fcd8e5e8..2e19e46a6a 100644
--- a/saleor/graphql/order/mutations/order_line_delete.py
+++ b/saleor/graphql/order/mutations/order_line_delete.py
@@ -7,7 +7,11 @@ from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.fetch import OrderLineInfo
from ....order.search import update_order_search_vector
-from ....order.utils import delete_order_line, recalculate_order
+from ....order.utils import (
+ delete_order_line,
+ invalidate_order_prices,
+ recalculate_order_weight,
+)
from ...core.mutations import BaseMutation
from ...core.types import OrderError
from ..types import Order, OrderLine
@@ -56,20 +60,19 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
delete_order_line(line_info, manager)
line.id = db_id
+ updated_fields = []
if not order.is_shipping_required():
order.shipping_method = None
order.shipping_price = zero_taxed_money(order.currency)
order.shipping_method_name = None
- order.save(
- update_fields=[
- "currency",
- "shipping_method",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_method_name",
- "updated_at",
- ]
- )
+ updated_fields = [
+ "currency",
+ "shipping_method",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_method_name",
+ "updated_at",
+ ]
# Create the removal event
events.order_removed_products_event(
order=order,
@@ -78,8 +81,13 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
order_lines=[(line.quantity, line)],
)
- recalculate_order(order)
- update_order_search_vector(order)
+ invalidate_order_prices(order)
+ recalculate_order_weight(order)
+ update_order_search_vector(order, save=False)
+ updated_fields.extend(
+ ["should_refresh_prices", "weight", "search_vector", "updated_at"]
+ )
+ order.save(update_fields=updated_fields)
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
return OrderLineDelete(order=order, order_line=line)
diff --git a/saleor/graphql/order/mutations/order_line_discount_remove.py b/saleor/graphql/order/mutations/order_line_discount_remove.py
index 5817c490cf..3cea998705 100644
--- a/saleor/graphql/order/mutations/order_line_discount_remove.py
+++ b/saleor/graphql/order/mutations/order_line_discount_remove.py
@@ -3,7 +3,7 @@ import graphene
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events
-from ....order.utils import recalculate_order, remove_discount_from_order_line
+from ....order.utils import invalidate_order_prices, remove_discount_from_order_line
from ...core.types import OrderError
from ..types import Order, OrderLine
from .order_discount_common import OrderDiscountCommon
@@ -53,5 +53,5 @@ class OrderLineDiscountRemove(OrderDiscountCommon):
line=order_line,
)
- recalculate_order(order)
+ invalidate_order_prices(order, save=True)
return OrderLineDiscountRemove(order_line=order_line, order=order)
diff --git a/saleor/graphql/order/mutations/order_line_discount_update.py b/saleor/graphql/order/mutations/order_line_discount_update.py
index d02fd60fdd..2a8a1f8fe9 100644
--- a/saleor/graphql/order/mutations/order_line_discount_update.py
+++ b/saleor/graphql/order/mutations/order_line_discount_update.py
@@ -5,7 +5,7 @@ import graphene
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
from ....order import events
-from ....order.utils import recalculate_order, update_discount_for_order_line
+from ....order.utils import invalidate_order_prices, update_discount_for_order_line
from ...core.types import OrderError
from ..types import Order, OrderLine
from .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput
@@ -82,5 +82,5 @@ class OrderLineDiscountUpdate(OrderDiscountCommon):
line=order_line,
line_before_update=order_line_before_update,
)
- recalculate_order(order)
+ invalidate_order_prices(order, save=True)
return OrderLineDiscountUpdate(order_line=order_line, order=order)
diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.py
index de2b1ee867..308800236f 100644
--- a/saleor/graphql/order/mutations/order_line_update.py
+++ b/saleor/graphql/order/mutations/order_line_update.py
@@ -8,7 +8,11 @@ from ....core.tracing import traced_atomic_transaction
from ....order import models
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderLineInfo
-from ....order.utils import change_order_line_quantity, recalculate_order
+from ....order.utils import (
+ change_order_line_quantity,
+ invalidate_order_prices,
+ recalculate_order_weight,
+)
from ...core.mutations import ModelMutation
from ...core.types import OrderError
from ..types import Order, OrderLine
@@ -81,7 +85,9 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
"Cannot set new quantity because of insufficient stock.",
code=OrderErrorCode.INSUFFICIENT_STOCK,
)
- recalculate_order(instance.order)
+ invalidate_order_prices(instance.order)
+ recalculate_order_weight(instance.order)
+ instance.order.save(update_fields=["should_refresh_prices", "weight"])
func = get_webhook_handler_by_order_status(instance.order.status, info)
transaction.on_commit(lambda: func(instance.order))
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 33acf350d3..c6ea7ba93e 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -10,7 +10,11 @@ from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.error_codes import OrderErrorCode
from ....order.search import update_order_search_vector
-from ....order.utils import add_variant_to_order, recalculate_order
+from ....order.utils import (
+ add_variant_to_order,
+ invalidate_order_prices,
+ recalculate_order_weight,
+)
from ...core.mutations import BaseMutation
from ...core.types import NonNullList, OrderError
from ...product.types import ProductVariant
@@ -135,9 +139,17 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
lines = [line for _, line in added_lines]
- recalculate_order(order)
- update_order_search_vector(order)
-
+ invalidate_order_prices(order)
+ recalculate_order_weight(order)
+ update_order_search_vector(order, save=False)
+ order.save(
+ update_fields=[
+ "should_refresh_prices",
+ "weight",
+ "search_vector",
+ "updated_at",
+ ]
+ )
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.py
index cbd31111fd..79834f1c32 100644
--- a/saleor/graphql/order/mutations/order_update.py
+++ b/saleor/graphql/order/mutations/order_update.py
@@ -8,7 +8,7 @@ from ....core.tracing import traced_atomic_transaction
from ....order import OrderStatus, models
from ....order.error_codes import OrderErrorCode
from ....order.search import prepare_order_search_vector_value
-from ....order.utils import update_order_prices
+from ....order.utils import invalidate_order_prices
from ...account.types import AddressInput
from ...core.types import OrderError
from ..types import Order
@@ -63,6 +63,13 @@ class OrderUpdate(DraftOrderCreate):
)
return instance
+ @classmethod
+ def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
+ return any(
+ cleaned_input.get(field) is not None
+ for field in ["shipping_address", "billing_address"]
+ )
+
@classmethod
@traced_atomic_transaction()
def save(cls, info, instance, cleaned_input):
@@ -71,10 +78,9 @@ class OrderUpdate(DraftOrderCreate):
user = User.objects.filter(email=instance.user_email).first()
instance.user = user
instance.search_vector = prepare_order_search_vector_value(instance)
+
+ if cls.should_invalidate_prices(instance, cleaned_input, False):
+ invalidate_order_prices(instance)
+
instance.save()
- update_order_prices(
- instance,
- info.context.plugins,
- info.context.site.settings.include_taxes_in_prices,
- )
transaction.on_commit(lambda: info.context.plugins.order_updated(instance))
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
index 3b06d1c2ad..1e3efedfd7 100644
--- a/saleor/graphql/order/mutations/order_update_shipping.py
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -6,7 +6,7 @@ from ....core.taxes import zero_taxed_money
from ....order import models
from ....order.actions import order_shipping_updated
from ....order.error_codes import OrderErrorCode
-from ....order.utils import recalculate_order, update_order_prices
+from ....order.utils import invalidate_order_prices
from ....shipping import models as shipping_models
from ....shipping.utils import convert_to_shipping_method_data
from ...core.mutations import BaseMutation
@@ -97,6 +97,7 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
order.shipping_method = None
order.shipping_price = zero_taxed_money(order.currency)
order.shipping_method_name = None
+ invalidate_order_prices(order)
order.save(
update_fields=[
"currency",
@@ -104,10 +105,10 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
"shipping_price_net_amount",
"shipping_price_gross_amount",
"shipping_method_name",
+ "should_refresh_prices",
"updated_at",
]
)
- recalculate_order(order)
return OrderUpdateShipping(order=order)
method = cls.get_node_or_error(
@@ -141,28 +142,18 @@ class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
clean_order_update_shipping(order, shipping_method_data, info.context.plugins)
order.shipping_method = method
- shipping_price = info.context.plugins.calculate_order_shipping(order)
- order.shipping_price = shipping_price
- order.shipping_tax_rate = info.context.plugins.get_order_shipping_tax_rate(
- order, shipping_price
- )
+
order.shipping_method_name = method.name
+ invalidate_order_prices(order)
order.save(
update_fields=[
"currency",
"shipping_method",
"shipping_method_name",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_tax_rate",
+ "should_refresh_prices",
"updated_at",
]
)
- update_order_prices(
- order,
- info.context.plugins,
- info.context.site.settings.include_taxes_in_prices,
- )
# Post-process the results
order_shipping_updated(order, info.context.plugins)
return OrderUpdateShipping(order=order)
diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.py
index d4e6d40fe7..27b42f2c2a 100644
--- a/saleor/graphql/order/mutations/utils.py
+++ b/saleor/graphql/order/mutations/utils.py
@@ -1,14 +1,12 @@
from django.core.exceptions import ValidationError
-from ....order import OrderStatus, events
+from ....order import ORDER_EDITABLE_STATUS, OrderStatus, events
from ....order.error_codes import OrderErrorCode
from ....payment import PaymentError
from ....plugins.manager import PluginsManager
from ....shipping.interface import ShippingMethodData
from ..utils import get_shipping_method_availability_error
-ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)
-
class EditableOrderValidationMixin:
class Meta:
diff --git a/saleor/graphql/order/tests/deprecated/test_discount_order.py b/saleor/graphql/order/tests/deprecated/test_discount_order.py
index 040ce179df..df634c6daa 100644
--- a/saleor/graphql/order/tests/deprecated/test_discount_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_discount_order.py
@@ -149,15 +149,18 @@ def test_update_percentage_order_discount_by_old_id(
errors = data["errors"]
assert len(errors) == 0
- assert order.undiscounted_total == current_undiscounted_total
-
- assert expected_total == order.total
+ # Use `net` values in comparison due to that fixture have taxes incluted in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert order.undiscounted_total.net == current_undiscounted_total.net
+ assert expected_total.net == order.total.net
assert order.discounts.count() == 1
order_discount = order.discounts.first()
assert order_discount.value == value
assert order_discount.value_type == DiscountValueType.PERCENTAGE
- assert order_discount.amount == (current_undiscounted_total - expected_total).gross
+ discount_amount = current_undiscounted_total.net - expected_total.net
+ assert order_discount.amount == discount_amount
assert order_discount.reason == reason
event = order.events.get()
diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.py
index e241f4bb11..9d63ef6fa7 100644
--- a/saleor/graphql/order/tests/test_discount_order.py
+++ b/saleor/graphql/order/tests/test_discount_order.py
@@ -96,7 +96,7 @@ def test_add_fixed_order_discount_to_order(
order.status = status
order.save(update_fields=["status"])
total_before_order_discount = order.total
- value = Decimal("10")
+ value = Decimal("10.000")
variables = {
"orderId": graphene.Node.to_global_id("Order", order.pk),
"input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},
@@ -107,17 +107,17 @@ def test_add_fixed_order_discount_to_order(
data = content["data"]["orderDiscountAdd"]
order.refresh_from_db()
- expected_gross = total_before_order_discount.gross.amount - value
expected_net = total_before_order_discount.net.amount - value
errors = data["errors"]
assert len(errors) == 0
- assert expected_gross == order.total.gross.amount
+ # Use `net` values in comparison due to that fixture have taxes incluted in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert order.undiscounted_total.net == total_before_order_discount.net
assert expected_net == order.total.net.amount
- assert order.undiscounted_total == total_before_order_discount
-
assert order.discounts.count() == 1
order_discount = order.discounts.first()
assert order_discount.value == value
@@ -168,15 +168,18 @@ def test_add_percentage_order_discount_to_order(
errors = data["errors"]
assert len(errors) == 0
- assert expected_total == order.total
-
- assert order.undiscounted_total == total_before_order_discount
+ # Use `net` values in comparison due to that fixture have taxes incluted in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert expected_net_total == order.total.net
+ assert order.undiscounted_total.net == total_before_order_discount.net
assert order.discounts.count() == 1
order_discount = order.discounts.first()
assert order_discount.value == value
assert order_discount.value_type == DiscountValueType.PERCENTAGE
- assert order_discount.amount == (total_before_order_discount - expected_total).gross
+ discount_amount = total_before_order_discount.net - expected_total.net
+ assert order_discount.amount == discount_amount
assert order_discount.reason == reason
event = order.events.get()
@@ -253,15 +256,18 @@ def test_update_percentage_order_discount_to_order(
errors = data["errors"]
assert len(errors) == 0
- assert order.undiscounted_total == current_undiscounted_total
-
- assert expected_total == order.total
+ # Use `net` values in comparison due to that fixture have taxes incluted in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert order.undiscounted_total.net == current_undiscounted_total.net
+ assert expected_net_total == order.total.net
assert order.discounts.count() == 1
order_discount = order.discounts.first()
assert order_discount.value == value
assert order_discount.value_type == DiscountValueType.PERCENTAGE
- assert order_discount.amount == (current_undiscounted_total - expected_total).gross
+ discount_amount = current_undiscounted_total.net - expected_total.net
+ assert order_discount.amount == discount_amount
assert order_discount.reason == reason
event = order.events.get()
@@ -271,17 +277,20 @@ def test_update_percentage_order_discount_to_order(
assert discount_data["value"] == str(value)
assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value
- assert discount_data["amount_value"] == str(order_discount.amount.amount)
+ assert discount_data["amount_value"] == str(discount_amount.amount)
+@patch("saleor.order.calculations.PluginsManager.calculate_order_shipping")
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
def test_update_fixed_order_discount_to_order(
+ mocked_function,
status,
draft_order_with_fixed_discount_order,
staff_api_client,
permission_manage_orders,
):
order = draft_order_with_fixed_discount_order
+ mocked_function.return_value = order.shipping_price
order.status = status
order.save(update_fields=["status"])
order_discount = draft_order_with_fixed_discount_order.discounts.get()
@@ -308,15 +317,18 @@ def test_update_fixed_order_discount_to_order(
errors = data["errors"]
assert len(errors) == 0
- assert order.undiscounted_total == current_undiscounted_total
-
- assert expected_total == order.total
+ # Use `net` values in comparison due to that fixture have taxes incluted in
+ # prices but after recalculation taxes are removed because in tests we
+ # don't use any tax app.
+ assert order.undiscounted_total.net == current_undiscounted_total.net
+ assert expected_total.net == order.total.net
assert order.discounts.count() == 1
order_discount = order.discounts.first()
assert order_discount.value == value
assert order_discount.value_type == DiscountValueType.FIXED
- assert order_discount.amount == (current_undiscounted_total - expected_total).gross
+ discount_amount = current_undiscounted_total.net - expected_total.net
+ assert order_discount.amount == discount_amount
event = order.events.get()
assert event.type == OrderEvents.ORDER_DISCOUNT_UPDATED
@@ -325,7 +337,7 @@ def test_update_fixed_order_discount_to_order(
assert discount_data["value"] == str(value)
assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
- assert discount_data["amount_value"] == str(order_discount.amount.amount)
+ assert discount_data["amount_value"] == str(discount_amount.amount)
def test_update_order_discount_order_is_not_draft(
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 3af4aaeeca..83cd61af6f 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -1,6 +1,8 @@
from copy import deepcopy
from datetime import date, datetime, timedelta
from decimal import Decimal
+from functools import reduce
+from operator import getitem
from unittest import mock
from unittest.mock import ANY, MagicMock, Mock, call, patch
@@ -23,13 +25,14 @@ from ....core.anonymize import obfuscate_email
from ....core.notify_events import NotifyEventType
from ....core.prices import quantize_price
from ....core.taxes import TaxError, zero_taxed_money
-from ....discount.models import OrderDiscount
+from ....discount.models import OrderDiscount, VoucherChannelListing
from ....giftcard import GiftCardEvents
from ....giftcard.events import gift_cards_bought_event, gift_cards_used_in_order_event
from ....order import FulfillmentStatus, OrderEvents, OrderOrigin, OrderStatus
from ....order import events as order_events
from ....order.error_codes import OrderErrorCode
from ....order.events import order_replacement_created
+from ....order.interface import OrderTaxedPricesData
from ....order.models import Order, OrderEvent, OrderLine, get_order_number
from ....order.notifications import get_default_order_payload
from ....order.search import (
@@ -2503,6 +2506,11 @@ DRAFT_ORDER_CREATE_MUTATION = """
code
}
customerNote
+ total {
+ gross {
+ amount
+ }
+ }
}
}
}
@@ -3405,6 +3413,109 @@ def test_draft_order_create_invalid_shipping_address(
assert errors[0]["addressType"] == AddressType.SHIPPING.upper()
+TAX_RATE_1 = Decimal("1.23")
+TAX_RATE_2 = Decimal("1.18")
+
+
+def calculate_order_line_price_side_effect(price_name):
+ tax_rates = iter([TAX_RATE_1, TAX_RATE_2])
+
+ def inner(
+ order,
+ order_line,
+ variant,
+ product,
+ ):
+ tax_rate = next(tax_rates)
+ undiscounted_price = getattr(order_line, f"undiscounted_{price_name}")
+ undiscounted_price.gross *= tax_rate
+ price_with_discounts = getattr(order_line, price_name)
+ price_with_discounts.gross *= tax_rate
+
+ return OrderTaxedPricesData(
+ undiscounted_price=undiscounted_price.quantize(),
+ price_with_discounts=price_with_discounts.quantize(),
+ )
+
+ return inner
+
+
+ PluginsManager,
+ "calculate_order_line_unit",
+ new=Mock(side_effect=calculate_order_line_price_side_effect("unit_price")),
+)
+ PluginsManager,
+ "calculate_order_line_total",
+ new=Mock(side_effect=calculate_order_line_price_side_effect("total_price")),
+)
+def test_draft_order_create_price_recalculation(
+ staff_api_client,
+ permission_manage_orders,
+ customer_user,
+ product_available_in_many_channels,
+ product_variant_list,
+ channel_PLN,
+ graphql_address_data,
+ voucher,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ discount = "10"
+ variant_1 = product_available_in_many_channels.variants.first()
+ variant_2 = product_variant_list[2]
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ variant_2_id = graphene.Node.to_global_id("ProductVariant", variant_2.id)
+ quantity_1 = 3
+ quantity_2 = 4
+ lines = [
+ {"variantId": variant_1_id, "quantity": quantity_1},
+ {"variantId": variant_2_id, "quantity": quantity_2},
+ ]
+ address = graphql_address_data
+ voucher_amount = 13
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_PLN,
+ discount=Money(voucher_amount, channel_PLN.currency_code),
+ )
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": lines,
+ "billingAddress": address,
+ "shippingAddress": address,
+ "voucher": voucher_id,
+ "channel": channel_id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ assert Order.objects.count() == 1
+ order = Order.objects.first()
+ line1, line2 = order.lines.all()
+
+ assert line1.total_price == line1.unit_price * quantity_1
+ assert line1.unit_price.gross == line1.unit_price.net * TAX_RATE_1
+ assert line1.total_price.gross == line1.total_price.net * TAX_RATE_1
+
+ assert line2.total_price == line2.unit_price * quantity_2
+ assert line2.unit_price.gross == line2.unit_price.net * TAX_RATE_2
+ assert line2.total_price.gross == line2.total_price.net * TAX_RATE_2
+
+ assert order.total == line1.total_price + line2.total_price
+
+
DRAFT_UPDATE_QUERY = """
mutation draftUpdate(
$id: ID!,
@@ -3553,45 +3664,6 @@ def test_draft_order_update_with_non_draft_order(
assert error["code"] == OrderErrorCode.INVALID.name
-@patch("saleor.graphql.order.mutations.draft_order_create.update_order_prices")
-def test_draft_order_update_tax_error(
- update_order_prices_mock,
- staff_api_client,
- permission_manage_orders,
- draft_order,
- voucher,
- graphql_address_data,
-):
- err_msg = "Test error"
- update_order_prices_mock.side_effect = TaxError(err_msg)
- order = draft_order
- assert not order.voucher
- assert not order.customer_note
- query = DRAFT_ORDER_UPDATE_MUTATION
- order_id = graphene.Node.to_global_id("Order", order.id)
- voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
- customer_note = "Test customer note"
- variables = {
- "id": order_id,
- "voucher": voucher_id,
- "customerNote": customer_note,
- "shippingAddress": graphql_address_data,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- data = content["data"]["draftOrderUpdate"]
- errors = data["errors"]
- assert len(errors) == 1
- assert errors[0]["code"] == OrderErrorCode.TAX_ERROR.name
- assert errors[0]["message"] == f"Unable to calculate taxes - {err_msg}"
-
- order.refresh_from_db()
- assert not order.voucher
- assert not order.customer_note
-
-
def test_draft_order_update_invalid_address(
staff_api_client,
permission_manage_orders,
@@ -5696,6 +5768,10 @@ ORDER_LINE_DELETE_MUTATION = """
currency
amount
}
+ net {
+ currency
+ amount
+ }
}
}
}
@@ -6968,6 +7044,11 @@ ORDER_UPDATE_SHIPPING_QUERY = """
}
order {
id
+ total {
+ gross {
+ amount
+ }
+ }
}
}
}
@@ -7071,9 +7152,13 @@ def test_order_update_shipping_tax_included(
shipping_total = shipping_method.channel_listings.get(
channel_id=order.channel_id
).get_total()
+ shipping_price = TaxedMoney(
+ shipping_total / Decimal("1.19"), shipping_total
+ ).quantize()
assert order.status == OrderStatus.UNCONFIRMED
assert order.shipping_method == shipping_method
- assert order.shipping_price_gross == 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")
assert order.shipping_method_name == shipping_method.name
@@ -9842,9 +9927,9 @@ def test_draft_order_properly_recalculate_total_after_shipping_product_removed(
line.save()
query = ORDER_LINE_DELETE_MUTATION
- line = order.lines.get(product_sku="SKU_B")
- line_id = graphene.Node.to_global_id("OrderLine", line.id)
- variables = {"id": line_id}
+ line_2 = order.lines.get(product_sku="SKU_B")
+ line_2_id = graphene.Node.to_global_id("OrderLine", line_2.id)
+ variables = {"id": line_2_id}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
@@ -9852,9 +9937,10 @@ def test_draft_order_properly_recalculate_total_after_shipping_product_removed(
content = get_graphql_content(response)
data = content["data"]["orderLineDelete"]
- assert data["order"]["total"]["gross"]["amount"] == float(
- order.total_gross_amount
- ) - float(line.total_price_gross_amount)
+ order.refresh_from_db()
+ assert data["order"]["total"]["net"]["amount"] == float(
+ line.total_price_net_amount
+ ) + float(order.shipping_price_net_amount)
ORDER_UPDATE_SHIPPING_QUERY_WITH_TOTAL = """
@@ -10076,3 +10162,200 @@ def test_sort_order_by_rank_without_search(staff_api_client, permission_manage_o
content["errors"][0]["message"]
== "Sorting by RANK is available only when using a search filter."
)
+
+
+ "fun_to_patch, price_name",
+ [
+ ("order_total", "total"),
+ ("order_undiscounted_total", "undiscountedTotal"),
+ ("order_shipping", "shippingPrice"),
+ ],
+)
+def test_order_resolver_tax_recalculation(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ fun_to_patch,
+ price_name,
+):
+ # given
+ price = TaxedMoney(
+ net=Money(amount="1234.56", currency="USD"),
+ gross=Money(amount="1267.89", currency="USD"),
+ )
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.should_refresh_prices = True
+ order.save()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ query = (
+ """
+ query OrderPrices($id: ID!) {
+ order(id: $id) {
+ %s { net { amount } gross { amount } }
+ }
+ }
+ """
+ % price_name
+ )
+ variables = {"id": order_id}
+
+ # when
+ with patch(
+ f"saleor.order.calculations.{fun_to_patch}", new=Mock(return_value=price)
+ ):
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_orders],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["order"]
+
+ # then
+ assert str(data[price_name]["net"]["amount"]) == str(price.net.amount)
+ assert str(data[price_name]["gross"]["amount"]) == str(price.gross.amount)
+
+
+ORDER_LINE_PRICE_DATA = OrderTaxedPricesData(
+ price_with_discounts=TaxedMoney(
+ net=Money(amount="1234.56", currency="USD"),
+ gross=Money(amount="1267.89", currency="USD"),
+ ),
+ undiscounted_price=TaxedMoney(
+ net=Money(amount="7234.56", currency="USD"),
+ gross=Money(amount="7267.89", currency="USD"),
+ ),
+)
+
+
+ "fun_to_patch, price_name, expected_price",
+ [
+ ("order_line_unit", "unitPrice", ORDER_LINE_PRICE_DATA.price_with_discounts),
+ (
+ "order_line_unit",
+ "undiscountedUnitPrice",
+ ORDER_LINE_PRICE_DATA.undiscounted_price,
+ ),
+ ("order_line_total", "totalPrice", ORDER_LINE_PRICE_DATA.price_with_discounts),
+ ],
+)
+def test_order_line_resolver_tax_recalculation(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ fun_to_patch,
+ price_name,
+ expected_price,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.should_refresh_prices = True
+ order.save()
+
+ order.lines.last().delete()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ query = (
+ """
+ query OrderLinePrices($id: ID!) {
+ order(id: $id) {
+ lines {
+ %s { net { amount } gross { amount } }
+ }
+ }
+ }
+ """
+ % price_name
+ )
+ variables = {"id": order_id}
+
+ # when
+ with patch(
+ f"saleor.order.calculations.{fun_to_patch}",
+ new=Mock(return_value=ORDER_LINE_PRICE_DATA),
+ ):
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_orders],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["order"]["lines"][0]
+
+ # then
+ assert str(data[price_name]["net"]["amount"]) == str(expected_price.net.amount)
+ assert str(data[price_name]["gross"]["amount"]) == str(expected_price.gross.amount)
+
+
+ORDER_SHIPPING_TAX_RATE_QUERY = """
+query OrderShippingTaxRate($id: ID!) {
+ order(id: $id) {
+ shippingTaxRate
+ }
+}
+"""
+
+
+ORDER_LINE_TAX_RATE_QUERY = """
+query OrderLineTaxRate($id: ID!) {
+ order(id: $id) {
+ lines {
+ taxRate
+ }
+ }
+}
+"""
+
+
+ "query, fun_to_patch, path",
+ [
+ (ORDER_SHIPPING_TAX_RATE_QUERY, "order_shipping_tax_rate", ["shippingTaxRate"]),
+ (ORDER_LINE_TAX_RATE_QUERY, "order_line_tax_rate", ["lines", 0, "taxRate"]),
+ ],
+)
+def test_order_tax_rate_resolver_tax_recalculation(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ query,
+ fun_to_patch,
+ path,
+):
+ # given
+ tax_rate = Decimal("0.01")
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.should_refresh_prices = True
+ order.save()
+
+ order.lines.last().delete()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ variables = {"id": order_id}
+
+ # when
+ with patch(
+ f"saleor.order.calculations.{fun_to_patch}", new=Mock(return_value=tax_rate)
+ ):
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_orders],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["order"]
+
+ # then
+ assert str(reduce(getitem, path, data)) == str(tax_rate)
diff --git a/saleor/graphql/order/tests/test_order_price_expiration.py b/saleor/graphql/order/tests/test_order_price_expiration.py
new file mode 100644
index 0000000000..d1025b5341
--- /dev/null
+++ b/saleor/graphql/order/tests/test_order_price_expiration.py
@@ -0,0 +1,314 @@
+import pytest
+from graphene import Node
+
+from ....order import OrderStatus
+from ...tests.utils import get_graphql_content
+
+DRAFT_ORDER_UPDATE_MUTATION = """
+mutation draftUpdate(
+ $id: ID!
+ $voucher: ID!
+ $customerNote: String
+ $shippingAddress: AddressInput
+ $billingAddress: AddressInput
+) {
+ draftOrderUpdate(
+ id: $id
+ input: {
+ voucher: $voucher
+ customerNote: $customerNote
+ shippingAddress: $shippingAddress
+ billingAddress: $billingAddress
+ }
+ ) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+def order_with_lines(order_with_lines):
+ order_with_lines.status = OrderStatus.UNCONFIRMED
+ order_with_lines.save(update_fields=["status"])
+ return order_with_lines
+
+
+def test_draft_order_update_shipping_address_invalidate_prices(
+ staff_api_client,
+ permission_manage_orders,
+ draft_order,
+ voucher,
+ graphql_address_data,
+):
+ # given
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ variables = {
+ "id": Node.to_global_id("Order", draft_order.id),
+ "voucher": Node.to_global_id("Voucher", voucher.id),
+ "shippingAddress": graphql_address_data,
+ }
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["draftOrderUpdate"]["errors"]
+ draft_order.refresh_from_db()
+ assert draft_order.should_refresh_prices
+
+
+def test_draft_order_update_billing_address_invalidate_prices(
+ staff_api_client,
+ permission_manage_orders,
+ draft_order,
+ voucher,
+ graphql_address_data,
+):
+ # given
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ variables = {
+ "id": Node.to_global_id("Order", draft_order.id),
+ "voucher": Node.to_global_id("Voucher", voucher.id),
+ "billingAddress": graphql_address_data,
+ }
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["draftOrderUpdate"]["errors"]
+ draft_order.refresh_from_db()
+ assert draft_order.should_refresh_prices
+
+
+ORDER_UPDATE_MUTATION = """
+mutation orderUpdate(
+ $id: ID!
+ $email: String
+ $shippingAddress: AddressInput
+ $billingAddress: AddressInput
+) {
+ orderUpdate(
+ id: $id
+ input: {
+ userEmail: $email
+ shippingAddress: $shippingAddress
+ billingAddress: $billingAddress
+ }
+ ) {
+ errors {
+ field
+ code
+ }
+ order {
+ userEmail
+ }
+ }
+}
+"""
+
+
+def test_order_update_shipping_address_invalidate_prices(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ graphql_address_data,
+):
+ # given
+ order = order_with_lines
+ order.user = None
+ order.save()
+ query = ORDER_UPDATE_MUTATION
+ variables = {
+ "id": Node.to_global_id("Order", order.id),
+ "shippingAddress": graphql_address_data,
+ }
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["orderUpdate"]["errors"]
+ order.refresh_from_db()
+ assert order.should_refresh_prices
+
+
+def test_order_update_billing_address_invalidate_prices(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ graphql_address_data,
+):
+ # given
+ order = order_with_lines
+ order.user = None
+ order.save()
+ query = ORDER_UPDATE_MUTATION
+ variables = {
+ "id": Node.to_global_id("Order", order.id),
+ "billingAddress": graphql_address_data,
+ }
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["orderUpdate"]["errors"]
+ order.refresh_from_db()
+ assert order.should_refresh_prices
+
+
+ORDER_LINES_CREATE_MUTATION = """
+mutation OrderLinesCreate(
+ $orderId: ID!
+ $variantId: ID!
+ $quantity: Int!
+) {
+ orderLinesCreate(
+ id: $orderId
+ input: [
+ {
+ variantId: $variantId
+ quantity: $quantity
+ }
+ ]
+ ) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+def test_order_lines_create_invalidate_prices(
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ line = order.lines.first()
+ variant = line.variant
+ variables = {
+ "orderId": Node.to_global_id("Order", order.id),
+ "variantId": Node.to_global_id("ProductVariant", variant.id),
+ "quantity": 2,
+ }
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["orderLinesCreate"]["errors"]
+ order.refresh_from_db()
+ assert order.should_refresh_prices
+
+
+ORDER_LINE_UPDATE_MUTATION = """
+mutation OrderLineUpdate(
+ $lineId: ID!
+ $quantity: Int!
+) {
+ orderLineUpdate(
+ id: $lineId
+ input: {
+ quantity: $quantity
+ }
+ ) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+def test_order_line_update_invalidate_prices(
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ line = order.lines.first()
+ variables = {"lineId": Node.to_global_id("OrderLine", line.id), "quantity": 1}
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["orderLineUpdate"]["errors"]
+ order.refresh_from_db()
+ assert order.should_refresh_prices
+
+
+ORDER_LINE_DELETE_MUTATION = """
+mutation OrderLineDelete(
+ $id: ID!
+) {
+ orderLineDelete(
+ id: $id
+ ) {
+ errors {
+ field
+ message
+ }
+ }
+}
+"""
+
+
+def test_order_line_remove(
+ order_with_lines, permission_manage_orders, staff_api_client
+):
+ # given
+ order = order_with_lines
+ line = order.lines.first()
+ query = ORDER_LINE_DELETE_MUTATION
+ variables = {"id": Node.to_global_id("OrderLine", line.id)}
+
+ # when
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ )
+
+ # then
+ assert not content["data"]["orderLineDelete"]["errors"]
+ order.refresh_from_db()
+ assert order.should_refresh_prices
diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.py
index 93176782e7..5fe943fc0f 100644
--- a/saleor/graphql/order/tests/test_pagination.py
+++ b/saleor/graphql/order/tests/test_pagination.py
@@ -50,16 +50,19 @@ def draft_orders_for_pagination(db, channel_USD):
total=TaxedMoney(net=Money(1, "USD"), gross=Money(1, "USD")),
status=OrderStatus.DRAFT,
channel=channel_USD,
+ should_refresh_prices=False,
),
Order(
total=TaxedMoney(net=Money(2, "USD"), gross=Money(2, "USD")),
status=OrderStatus.DRAFT,
channel=channel_USD,
+ should_refresh_prices=False,
),
Order(
total=TaxedMoney(net=Money(3, "USD"), gross=Money(3, "USD")),
status=OrderStatus.DRAFT,
channel=channel_USD,
+ should_refresh_prices=False,
),
]
)
@@ -373,7 +376,11 @@ def test_draft_order_query_pagination_with_filter_created(
channel_USD,
):
with freeze_time("2012-01-14"):
- Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)
+ Order.objects.create(
+ status=OrderStatus.DRAFT,
+ channel=channel_USD,
+ should_refresh_prices=False,
+ )
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
diff --git a/saleor/graphql/order/tests/test_utils.py b/saleor/graphql/order/tests/test_utils.py
new file mode 100644
index 0000000000..e8b05777c7
--- /dev/null
+++ b/saleor/graphql/order/tests/test_utils.py
@@ -0,0 +1,46 @@
+import pytest
+
+from ....order import OrderStatus
+from ....order.utils import invalidate_order_prices
+
+
+ "status, invalid_prices",
+ [
+ (OrderStatus.DRAFT, True),
+ (OrderStatus.UNCONFIRMED, True),
+ (OrderStatus.UNFULFILLED, False),
+ ],
+)
+def test_invalidate_order_prices_status(order, status, invalid_prices):
+ # given
+ order.should_refresh_prices = False
+ order.status = status
+
+ # when
+ invalidate_order_prices(order, save=False)
+
+ # then
+ assert order.should_refresh_prices is invalid_prices
+
+
+ "save, invalid_prices",
+ [
+ (True, True),
+ (False, False),
+ ],
+)
+def test_invalidate_order_prices_save(order, save, invalid_prices):
+ # given
+ order.should_refresh_prices = False
+ order.save(update_fields=["should_refresh_prices"])
+ order.status = OrderStatus.DRAFT
+
+ # when
+ invalidate_order_prices(order, save=save)
+
+ # then
+ assert order.should_refresh_prices
+ order.refresh_from_db()
+ assert order.should_refresh_prices is invalid_prices
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 83dd130c82..5139199e0d 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -27,7 +27,7 @@ from ...discount import OrderDiscountType
from ...graphql.checkout.types import DeliveryMethod
from ...graphql.utils import get_user_or_app_from_context
from ...graphql.warehouse.dataloaders import StockByIdLoader, WarehouseByIdLoader
-from ...order import OrderStatus, models
+from ...order import OrderStatus, calculations, models
from ...order.models import FulfillmentStatus
from ...order.utils import (
get_order_country,
@@ -643,16 +643,34 @@ class OrderLine(ModelObjectType):
return Promise.all([variants_product, variant_medias]).then(_resolve_thumbnail)
@staticmethod
- def resolve_unit_price(root: models.OrderLine, _info):
- return root.unit_price
+ @traced_resolver
+ def resolve_unit_price(root: models.OrderLine, info):
+ def _resolve_unit_price(data):
+ order, lines = data
+ return calculations.order_line_unit(
+ order, root, info.context.plugins, lines
+ ).price_with_discounts
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ return Promise.all([order, lines]).then(_resolve_unit_price)
@staticmethod
def resolve_quantity_to_fulfill(root: models.OrderLine, info):
return root.quantity_unfulfilled
@staticmethod
- def resolve_undiscounted_unit_price(root: models.OrderLine, _info):
- return root.undiscounted_unit_price
+ @traced_resolver
+ def resolve_undiscounted_unit_price(root: models.OrderLine, info):
+ def _resolve_undiscounted_unit_price(data):
+ order, lines = data
+ return calculations.order_line_unit(
+ order, root, info.context.plugins, lines
+ ).undiscounted_price
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ return Promise.all([order, lines]).then(_resolve_undiscounted_unit_price)
@staticmethod
def resolve_unit_discount_type(root: models.OrderLine, _info):
@@ -667,8 +685,43 @@ class OrderLine(ModelObjectType):
return root.unit_discount
@staticmethod
- def resolve_total_price(root: models.OrderLine, _info):
- return root.total_price
+ @traced_resolver
+ def resolve_tax_rate(root: models.OrderLine, info):
+ def _resolve_tax_rate(data):
+ order, lines = data
+ return calculations.order_line_tax_rate(
+ order, root, info.context.plugins, lines
+ )
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ return Promise.all([order, lines]).then(_resolve_tax_rate)
+
+ @staticmethod
+ @traced_resolver
+ def resolve_total_price(root: models.OrderLine, info):
+ def _resolve_total_price(data):
+ order, lines = data
+ return calculations.order_line_total(
+ order, root, info.context.plugins, lines
+ ).price_with_discounts
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ return Promise.all([order, lines]).then(_resolve_total_price)
+
+ @staticmethod
+ @traced_resolver
+ def resolve_undiscounted_total_price(root: models.OrderLine, info):
+ def _resolve_undiscounted_total_price(data):
+ order, lines = data
+ return calculations.order_line_total(
+ order, root, info.context.plugins, lines
+ ).undiscounted_price
+
+ order = OrderByIdLoader(info.context).load(root.order_id)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.order_id)
+ return Promise.all([order, lines]).then(_resolve_undiscounted_total_price)
@staticmethod
def resolve_translated_product_name(root: models.OrderLine, _info):
@@ -1091,8 +1144,30 @@ class Order(ModelObjectType):
)
@staticmethod
- def resolve_shipping_price(root: models.Order, _info):
- return root.shipping_price
+ @traced_resolver
+ def resolve_shipping_price(root: models.Order, info):
+ def _resolve_shipping_price(lines):
+ return calculations.order_shipping(root, info.context.plugins, lines)
+
+ return (
+ OrderLinesByOrderIdLoader(info.context)
+ .load(root.id)
+ .then(_resolve_shipping_price)
+ )
+
+ @staticmethod
+ @traced_resolver
+ def resolve_shipping_tax_rate(root: models.Order, info):
+ def _resolve_shipping_tax_rate(lines):
+ return calculations.order_shipping_tax_rate(
+ root, info.context.plugins, lines
+ )
+
+ return (
+ OrderLinesByOrderIdLoader(info.context)
+ .load(root.id)
+ .then(_resolve_shipping_tax_rate)
+ )
@staticmethod
def resolve_actions(root: models.Order, info):
@@ -1126,12 +1201,28 @@ class Order(ModelObjectType):
)
@staticmethod
- def resolve_total(root: models.Order, _info):
- return root.total
+ @traced_resolver
+ def resolve_total(root: models.Order, info):
+ def _resolve_total(lines):
+ return calculations.order_total(root, info.context.plugins, lines)
+
+ return (
+ OrderLinesByOrderIdLoader(info.context).load(root.id).then(_resolve_total)
+ )
@staticmethod
- def resolve_undiscounted_total(root: models.Order, _info):
- return root.undiscounted_total
+ @traced_resolver
+ def resolve_undiscounted_total(root: models.Order, info):
+ def _resolve_undiscounted_total(lines):
+ return calculations.order_undiscounted_total(
+ root, info.context.plugins, lines
+ )
+
+ return (
+ OrderLinesByOrderIdLoader(info.context)
+ .load(root.id)
+ .then(_resolve_undiscounted_total)
+ )
@staticmethod
def resolve_total_authorized(root: models.Order, info):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a132b59d75..4fbae15e79 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1642,6 +1642,24 @@ enum WebhookEventTypeEnum {
"""Void payment."""
PAYMENT_VOID
+ """
+ Event called for checkout tax calculation.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ CHECKOUT_CALCULATE_TAXES
+
+ """
+ Event called for order tax calculation.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_CALCULATE_TAXES
+
"""Fetch external shipping methods for checkout."""
SHIPPING_LIST_METHODS_FOR_CHECKOUT
@@ -1684,6 +1702,24 @@ enum WebhookEventTypeSyncEnum {
"""Void payment."""
PAYMENT_VOID
+ """
+ Event called for checkout tax calculation.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ CHECKOUT_CALCULATE_TAXES
+
+ """
+ Event called for order tax calculation.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_CALCULATE_TAXES
+
"""Fetch external shipping methods for checkout."""
SHIPPING_LIST_METHODS_FOR_CHECKOUT
@@ -2209,6 +2245,7 @@ enum PermissionEnum {
MANAGE_TRANSLATIONS
MANAGE_CHECKOUTS
HANDLE_CHECKOUTS
+ HANDLE_TAXES
}
"""
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index c7ff03c0f2..3185b666d3 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -1,6 +1,7 @@
import graphene
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
+from ..core.descriptions import ADDED_IN_36, PREVIEW_FEATURE
from ..core.utils import str_to_enum
checkout_updated_event_enum_description = (
@@ -136,6 +137,12 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventSyncType.PAYMENT_VOID: "Void payment.",
WebhookEventSyncType.PAYMENT_CONFIRM: "Confirm payment.",
WebhookEventSyncType.PAYMENT_PROCESS: "Process payment.",
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES: (
+ "Event called for checkout tax calculation." + ADDED_IN_36 + PREVIEW_FEATURE
+ ),
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES: (
+ "Event called for order tax calculation." + ADDED_IN_36 + PREVIEW_FEATURE
+ ),
}
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 585b5eb343..e8e41a28c2 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -37,6 +37,9 @@ class OrderStatus:
]
+ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)
+
+
class OrderOrigin:
CHECKOUT = "checkout" # order created from checkout
DRAFT = "draft" # order created from draft order
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 6368a53abe..96ee6e3308 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -58,7 +58,6 @@ from .notifications import (
)
from .utils import (
order_line_needs_automatic_fulfillment,
- recalculate_order,
restock_fulfillment_lines,
update_order_authorize_data,
update_order_charge_data,
@@ -275,7 +274,6 @@ def order_awaits_fulfillment_approval(
def order_shipping_updated(order: "Order", manager: "PluginsManager"):
- recalculate_order(order)
manager.order_updated(order)
@@ -1127,8 +1125,6 @@ def create_replace_order(
lines_to_create = order_line_to_create.values()
OrderLine.objects.bulk_create(lines_to_create)
- recalculate_order(replace_order)
-
draft_order_created_from_replace_event(
draft_order=replace_order,
original_order=original_order,
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
new file mode 100644
index 0000000000..424e887adc
--- /dev/null
+++ b/saleor/order/calculations.py
@@ -0,0 +1,327 @@
+from decimal import Decimal
+from typing import Iterable, Optional, Tuple
+
+from django.db import transaction
+from django.db.models import prefetch_related_objects
+from prices import Money, TaxedMoney
+
+from ..core.prices import quantize_price
+from ..core.taxes import TaxError, zero_taxed_money
+from ..discount import OrderDiscountType
+from ..order.tests.test_calculations import TaxData
+from ..plugins.manager import PluginsManager
+from . import ORDER_EDITABLE_STATUS, utils
+from .interface import OrderTaxedPricesData
+from .models import Order, OrderLine
+
+
+def _recalculate_order_prices(
+ manager: PluginsManager, order: Order, lines: Iterable[OrderLine]
+) -> None:
+ """Fetch taxes from plugins and recalculate order/lines prices.
+
+ Does not throw TaxError.
+ """
+ currency = order.currency
+
+ subtotal = zero_taxed_money(currency)
+ for line in lines:
+ variant = line.variant
+ if variant:
+ product = variant.product
+
+ try:
+ line_unit = manager.calculate_order_line_unit(
+ order, line, variant, product
+ )
+ line.undiscounted_unit_price = line_unit.undiscounted_price
+ line.unit_price = line_unit.price_with_discounts
+
+ line_total = manager.calculate_order_line_total(
+ order, line, variant, product
+ )
+ line.undiscounted_total_price = line_total.undiscounted_price
+ line.total_price = line_total.price_with_discounts
+
+ line.tax_rate = manager.get_order_line_tax_rate(
+ order, product, variant, None, line_unit.undiscounted_price
+ )
+ except TaxError:
+ pass
+
+ subtotal += line.total_price
+ try:
+ order.shipping_price = manager.calculate_order_shipping(order)
+ order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
+ order, order.shipping_price
+ )
+ except TaxError:
+ pass
+
+ order.total = order.shipping_price + subtotal
+
+
+def _apply_tax_data(
+ order: Order, lines: Iterable[OrderLine], tax_data: TaxData
+) -> None:
+ """Apply all prices from tax data to order and order lines."""
+ currency = order.currency
+ shipping_price = TaxedMoney(
+ net=Money(tax_data.shipping_price_net_amount, currency),
+ gross=Money(tax_data.shipping_price_gross_amount, currency),
+ )
+
+ order.shipping_price = shipping_price
+ # We use % value in tax app input but on database we store
+ # it as a fractional value.
+ # e.g Tax app sends `10%` as `10` but in database it's stored as `0.1`
+ order.shipping_tax_rate = tax_data.shipping_tax_rate / 100
+
+ subtotal = zero_taxed_money(order.currency)
+ for (order_line, tax_line) in zip(lines, tax_data.lines):
+ line_total_price = TaxedMoney(
+ net=Money(tax_line.total_net_amount, currency),
+ gross=Money(tax_line.total_gross_amount, currency),
+ )
+ order_line.total_price = line_total_price
+ order_line.unit_price = line_total_price / order_line.quantity
+ # We use % value in tax app input but on database we store
+ # it as a fractional value.
+ # e.g Tax app sends `10%` as `10` but in database it's stored as `0.1`
+ order_line.tax_rate = tax_line.tax_rate / 100
+ subtotal += line_total_price
+
+ order.total = shipping_price + subtotal
+
+
+def _recalculate_order_discounts(order: Order, lines: Iterable[OrderLine]) -> None:
+ """Recalculate all order discounts and update order/lines prices."""
+ undiscounted_subtotal = zero_taxed_money(order.currency)
+ for line in lines:
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ undiscounted_total_price = (
+ line.undiscounted_unit_price * line.quantity
+ if line.unit_discount
+ else line.total_price
+ )
+ line.undiscounted_total_price = undiscounted_total_price
+ undiscounted_subtotal += undiscounted_total_price
+
+ order.undiscounted_total = undiscounted_subtotal + order.shipping_price
+
+ order_discounts = order.discounts.filter(type=OrderDiscountType.MANUAL)
+ for order_discount in order_discounts:
+ utils.update_order_discount_for_order(
+ order,
+ order_discount,
+ )
+
+
+def fetch_order_prices_if_expired(
+ order: Order,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> Tuple[Order, Optional[Iterable[OrderLine]]]:
+ """Fetch order prices with taxes.
+
+ First calculate and apply all order prices with taxes separately,
+ then apply tax data as well if we receive one.
+
+ Prices will be updated if force_update is True,
+ or if order.should_refresh_prices is True.
+ """
+ if order.status not in ORDER_EDITABLE_STATUS:
+ return order, lines
+
+ if not force_update and not order.should_refresh_prices:
+ return order, lines
+
+ if lines is None:
+ lines = list(order.lines.select_related("variant__product__product_type"))
+ else:
+ prefetch_related_objects(lines, "variant__product__product_type")
+
+ order.should_refresh_prices = False
+
+ _recalculate_order_prices(manager, order, lines)
+
+ tax_data = manager.get_taxes_for_order(order)
+
+ with transaction.atomic(savepoint=False):
+ if tax_data:
+ _apply_tax_data(order, lines, tax_data)
+
+ _recalculate_order_discounts(order, lines)
+
+ order.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "undiscounted_total_net_amount",
+ "undiscounted_total_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_tax_rate",
+ "should_refresh_prices",
+ ]
+ )
+ order.lines.bulk_update(
+ lines,
+ [
+ "unit_price_net_amount",
+ "unit_price_gross_amount",
+ "undiscounted_unit_price_net_amount",
+ "undiscounted_unit_price_gross_amount",
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ "undiscounted_total_price_net_amount",
+ "undiscounted_total_price_gross_amount",
+ "tax_rate",
+ ],
+ )
+ return order, lines
+
+
+def _find_order_line(
+ lines: Optional[Iterable[OrderLine]],
+ order_line: OrderLine,
+) -> OrderLine:
+ """Return order line from provided lines.
+
+ The return value represents the updated version of order_line parameter.
+ """
+ return next(
+ (line for line in (lines or []) if line.pk == order_line.pk), order_line
+ )
+
+
+def order_line_unit(
+ order: Order,
+ order_line: OrderLine,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> OrderTaxedPricesData:
+ """Return the unit price of provided line, taxes included.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ currency = order.currency
+ _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ order_line = _find_order_line(lines, order_line)
+ return OrderTaxedPricesData(
+ undiscounted_price=quantize_price(order_line.undiscounted_unit_price, currency),
+ price_with_discounts=quantize_price(order_line.unit_price, currency),
+ )
+
+
+def order_line_total(
+ order: Order,
+ order_line: OrderLine,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> OrderTaxedPricesData:
+ """Return the total price of provided line, taxes included.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ currency = order.currency
+ _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ order_line = _find_order_line(lines, order_line)
+ return OrderTaxedPricesData(
+ undiscounted_price=quantize_price(
+ order_line.undiscounted_total_price, currency
+ ),
+ price_with_discounts=quantize_price(order_line.total_price, currency),
+ )
+
+
+def order_line_tax_rate(
+ order: Order,
+ order_line: OrderLine,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> Decimal:
+ """Return the tax rate of provided line.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ _, lines = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ order_line = _find_order_line(lines, order_line)
+ return order_line.tax_rate
+
+
+def order_shipping(
+ order: Order,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> TaxedMoney:
+ """Return the shipping price of the order.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ currency = order.currency
+ order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ return quantize_price(order.shipping_price, currency)
+
+
+def order_shipping_tax_rate(
+ order: Order,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> Decimal:
+ """Return the shipping tax rate of the order.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ return order.shipping_tax_rate
+
+
+def order_total(
+ order: Order,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> TaxedMoney:
+ """Return the total price of the order.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ currency = order.currency
+ order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ return quantize_price(order.total, currency)
+
+
+def order_undiscounted_total(
+ order: Order,
+ manager: PluginsManager,
+ lines: Optional[Iterable[OrderLine]] = None,
+ force_update: bool = False,
+) -> TaxedMoney:
+ """Return the undiscounted total price of the order.
+
+ It takes into account all plugins.
+ If the prices are expired, call all order price calculation methods
+ and save them in the model directly.
+ """
+ currency = order.currency
+ order, _ = fetch_order_prices_if_expired(order, manager, lines, force_update)
+ return quantize_price(order.undiscounted_total, currency)
diff --git a/saleor/order/migrations/0155_order_should_refresh_prices.py b/saleor/order/migrations/0155_order_should_refresh_prices.py
new file mode 100644
index 0000000000..fd45a8be13
--- /dev/null
+++ b/saleor/order/migrations/0155_order_should_refresh_prices.py
@@ -0,0 +1,18 @@
+# Generated by Django 3.2.12 on 2022-03-29 15:35
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0154_auto_20220621_0850"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="should_refresh_prices",
+ field=models.BooleanField(default=True),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 8d6e18b0e2..d056c4226a 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -289,6 +289,8 @@ class Order(ModelWithMetadata):
redirect_url = models.URLField(blank=True, null=True)
search_document = models.TextField(blank=True, default="")
search_vector = SearchVectorField(blank=True, null=True)
+ # this field is used only for draft/unconfirmed orders
+ should_refresh_prices = models.BooleanField(default=True)
objects = models.Manager.from_queryset(OrderQueryset)()
class Meta:
diff --git a/saleor/order/search.py b/saleor/order/search.py
index b5785a0de9..41802b689b 100644
--- a/saleor/order/search.py
+++ b/saleor/order/search.py
@@ -14,9 +14,10 @@ if TYPE_CHECKING:
from .models import Order
-def update_order_search_vector(order: "Order"):
+def update_order_search_vector(order: "Order", *, save: bool = True):
order.search_vector = prepare_order_search_vector_value(order)
- order.save(update_fields=["search_vector", "updated_at"])
+ if save:
+ order.save(update_fields=["search_vector", "updated_at"])
def prepare_order_search_vector_value(order: "Order", *, already_prefetched=False):
diff --git a/saleor/order/tasks.py b/saleor/order/tasks.py
index 998acebe6d..e7012600fa 100644
--- a/saleor/order/tasks.py
+++ b/saleor/order/tasks.py
@@ -3,14 +3,17 @@ from typing import List
from ..celeryconf import app
from ..plugins.manager import get_plugins_manager
from .models import Order
-from .utils import recalculate_order
+from .utils import invalidate_order_prices
@app.task
def recalculate_orders_task(order_ids: List[int]):
orders = Order.objects.filter(id__in=order_ids)
+
for order in orders:
- recalculate_order(order)
+ invalidate_order_prices(order)
+
+ Order.objects.bulk_update(orders, ["should_refresh_prices"])
@app.task
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
new file mode 100644
index 0000000000..ee4584c27f
--- /dev/null
+++ b/saleor/order/tests/test_calculations.py
@@ -0,0 +1,677 @@
+from decimal import Decimal
+from typing import Literal, Union
+from unittest.mock import Mock, patch, sentinel
+
+import pytest
+from prices import Money, TaxedMoney
+
+from ...core.prices import quantize_price
+from ...core.taxes import TaxData, TaxError, TaxLineData, zero_taxed_money
+from .. import OrderStatus, calculations
+from ..interface import OrderTaxedPricesData
+
+
+def order_with_lines(order_with_lines):
+ order_with_lines.status = OrderStatus.UNCONFIRMED
+ return order_with_lines
+
+
+def order_lines(order_with_lines):
+ return order_with_lines.lines.all()
+
+
+def tax_data(order_with_lines, order_lines):
+ order = order_with_lines
+ tax_rate = Decimal("1.23")
+ shipping_tax_rate = Decimal("1.17")
+ lines = []
+ for i, line in enumerate(order_lines, start=1):
+ line_tax_rate = tax_rate + Decimal(f"{i}") / 100
+ lines.append(
+ TaxLineData(
+ total_net_amount=line.total_price.net.amount,
+ total_gross_amount=line.total_price.net.amount * line_tax_rate,
+ tax_rate=line_tax_rate,
+ )
+ )
+
+ shipping_net = order.shipping_price.net.amount
+ shipping_gross = order.shipping_price.net.amount * shipping_tax_rate
+ return TaxData(
+ shipping_price_net_amount=shipping_net,
+ shipping_price_gross_amount=shipping_gross,
+ shipping_tax_rate=shipping_tax_rate,
+ lines=lines,
+ )
+
+
+def create_taxed_money(net: Decimal, gross: Decimal, currency: str) -> TaxedMoney:
+ return TaxedMoney(net=Money(net, currency), gross=Money(gross, currency))
+
+
+def create_order_taxed_prices_data(
+ net: Decimal, gross: Decimal, currency: str
+) -> OrderTaxedPricesData:
+ return OrderTaxedPricesData(
+ undiscounted_price=create_taxed_money(net, gross, currency),
+ price_with_discounts=create_taxed_money(net, gross, currency),
+ )
+
+
+def test_recalculate_order_prices(order_with_lines, order_lines, tax_data):
+ # given
+ order = order_with_lines
+ currency = order.currency
+ lines = list(order_lines)
+ lines.append(
+ Mock(
+ variant=None,
+ total_price=create_taxed_money(
+ net=Decimal("33.33"),
+ gross=Decimal("44.44"),
+ currency=order.currency,
+ ),
+ )
+ )
+
+ total_prices = [
+ get_order_priced_taxes_data(line, "total", currency) for line in tax_data.lines
+ ]
+ unit_prices = []
+ for line, total_price in zip(lines, total_prices):
+ unit_prices.append(
+ OrderTaxedPricesData(
+ undiscounted_price=total_price.undiscounted_price / line.quantity,
+ price_with_discounts=total_price.price_with_discounts / line.quantity,
+ )
+ )
+ tax_rates = [line.tax_rate for line in tax_data.lines]
+ shipping_tax_rate = tax_data.shipping_tax_rate
+ shipping = get_taxed_money(tax_data, "shipping_price", currency)
+ subtotal = sum(
+ (get_taxed_money(line, "total", currency) for line in tax_data.lines),
+ zero_taxed_money(order.currency),
+ ) + create_taxed_money(Decimal("33.33"), Decimal("44.44"), order.currency)
+ total = shipping + subtotal
+
+ manager = Mock(
+ calculate_order_line_unit=Mock(side_effect=unit_prices),
+ calculate_order_line_total=Mock(side_effect=total_prices),
+ get_order_shipping_tax_rate=Mock(return_value=shipping_tax_rate),
+ get_order_line_tax_rate=Mock(side_effect=tax_rates),
+ calculate_order_shipping=Mock(return_value=shipping),
+ )
+
+ # when
+ calculations._recalculate_order_prices(manager, order, lines)
+
+ # then
+ assert order.total == total
+ assert order.shipping_price == shipping
+ assert order.shipping_tax_rate == shipping_tax_rate
+
+ for line_unit, line_total, tax_rate, line in zip(
+ unit_prices, total_prices, tax_rates, lines
+ ):
+ assert line.unit_price == line_unit.price_with_discounts
+ assert line.undiscounted_unit_price == line_unit.undiscounted_price
+ assert line.total_price == line_total.price_with_discounts
+ assert line.undiscounted_total_price == line_total.undiscounted_price
+ assert tax_rate == line.tax_rate
+
+
+ "mocked_method_name",
+ [
+ "calculate_order_line_unit",
+ "calculate_order_line_total",
+ "get_order_line_tax_rate",
+ "calculate_order_shipping",
+ "get_order_shipping_tax_rate",
+ ],
+)
+def test_recalculate_order_prices_tax_error(
+ order_with_lines, order_lines, mocked_method_name
+):
+ # given
+ order = order_with_lines
+ lines = order_lines
+ zero_money = zero_taxed_money(order.currency)
+ zero_prices = OrderTaxedPricesData(
+ undiscounted_price=zero_money,
+ price_with_discounts=zero_money,
+ )
+ manager_methods = {
+ "calculate_order_line_unit": Mock(return_value=zero_prices),
+ "calculate_order_line_total": Mock(return_value=zero_prices),
+ "get_order_shipping_tax_rate": Mock(return_value=Decimal("0.00")),
+ "get_order_line_tax_rate": Mock(return_value=Decimal("0.00")),
+ "calculate_order_shipping": Mock(return_value=zero_money),
+ mocked_method_name: Mock(side_effect=TaxError()),
+ }
+ manager = Mock(**manager_methods)
+
+ # when
+ calculations._recalculate_order_prices(manager, order, lines)
+
+ # then
+ # no exception is raised
+
+
+def test_recalculate_order_prices_tax_error_line_prices(
+ order_with_lines, order_lines, tax_data
+):
+ # given
+ order = order_with_lines
+ currency = order.currency
+ lines = list(order_lines)
+ lines.append(
+ Mock(
+ variant=None,
+ total_price=create_taxed_money(
+ net=Decimal("33.33"),
+ gross=Decimal("44.44"),
+ currency=currency,
+ ),
+ )
+ )
+ error_line = order_lines[0]
+ old_line_unit_price = error_line.unit_price
+ old_line_undiscounted_unit_price = error_line.undiscounted_unit_price
+ old_line_total_price = error_line.total_price
+ old_line_undiscounted_total_price = error_line.undiscounted_total_price
+ old_line_tax_rate = error_line.tax_rate
+
+ total_prices = [
+ get_order_priced_taxes_data(line, "total", currency) for line in tax_data.lines
+ ]
+ unit_prices = []
+ for line, total_price in zip(lines, total_prices):
+ unit_prices.append(
+ OrderTaxedPricesData(
+ undiscounted_price=total_price.undiscounted_price / line.quantity,
+ price_with_discounts=total_price.price_with_discounts / line.quantity,
+ )
+ )
+ tax_rates = [line.tax_rate for line in tax_data.lines]
+ shipping_tax_rate = tax_data.shipping_tax_rate
+ shipping = get_taxed_money(tax_data, "shipping_price", currency)
+
+ subtotal = (
+ error_line.total_price
+ + sum(
+ [get_taxed_money(line, "total", currency) for line in tax_data.lines[1:]],
+ zero_taxed_money(currency),
+ )
+ + create_taxed_money(Decimal("33.33"), Decimal("44.44"), currency)
+ )
+ total = shipping + subtotal
+
+ manager = Mock(
+ calculate_order_line_unit=Mock(side_effect=[TaxError] + unit_prices[1:]),
+ calculate_order_line_total=Mock(side_effect=total_prices[1:]),
+ get_order_shipping_tax_rate=Mock(return_value=shipping_tax_rate),
+ get_order_line_tax_rate=Mock(side_effect=tax_rates[1:]),
+ calculate_order_shipping=Mock(return_value=shipping),
+ )
+
+ # when
+ calculations._recalculate_order_prices(manager, order, lines)
+
+ # then
+ assert order.total == total
+ assert order.shipping_price == shipping
+ assert order.shipping_tax_rate == shipping_tax_rate
+
+ assert old_line_unit_price == error_line.unit_price
+ assert old_line_undiscounted_unit_price == error_line.undiscounted_unit_price
+ assert old_line_total_price == error_line.total_price
+ assert old_line_undiscounted_total_price == error_line.undiscounted_total_price
+ assert old_line_tax_rate == error_line.tax_rate
+
+ for line_unit, line_total, tax_rate, line in list(
+ zip(unit_prices, total_prices, tax_rates, lines)
+ )[1:]:
+ assert line.unit_price == line_unit.price_with_discounts
+ assert line.undiscounted_unit_price == line_unit.undiscounted_price
+ assert line.total_price == line_total.price_with_discounts
+ assert line.undiscounted_total_price == line_total.undiscounted_price
+ assert tax_rate == line.tax_rate
+
+
+def test_recalculate_order_prices_tax_error_shipping_price(
+ order_with_lines, order_lines, tax_data
+):
+ # given
+ order = order_with_lines
+ currency = order.currency
+ lines = list(order_lines)
+ lines.append(
+ Mock(
+ variant=None,
+ total_price=create_taxed_money(
+ net=Decimal("33.33"),
+ gross=Decimal("44.44"),
+ currency=currency,
+ ),
+ )
+ )
+ old_shipping_price = order.shipping_price
+ old_shipping_tax_rate = order.shipping_tax_rate
+
+ total_prices = [
+ get_order_priced_taxes_data(line, "total", currency) for line in tax_data.lines
+ ]
+ unit_prices = []
+ for line, total_price in zip(lines, total_prices):
+ unit_prices.append(
+ OrderTaxedPricesData(
+ undiscounted_price=total_price.undiscounted_price / line.quantity,
+ price_with_discounts=total_price.price_with_discounts / line.quantity,
+ )
+ )
+ tax_rates = [line.tax_rate for line in tax_data.lines]
+ shipping_tax_rate = tax_data.shipping_tax_rate
+
+ subtotal = sum(
+ [get_taxed_money(line, "total", currency) for line in tax_data.lines],
+ zero_taxed_money(currency),
+ ) + create_taxed_money(Decimal("33.33"), Decimal("44.44"), currency)
+
+ manager = Mock(
+ calculate_order_line_unit=Mock(side_effect=unit_prices),
+ calculate_order_line_total=Mock(side_effect=total_prices),
+ get_order_shipping_tax_rate=Mock(return_value=shipping_tax_rate),
+ get_order_line_tax_rate=Mock(side_effect=tax_rates),
+ calculate_order_shipping=Mock(side_effect=TaxError),
+ )
+
+ # when
+ calculations._recalculate_order_prices(manager, order, lines)
+
+ # then
+ assert order.total == subtotal + old_shipping_price
+ assert order.shipping_price == old_shipping_price
+ assert order.shipping_tax_rate == old_shipping_tax_rate
+
+ for line_unit, line_total, tax_rate, line in zip(
+ unit_prices, total_prices, tax_rates, lines
+ ):
+ assert line.unit_price == line_unit.price_with_discounts
+ assert line.undiscounted_unit_price == line_unit.undiscounted_price
+ assert line.total_price == line_total.price_with_discounts
+ assert line.undiscounted_total_price == line_total.undiscounted_price
+ assert tax_rate == line.tax_rate
+
+
+def test_apply_tax_data(order_with_lines, order_lines, tax_data):
+ # given
+ order = order_with_lines
+ lines = order_lines
+
+ # when
+ calculations._apply_tax_data(order, [line for line in lines], tax_data)
+
+ # then
+ assert str(order.shipping_price.net.amount) == str(
+ tax_data.shipping_price_net_amount
+ )
+ assert str(order.shipping_price.gross.amount) == str(
+ tax_data.shipping_price_gross_amount
+ )
+
+ for line, tax_line in zip(lines, tax_data.lines):
+ assert str(line.total_price.net.amount) == str(tax_line.total_net_amount)
+ assert str(line.total_price.gross.amount) == str(tax_line.total_gross_amount)
+
+
+def manager_with_mocked_plugins_calculations(
+ plugins_manager, tax_data, order_with_lines
+):
+ currency = order_with_lines.currency
+ plugins_manager.get_order_shipping_tax_rate = Mock(
+ return_value=tax_data.shipping_tax_rate
+ )
+ plugins_manager.calculate_order_shipping = Mock(
+ return_value=get_taxed_money(tax_data, "shipping_price", currency)
+ )
+
+ total_prices = [
+ get_order_priced_taxes_data(line, "total", currency) for line in tax_data.lines
+ ]
+ plugins_manager.calculate_order_line_total = Mock(side_effect=total_prices)
+
+ unit_prices = []
+ for line, total_price in zip(order_with_lines.lines.all(), total_prices):
+ unit_price = quantize_price(
+ total_price.price_with_discounts / line.quantity, currency
+ )
+ unit_prices.append(
+ OrderTaxedPricesData(
+ undiscounted_price=unit_price,
+ price_with_discounts=unit_price,
+ )
+ )
+
+ plugins_manager.calculate_order_line_unit = Mock(side_effect=unit_prices)
+ plugins_manager.get_order_line_tax_rate = Mock(
+ side_effect=[line.tax_rate for line in tax_data.lines]
+ )
+ return plugins_manager
+
+
+def fetch_kwargs(order_with_lines, plugins_manager):
+ return {
+ "order": order_with_lines,
+ "manager": plugins_manager,
+ "force_update": True,
+ }
+
+
+def fetch_kwargs_with_lines(order_with_lines, order_lines, plugins_manager):
+ return {
+ "order": order_with_lines,
+ "lines": order_lines,
+ "manager": plugins_manager,
+ }
+
+
+def get_taxed_money(
+ obj: Union[TaxData, TaxLineData],
+ attr: Literal["unit", "total", "subtotal", "shipping_price"],
+ currency: str,
+) -> TaxedMoney:
+ return TaxedMoney(
+ Money(getattr(obj, f"{attr}_net_amount"), currency),
+ Money(getattr(obj, f"{attr}_gross_amount"), currency),
+ )
+
+
+def get_order_priced_taxes_data(
+ obj: Union[TaxData, TaxLineData],
+ attr: Literal["unit", "total", "subtotal", "shipping_price"],
+ currency: str,
+) -> OrderTaxedPricesData:
+ return OrderTaxedPricesData(
+ undiscounted_price=get_taxed_money(obj, attr, currency),
+ price_with_discounts=get_taxed_money(obj, attr, currency),
+ )
+
+
+def test_fetch_order_prices_if_expired_plugins(
+ plugins_manager,
+ fetch_kwargs,
+ order_with_lines,
+ tax_data,
+):
+ # given
+ currency = order_with_lines.currency
+ total_prices = [
+ get_order_priced_taxes_data(line, "total", currency) for line in tax_data.lines
+ ]
+ subtotal = zero_taxed_money(currency)
+ unit_prices = []
+ for line, total_price in zip(order_with_lines.lines.all(), total_prices):
+ subtotal += total_price.price_with_discounts
+ unit_prices.append(
+ OrderTaxedPricesData(
+ undiscounted_price=total_price.undiscounted_price / line.quantity,
+ price_with_discounts=total_price.price_with_discounts / line.quantity,
+ )
+ )
+ tax_rates = [line.tax_rate for line in tax_data.lines]
+ shipping_tax_rate = tax_data.shipping_tax_rate
+ shipping = get_taxed_money(tax_data, "shipping_price", currency)
+
+ total = subtotal + shipping
+
+ plugins_manager.calculate_order_line_unit = Mock(side_effect=unit_prices)
+ plugins_manager.calculate_order_line_total = Mock(side_effect=total_prices)
+ plugins_manager.get_order_line_tax_rate = Mock(side_effect=tax_rates)
+ plugins_manager.calculate_order_shipping = Mock(return_value=shipping)
+ plugins_manager.get_order_shipping_tax_rate = Mock(return_value=shipping_tax_rate)
+ plugins_manager.get_taxes_for_order = Mock(return_value=None)
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ order_with_lines.refresh_from_db()
+ assert order_with_lines.shipping_price == get_taxed_money(
+ tax_data, "shipping_price", currency
+ )
+ assert order_with_lines.shipping_tax_rate == tax_data.shipping_tax_rate
+ assert order_with_lines.total == total
+ for order_line, tax_line, unit_price in zip(
+ order_with_lines.lines.all(), tax_data.lines, unit_prices
+ ):
+ assert order_line.unit_price == unit_price.price_with_discounts
+ assert order_line.total_price == get_taxed_money(tax_line, "total", currency)
+ assert order_line.tax_rate == tax_line.tax_rate
+
+
+def test_fetch_order_prices_if_expired_webhooks_success(
+ plugins_manager,
+ fetch_kwargs,
+ order_with_lines,
+ tax_data,
+):
+ # given
+ currency = order_with_lines.currency
+ plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ shipping_price = get_taxed_money(tax_data, "shipping_price", currency)
+ assert order_with_lines.shipping_price == shipping_price
+ assert order_with_lines.shipping_tax_rate == tax_data.shipping_tax_rate / 100
+ subtotal = zero_taxed_money(currency)
+ for order_line, tax_line in zip(order_with_lines.lines.all(), tax_data.lines):
+ line_total = get_taxed_money(tax_line, "total", currency)
+ subtotal += line_total
+ assert order_line.total_price == line_total
+ assert order_line.unit_price == line_total / order_line.quantity
+ assert order_line.tax_rate == tax_line.tax_rate / 100
+ assert order_with_lines.total == subtotal + shipping_price
+
+
+def test_fetch_order_prices_if_expired_recalculate_all_prices(
+ plugins_manager,
+ fetch_kwargs,
+ order_with_lines,
+ tax_data,
+):
+ # given
+ currency = order_with_lines.currency
+ discount_amount = Decimal("3.00")
+ order_with_lines.discounts.create(
+ value=discount_amount,
+ amount_value=discount_amount,
+ currency=order_with_lines.currency,
+ )
+ order_with_lines.total_net_amount = Decimal("0.00")
+ order_with_lines.total_gross_amount = Decimal("0.00")
+ order_with_lines.undiscounted_total_net_amount = Decimal("0.00")
+ order_with_lines.undiscounted_total_gross_amount = Decimal("0.00")
+ order_with_lines.save()
+ plugins_manager.get_taxes_for_order = Mock(return_value=tax_data)
+
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ order_with_lines.refresh_from_db()
+ shipping_price = get_taxed_money(tax_data, "shipping_price", currency)
+ assert order_with_lines.shipping_price == shipping_price
+ assert order_with_lines.shipping_tax_rate == tax_data.shipping_tax_rate / 100
+ subtotal = zero_taxed_money(currency)
+ for order_line, tax_line in zip(order_with_lines.lines.all(), tax_data.lines):
+ line_total = get_taxed_money(tax_line, "total", currency)
+ subtotal += line_total
+ assert order_line.total_price == line_total
+ assert order_line.unit_price == line_total / order_line.quantity
+ assert order_line.tax_rate == tax_line.tax_rate / 100
+
+ assert order_with_lines.undiscounted_total == subtotal + shipping_price
+ assert order_with_lines.total == subtotal + shipping_price - create_taxed_money(
+ discount_amount, discount_amount, order_with_lines.currency
+ )
+
+
+def test_fetch_order_prices_if_expired_prefetch(fetch_kwargs, order_lines):
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs)
+
+ # then
+ assert all(line._state.fields_cache for line in order_lines)
+
+
+def test_fetch_order_prices_if_expired_prefetch_with_lines(
+ fetch_kwargs_with_lines, order_lines
+):
+ # when
+ calculations.fetch_order_prices_if_expired(**fetch_kwargs_with_lines)
+
+ # then
+ assert all(line._state.fields_cache for line in order_lines)
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_line_unit(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_line_unit_price = create_taxed_money(
+ Decimal("1234.0000"), Decimal("1234.0000"), "USD"
+ )
+ expected_line_undiscounted_unit_price = create_taxed_money(
+ Decimal("5678.0000"), Decimal("5678.0000"), "USD"
+ )
+
+ order = Mock(currency="USD")
+ order_line = Mock(
+ pk=1,
+ unit_price=expected_line_unit_price,
+ undiscounted_unit_price=expected_line_undiscounted_unit_price,
+ )
+ mocked_fetch_order_prices_if_expired.return_value = (Mock(), [order_line])
+
+ # when
+ line_unit_price = calculations.order_line_unit(order, order_line, Mock())
+
+ # then
+ assert line_unit_price == OrderTaxedPricesData(
+ undiscounted_price=expected_line_undiscounted_unit_price,
+ price_with_discounts=expected_line_unit_price,
+ )
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_line_total(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_line_total_price = create_taxed_money(
+ Decimal("1234.0000"), Decimal("1234.0000"), "USD"
+ )
+ expected_line_undiscounted_total_price = create_taxed_money(
+ Decimal("5678.0000"), Decimal("5678.0000"), "USD"
+ )
+
+ order = Mock(currency="USD")
+ order_line = Mock(
+ pk=1,
+ total_price=expected_line_total_price,
+ undiscounted_total_price=expected_line_undiscounted_total_price,
+ )
+ mocked_fetch_order_prices_if_expired.return_value = (Mock(), [order_line])
+
+ # when
+ line_total_price = calculations.order_line_total(order, order_line, Mock())
+
+ # then
+ assert line_total_price == OrderTaxedPricesData(
+ undiscounted_price=expected_line_undiscounted_total_price,
+ price_with_discounts=expected_line_total_price,
+ )
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_line_tax_rate(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_line_tax_rate = sentinel.TAX_RATE
+
+ order_line = Mock(pk=1, tax_rate=expected_line_tax_rate)
+ mocked_fetch_order_prices_if_expired.return_value = (Mock(), [order_line])
+
+ # when
+ line_tax_rate = calculations.order_line_tax_rate(Mock(), order_line, Mock())
+
+ # then
+ assert line_tax_rate == expected_line_tax_rate
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_shipping(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_shipping_price = Decimal("1234.0000")
+
+ order = Mock(shipping_price=expected_shipping_price, currency="USD")
+ mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+
+ # when
+ shipping_price = calculations.order_shipping(order, Mock())
+
+ # then
+ assert shipping_price == quantize_price(expected_shipping_price, order.currency)
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_shipping_tax_rate(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_shipping_tax_rate = sentinel.SHIPPING_TAX_RATE
+
+ order = Mock(shipping_tax_rate=expected_shipping_tax_rate)
+ mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+
+ # when
+ shipping_tax_rate = calculations.order_shipping_tax_rate(order, Mock())
+
+ # then
+ assert shipping_tax_rate == expected_shipping_tax_rate
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_total(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_total = Decimal("1234.0000")
+
+ order = Mock(total=expected_total, currency="USD")
+ mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+
+ # when
+ total = calculations.order_total(order, Mock())
+
+ # then
+ assert total == quantize_price(expected_total, order.currency)
+
+
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_order_undiscounted_total(mocked_fetch_order_prices_if_expired):
+ # given
+ expected_undiscounted_total = Decimal("1234.0000")
+
+ order = Mock(undiscounted_total=expected_undiscounted_total, currency="USD")
+ mocked_fetch_order_prices_if_expired.return_value = (order, Mock())
+
+ # when
+ undiscounted_total = calculations.order_undiscounted_total(order, Mock())
+
+ # then
+ assert undiscounted_total == quantize_price(
+ expected_undiscounted_total, order.currency
+ )
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index d191da34ca..45f21da5d9 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -17,15 +17,16 @@ from ...discount.models import (
from ...discount.utils import validate_voucher_in_order
from ...graphql.core.utils import to_global_id_or_none
from ...graphql.tests.utils import get_graphql_content
-from ...order.interface import OrderTaxedPricesData
from ...payment import ChargeStatus
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...product.models import Collection
+from ...tests.fixtures import recalculate_order
from ...warehouse import WarehouseClickAndCollectOption
from ...warehouse.models import Stock, Warehouse
from ...warehouse.tests.utils import get_quantity_allocated_for_stock
from .. import FulfillmentStatus, OrderEvents, OrderStatus
+from ..calculations import fetch_order_prices_if_expired
from ..events import (
OrderEventsEmails,
event_fulfillment_confirmed_notification,
@@ -45,11 +46,9 @@ from ..utils import (
change_order_line_quantity,
delete_order_line,
get_voucher_discount_for_order,
- recalculate_order,
restock_fulfillment_lines,
update_order_authorize_data,
update_order_charge_data,
- update_order_prices,
update_order_status,
)
@@ -74,7 +73,9 @@ def test_order_get_subtotal(order_with_lines):
name="Test discount",
)
- recalculate_order(order_with_lines)
+ fetch_order_prices_if_expired(
+ order_with_lines, get_plugins_manager(), force_update=True
+ )
target_subtotal = order_with_lines.total - order_with_lines.shipping_price
assert order_with_lines.get_subtotal() == target_subtotal
@@ -167,45 +168,6 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_sale(
assert line.unit_discount_reason
-def test_add_variant_to_draft_order_adds_line_for_new_variant_with_tax(
- order_with_lines, product, product_translation_fr, settings, info, site_settings
-):
- order = order_with_lines
- variant = product.variants.get()
- lines_before = order.lines.count()
- settings.LANGUAGE_CODE = "fr"
- unit_price = TaxedMoney(net=Money(8, "USD"), gross=Money(10, "USD"))
- total_price = TaxedMoney(net=Money("30.34", "USD"), gross=Money("36.49", "USD"))
- unit_price_data = OrderTaxedPricesData(
- undiscounted_price=unit_price,
- price_with_discounts=unit_price,
- )
- total_price_data = OrderTaxedPricesData(
- undiscounted_price=total_price,
- price_with_discounts=total_price,
- )
- manager = Mock(
- calculate_order_line_unit=Mock(return_value=unit_price_data),
- calculate_order_line_total=Mock(return_value=total_price_data),
- get_order_line_tax_rate=Mock(return_value=0.25),
- )
-
- add_variant_to_order(
- order, variant, 1, info.context.user, info.context.app, manager, site_settings
- )
-
- line = order.lines.last()
- assert order.lines.count() == lines_before + 1
- assert line.product_sku == variant.sku
- assert line.product_variant_id == variant.get_global_id()
- assert line.quantity == 1
- assert line.unit_price == unit_price
- assert line.total_price == total_price
- assert line.translated_product_name == str(variant.product.translated)
- assert line.variant_name == str(variant)
- assert line.product_name == str(variant.product)
-
-
def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
order_with_lines, product, product_translation_fr, settings, info, site_settings
):
@@ -560,112 +522,6 @@ def test_queryset_ready_to_capture(channel_USD):
assert OrderStatus.CANCELED not in statuses
-@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")
-def test_update_order_prices(
- mocked_calculate_order_line_unit, order_with_lines, site_settings
-):
- manager = get_plugins_manager()
- channel = order_with_lines.channel
- address = order_with_lines.shipping_address
- address.country = "DE"
- address.save()
-
- line_1 = order_with_lines.lines.first()
- variant_1 = line_1.variant
- product_1 = variant_1.product
- variant_channel_listing_1 = variant_1.channel_listings.get(channel=channel)
- price_1 = variant_1.get_price(
- product_1, [], channel, variant_channel_listing_1, None
- )
- price_1 = TaxedMoney(net=price_1, gross=price_1)
-
- line_2 = order_with_lines.lines.last()
- variant_2 = line_2.variant
- product_2 = variant_2.product
- variant_channel_listing_2 = variant_2.channel_listings.get(channel=channel)
- price_2 = variant_2.get_price(
- product_2, [], channel, variant_channel_listing_2, None
- )
- price_2 = TaxedMoney(net=price_2, gross=price_2)
-
- mocked_calculate_order_line_unit.side_effect = [
- OrderTaxedPricesData(
- undiscounted_price=price_1,
- price_with_discounts=price_1,
- ),
- OrderTaxedPricesData(
- undiscounted_price=price_2,
- price_with_discounts=price_2,
- ),
- ]
-
- shipping_price = order_with_lines.shipping_method.channel_listings.get(
- channel_id=order_with_lines.channel_id
- ).price
- shipping_price = TaxedMoney(net=shipping_price, gross=shipping_price)
-
- update_order_prices(
- order_with_lines, manager, site_settings.include_taxes_in_prices
- )
-
- line_1.refresh_from_db()
- line_2.refresh_from_db()
- assert line_1.unit_price == price_1
- assert line_2.unit_price == price_2
- assert order_with_lines.shipping_price == shipping_price
- assert order_with_lines.shipping_tax_rate == Decimal("0.0")
- total = line_1.total_price + line_2.total_price + shipping_price
- assert order_with_lines.total == total
-
-
-def test_update_order_prices_tax_included(order_with_lines, vatlayer, site_settings):
- manager = get_plugins_manager()
-
- channel = order_with_lines.channel
- address = order_with_lines.shipping_address
- address.country = "DE"
- address.save()
-
- line_1 = order_with_lines.lines.first()
- variant_1 = line_1.variant
- product_1 = variant_1.product
- variant_channel_listing_1 = variant_1.channel_listings.get(channel=channel)
- price_1 = variant_1.get_price(
- product_1, [], channel, variant_channel_listing_1, None
- )
- line_1.unit_price_gross = price_1
- line_1.base_unit_price = price_1
- line_1.save()
-
- line_2 = order_with_lines.lines.last()
- variant_2 = line_2.variant
- product_2 = variant_2.product
- variant_channel_listing_2 = variant_2.channel_listings.get(channel=channel)
- price_2 = variant_2.get_price(
- product_2, [], channel, variant_channel_listing_2, None
- )
- line_2.unit_price_gross = price_2
- line_2.base_unit_price = price_2
- line_2.save()
-
- shipping_price = order_with_lines.shipping_method.channel_listings.get(
- channel_id=order_with_lines.channel_id
- ).price
-
- update_order_prices(
- order_with_lines, manager, site_settings.include_taxes_in_prices
- )
-
- line_1.refresh_from_db()
- line_2.refresh_from_db()
- assert line_1.unit_price.gross == price_1
- assert line_2.unit_price.gross == price_2
- assert order_with_lines.shipping_price.gross == shipping_price
- assert order_with_lines.shipping_tax_rate == Decimal("0.19")
- total = line_1.total_price + line_2.total_price + order_with_lines.shipping_price
- assert order_with_lines.total == total
-
-
def _calculate_order_weight_from_lines(order):
weight = zero_weight()
for line in order.lines.all():
@@ -779,7 +635,7 @@ def test_get_voucher_discount_for_order_voucher_validation(
mock_validate_voucher.assert_called_once_with(
voucher,
- subtotal,
+ subtotal.gross,
quantity,
customer_email,
order_with_lines.channel,
diff --git a/saleor/order/tests/test_order_search.py b/saleor/order/tests/test_order_search.py
index 79526936d8..d63a8c3c94 100644
--- a/saleor/order/tests/test_order_search.py
+++ b/saleor/order/tests/test_order_search.py
@@ -5,7 +5,7 @@ from ..models import OrderLine
from ..search import prepare_order_search_vector_value, update_order_search_vector
-def test_update_order_search_vector(order):
+def test_update_order_search_vector_auto_save(order):
# given
order.search_vector = ""
order.save(update_fields=["search_vector"])
@@ -15,9 +15,25 @@ def test_update_order_search_vector(order):
update_order_search_vector(order)
# then
+ order.refresh_from_db()
assert order.search_vector
+def test_update_order_search_vector_without_save(order):
+ # given
+ order.search_vector = ""
+ order.save(update_fields=["search_vector"])
+ assert not order.search_vector
+
+ # when
+ update_order_search_vector(order, save=False)
+
+ # then
+ assert order.search_vector
+ order.refresh_from_db()
+ assert not order.search_vector
+
+
def test_prepare_order_search_vector_value(
order_with_lines, address_usa, payment_dummy
):
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 3968807bd1..1f0253be55 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -1,6 +1,4 @@
-import copy
from decimal import Decimal
-from unittest.mock import Mock
import pytest
from prices import Money, TaxedMoney
@@ -9,7 +7,6 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...discount import DiscountValueType, OrderDiscountType
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCardEvent
-from ...order.interface import OrderTaxedPricesData
from ...plugins.manager import get_plugins_manager
from .. import OrderStatus
from ..events import OrderEvents
@@ -22,8 +19,6 @@ from ..utils import (
get_total_order_discount_excluding_shipping,
get_valid_shipping_methods_for_order,
match_orders_with_new_user,
- update_taxes_for_order_line,
- update_taxes_for_order_lines,
)
@@ -252,77 +247,6 @@ def test_get_valid_shipping_methods_for_order_shipping_not_required(
assert valid_shipping_methods == []
-def test_update_taxes_for_order_lines(order_with_lines):
- # given
- unit_price = TaxedMoney(net=Money("10.23", "USD"), gross=Money("15.80", "USD"))
- total_price = TaxedMoney(net=Money("30.34", "USD"), gross=Money("36.49", "USD"))
- tax_rate = Decimal("0.23")
- unit_price_data = OrderTaxedPricesData(
- undiscounted_price=unit_price,
- price_with_discounts=unit_price,
- )
- total_price_data = OrderTaxedPricesData(
- undiscounted_price=total_price,
- price_with_discounts=total_price,
- )
- manager = Mock(
- calculate_order_line_unit=Mock(return_value=unit_price_data),
- calculate_order_line_total=Mock(return_value=total_price_data),
- get_order_line_tax_rate=Mock(return_value=tax_rate),
- )
-
- # when
- update_taxes_for_order_lines(
- order_with_lines.lines.all(), order_with_lines, manager, True
- )
-
- # then
- for line in order_with_lines.lines.all():
- assert line.unit_price == unit_price
- assert line.total_price == total_price
- assert line.tax_rate == tax_rate
- assert line.undiscounted_unit_price == unit_price
- assert line.undiscounted_total_price == total_price
-
-
-def test_update_taxes_for_order_lines_discounted_price(order_with_lines):
- # given
- unit_discount_amount = Decimal("2.00")
-
- unit_price = TaxedMoney(net=Money("10.23", "USD"), gross=Money("15.80", "USD"))
- total_price = TaxedMoney(net=Money("30.34", "USD"), gross=Money("36.49", "USD"))
- tax_rate = Decimal("0.23")
- discount = TaxedMoney(
- net=Money(unit_discount_amount, "USD"), gross=Money(unit_discount_amount, "USD")
- )
- unit_price_data = OrderTaxedPricesData(
- undiscounted_price=unit_price + discount,
- price_with_discounts=unit_price,
- )
- total_price_data = OrderTaxedPricesData(
- undiscounted_price=total_price + discount,
- price_with_discounts=total_price,
- )
- manager = Mock(
- calculate_order_line_unit=Mock(return_value=unit_price_data),
- calculate_order_line_total=Mock(return_value=total_price_data),
- get_order_line_tax_rate=Mock(return_value=tax_rate),
- )
-
- # when
- update_taxes_for_order_lines(
- order_with_lines.lines.all(), order_with_lines, manager, True
- )
-
- # then
- for line in order_with_lines.lines.all():
- assert line.unit_price == unit_price
- assert line.total_price == total_price
- assert line.tax_rate == tax_rate
- assert line.undiscounted_unit_price == unit_price + discount
- assert line.undiscounted_total_price == total_price + discount
-
-
def test_add_variant_to_order(
order, customer_user, variant, site_settings, discount_info
):
@@ -476,52 +400,6 @@ def test_add_gift_cards_to_order_no_checkout_user(
}
-def test_update_taxes_for_order_line_deleted_variant(order_with_lines):
- # given
- order_line = order_with_lines.lines.first()
- order_line_unchanged_copy = copy.deepcopy(order_line)
- unit_discount_amount = Decimal("2.00")
-
- unit_price = TaxedMoney(net=Money("10.23", "USD"), gross=Money("15.80", "USD"))
- total_price = TaxedMoney(net=Money("30.34", "USD"), gross=Money("36.49", "USD"))
- tax_rate = Decimal("0.23")
- discount = TaxedMoney(
- net=Money(unit_discount_amount, "USD"), gross=Money(unit_discount_amount, "USD")
- )
- unit_price_data = OrderTaxedPricesData(
- undiscounted_price=unit_price + discount,
- price_with_discounts=unit_price,
- )
- total_price_data = OrderTaxedPricesData(
- undiscounted_price=total_price + discount,
- price_with_discounts=total_price,
- )
- manager = Mock(
- calculate_order_line_unit=Mock(return_value=unit_price_data),
- calculate_order_line_total=Mock(return_value=total_price_data),
- get_order_line_tax_rate=Mock(return_value=tax_rate),
- )
-
- # when
- order_line.variant = None
- update_taxes_for_order_line(order_line, order_with_lines, manager, True)
-
- # then
- assert order_line.unit_price == order_line_unchanged_copy.unit_price
- assert order_line.total_price == order_line_unchanged_copy.total_price
- assert order_line.tax_rate == order_line_unchanged_copy.tax_rate
- assert order_line.undiscounted_unit_price == order_line_unchanged_copy.unit_price
- assert order_line.undiscounted_total_price == order_line_unchanged_copy.total_price
-
-
-def test_get_total_order_discount_excluding_shipping_no_discounts(order):
- # when
- discount_amount = get_total_order_discount_excluding_shipping(order)
-
- # then
- assert discount_amount == Money("0", order.currency)
-
-
def test_get_total_order_discount_excluding_shipping(order, voucher_shipping_type):
# given
order.discounts.create(
@@ -588,3 +466,11 @@ def test_get_total_order_discount_excluding_shipping_no_shipping_discounts(
assert discount_amount == Money(
discount_1.amount_value + discount_2.amount_value, order.currency
)
+
+
+def test_get_total_order_discount_excluding_shipping_no_discounts(order):
+ # when
+ discount_amount = get_total_order_discount_excluding_shipping(order)
+
+ # then
+ assert discount_amount == Money("0", order.currency)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 811a62e110..7031a9f626 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,4 +1,3 @@
-import copy
from decimal import Decimal
from functools import partial, wraps
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union, cast
@@ -22,8 +21,6 @@ from ..discount.utils import (
)
from ..giftcard import events as gift_card_events
from ..giftcard.models import GiftCard
-from ..order.fetch import OrderLineInfo
-from ..order.models import Order, OrderLine
from ..payment.model_helpers import get_total_authorized
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.interface import ShippingMethodData
@@ -40,12 +37,15 @@ from ..warehouse.management import (
)
from ..warehouse.models import Warehouse
from . import (
+ ORDER_EDITABLE_STATUS,
FulfillmentStatus,
OrderAuthorizeStatus,
OrderChargeStatus,
OrderStatus,
events,
)
+from .fetch import OrderLineInfo
+from .models import Order, OrderLine
if TYPE_CHECKING:
from ..app.models import App
@@ -105,175 +105,38 @@ def get_voucher_discount_assigned_to_order(order: Order):
return order.discounts.filter(type=OrderDiscountType.VOUCHER).first()
-def recalculate_order_discounts(
- order: Order,
-) -> List[Tuple[OrderDiscount, OrderDiscount]]:
- """Recalculate all order discounts assigned to order.
-
- It returns the list of tuples which contains order discounts where the amount has
- been changed.
- """
-
- changed_order_discounts = []
- order_discounts = order.discounts.filter(type=OrderDiscountType.MANUAL)
- for order_discount in order_discounts:
- previous_order_discount = copy.deepcopy(order_discount)
- current_total = order.total.gross.amount
-
- update_order_discount_for_order(
- order,
- order_discount,
- )
- discount_value = order_discount.value
- discount_type = order_discount.value_type
- amount = order_discount.amount
-
- if (
- (
- discount_type == DiscountValueType.PERCENTAGE
- or current_total < discount_value
- )
- # No need to add new event when new and old amount of discount is the same
- and amount != previous_order_discount.amount
- ):
- changed_order_discounts.append(
- # order discount before changes, order discount after update
- (previous_order_discount, order_discount)
- )
- return changed_order_discounts
-
+def invalidate_order_prices(order: Order, *, save: bool = False) -> None:
+ """Mark order as ready for prices recalculation.
-@update_voucher_discount
-def recalculate_order_prices(order: Order, **kwargs):
- # avoid using prefetched order lines
- lines = OrderLine.objects.filter(order_id=order.pk)
- prices = [line.total_price for line in lines]
- total = sum(prices, order.shipping_price)
- undiscounted_total = TaxedMoney(total.net, total.gross)
+ Does nothing if order is not editable
+ (it's status is neither draft, nor unconfirmed).
- voucher_discount = kwargs.get("discount", zero_money(order.currency))
-
- # discount amount can't be greater than order total
- voucher_discount = min(voucher_discount, total.gross)
- total -= voucher_discount
-
- order.total = total
- order.undiscounted_total = undiscounted_total
-
- if voucher_discount:
- assigned_order_discount = get_voucher_discount_assigned_to_order(order)
- if assigned_order_discount:
- assigned_order_discount.amount_value = voucher_discount.amount
- assigned_order_discount.value = voucher_discount.amount
- assigned_order_discount.save(update_fields=["value", "amount_value"])
-
-
-def recalculate_order(order: Order, **kwargs):
- """Recalculate and assign total price of order.
-
- Total price is a sum of items in order and order shipping price minus
- discount amount.
-
- Voucher discount amount is recalculated by default. To avoid this, pass
- update_voucher_discount argument set to False.
+ By default, no save to database is executed.
+ Either manually call `order.save()` after, or pass `save=True`.
"""
+ if order.status not in ORDER_EDITABLE_STATUS:
+ return
- recalculate_order_prices(order, **kwargs)
+ order.should_refresh_prices = True
- changed_order_discounts = recalculate_order_discounts(order)
- events.order_discounts_automatically_updated_event(order, changed_order_discounts)
+ if save:
+ order.save(update_fields=["should_refresh_prices"])
- order.save(
- update_fields=[
- "total_net_amount",
- "total_gross_amount",
- "undiscounted_total_net_amount",
- "undiscounted_total_gross_amount",
- "currency",
- "updated_at",
- ]
- )
- recalculate_order_weight(order)
+def recalculate_order_weight(order: Order, *, save: bool = False):
+ """Recalculate order weights.
-def recalculate_order_weight(order):
- """Recalculate order weights."""
+ By default, no save to database is executed.
+ Either manually call `order.save()` after, or pass `save=True`.
+ """
weight = zero_weight()
for line in order.lines.all():
if line.variant:
weight += line.variant.get_weight() * line.quantity
weight.unit = order.weight.unit
order.weight = weight
- order.save(update_fields=["weight", "updated_at"])
-
-
-def update_taxes_for_order_line(
- line: "OrderLine", order: "Order", manager, tax_included
-):
- variant = line.variant
- if not variant:
- return
- product = variant.product # type: ignore
-
- line_price = line.unit_price.gross if tax_included else line.unit_price.net
- line.unit_price = TaxedMoney(line_price, line_price)
-
- unit_price_data = manager.calculate_order_line_unit(order, line, variant, product)
- total_price_data = manager.calculate_order_line_total(order, line, variant, product)
- line.unit_price = unit_price_data.price_with_discounts
- line.total_price = total_price_data.price_with_discounts
- line.undiscounted_unit_price = unit_price_data.undiscounted_price
- line.undiscounted_total_price = total_price_data.undiscounted_price
- if line.unit_price.tax and line.unit_price.net:
- line.tax_rate = manager.get_order_line_tax_rate(
- order, product, variant, None, line.unit_price
- )
-
-
-def update_taxes_for_order_lines(
- lines: Iterable[OrderLine], order: "Order", manager, tax_included
-):
- for line in lines:
- update_taxes_for_order_line(line, order, manager, tax_included=tax_included)
- manager.update_taxes_for_order_lines(order, lines)
- OrderLine.objects.bulk_update(
- lines,
- [
- "tax_rate",
- "unit_price_net_amount",
- "unit_price_gross_amount",
- "total_price_net_amount",
- "total_price_gross_amount",
- "undiscounted_unit_price_gross_amount",
- "undiscounted_unit_price_net_amount",
- "undiscounted_total_price_gross_amount",
- "undiscounted_total_price_net_amount",
- ],
- )
-
-
-def update_order_prices(order: Order, manager: "PluginsManager", tax_included: bool):
- """Update prices in order with given discounts and proper taxes."""
-
- update_taxes_for_order_lines(order.lines.all(), order, manager, tax_included)
-
- if order.shipping_method:
- shipping_price = manager.calculate_order_shipping(order)
- order.shipping_price = shipping_price
- order.shipping_tax_rate = manager.get_order_shipping_tax_rate(
- order, shipping_price
- )
- order.save(
- update_fields=[
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_tax_rate",
- "currency",
- "updated_at",
- ]
- )
-
- recalculate_order(order)
+ if save:
+ order.save(update_fields=["weight", "updated_at"])
def _calculate_quantity_including_returns(order):
@@ -413,19 +276,6 @@ def add_variant_to_order(
undiscounted_total_price=undiscounted_total_price,
variant=variant,
)
- unit_price_data = manager.calculate_order_line_unit(
- order, line, variant, product
- )
- total_line_price_data = manager.calculate_order_line_total(
- order, line, variant, product
- )
- line.unit_price = unit_price_data.price_with_discounts
- line.total_price = total_line_price_data.price_with_discounts
- line.undiscounted_unit_price = unit_price_data.undiscounted_price
- line.undiscounted_total_price = total_line_price_data.undiscounted_price
- line.tax_rate = manager.get_order_line_tax_rate(
- order, product, variant, None, unit_price
- )
manager.update_taxes_for_order_lines(order, list(order.lines.all()))
@@ -455,16 +305,6 @@ def add_variant_to_order(
line.save(
update_fields=[
- "currency",
- "unit_price_net_amount",
- "unit_price_gross_amount",
- "total_price_net_amount",
- "total_price_gross_amount",
- "undiscounted_unit_price_gross_amount",
- "undiscounted_unit_price_net_amount",
- "undiscounted_total_price_gross_amount",
- "undiscounted_total_price_net_amount",
- "tax_rate",
"unit_discount_amount",
"unit_discount_value",
"unit_discount_reason",
@@ -991,8 +831,6 @@ def update_discount_for_order_line(
# from db
order_line.save(update_fields=fields_to_update)
- update_taxes_for_order_lines(order.lines.all(), order, manager, tax_included)
-
def remove_discount_from_order_line(
order_line: OrderLine, order: "Order", manager, tax_included
@@ -1021,16 +859,6 @@ def remove_discount_from_order_line(
"base_unit_price_amount",
"total_price_net_amount",
"total_price_gross_amount",
- ]
- )
-
- update_taxes_for_order_lines(order.lines.all(), order, manager, tax_included)
- order_line.save(
- update_fields=[
- "unit_price_gross_amount",
- "unit_price_net_amount",
- "total_price_net_amount",
- "total_price_gross_amount",
"tax_rate",
]
)
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
index 46a2fa03f5..cb1ad391a2 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py
@@ -19,7 +19,6 @@ from saleor.payment.gateways.adyen.utils.common import (
from saleor.payment.interface import PaymentMethodInfo
from saleor.payment.utils import price_from_minor_unit, price_to_minor_unit
-from ......checkout.interface import CheckoutTaxedPricesData
from ...utils.common import prepare_address_request_data
@@ -132,29 +131,33 @@ def test_append_checkout_details_without_sku(
}
[email protected]("saleor.plugins.manager.PluginsManager.calculate_checkout_line_total")
@mock.patch("saleor.plugins.manager.PluginsManager.calculate_checkout_line_unit_price")
def test_append_checkout_details_tax_included(
mocked_calculate_checkout_line_unit_price,
+ mocked_calculate_checkout_line_total,
dummy_payment_data,
payment_dummy,
checkout_ready_to_complete,
):
# given
+ line = checkout_ready_to_complete.lines.first()
+ quantity = line.quantity
+
net = Money(100, "USD")
gross = Money(123, "USD")
# tax 23 %
unit_price = quantize_price(TaxedMoney(net=net, gross=gross), "USD")
+ total_price = quantize_price(
+ TaxedMoney(net=net * quantity, gross=gross * quantity), "USD"
+ )
country_code = checkout_ready_to_complete.get_country()
- mocked_calculate_checkout_line_unit_price.return_value = CheckoutTaxedPricesData(
- price_with_sale=unit_price,
- undiscounted_price=unit_price,
- price_with_discounts=unit_price,
- )
+ mocked_calculate_checkout_line_unit_price.return_value = unit_price
+ mocked_calculate_checkout_line_total.return_value = total_price
checkout_ready_to_complete.payments.add(payment_dummy)
- line = checkout_ready_to_complete.lines.first()
payment_data = {
"reference": "test",
}
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py
index 4e4efc96d5..36d8e61baf 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_api_response.py
@@ -2,6 +2,7 @@ from unittest.mock import patch
from Adyen.client import AdyenResult
from django.core.exceptions import ValidationError
+from django.utils import timezone
from ......payment import ChargeStatus
from ......payment.gateways.adyen.webhooks import handle_api_response
@@ -153,6 +154,8 @@ def test_handle_api_response_auto_capture_cannot_create_order_variant_deleted(
checkout = payment_adyen_for_checkout.checkout
checkout.lines.first().delete()
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
plugin = adyen_plugin(adyen_auto_capture=True)
diff --git a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
index 07385d14fb..388b1e6ae3 100644
--- a/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
+++ b/saleor/payment/gateways/adyen/tests/webhooks/test_handle_notifications.py
@@ -6,6 +6,7 @@ from unittest.mock import patch
import graphene
import pytest
from django.core.exceptions import ValidationError
+from django.utils import timezone
from ......checkout import calculations
from ......checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -269,6 +270,8 @@ def test_handle_authorization_for_checkout_one_of_variants_deleted(
payment.save()
checkout.lines.first().delete()
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
notification = notification(
@@ -744,6 +747,8 @@ def test_handle_capture_for_checkout_order_not_created_checkout_line_variant_del
payment.save()
checkout.lines.first().delete()
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
notification = notification(
@@ -1360,6 +1365,8 @@ def test_handle_not_created_order_order_not_created_checkout_line_variant_delete
# given
checkout = payment_adyen_for_checkout.checkout
checkout.lines.first().variant.delete()
+ checkout.price_expiration = timezone.now()
+ checkout.save()
payment_adyen_for_checkout.charge_status = ChargeStatus.FULLY_CHARGED
payment_adyen_for_checkout.captured_amount = payment_adyen_for_checkout.total
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index 730697c13d..b6cd7a918a 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -11,7 +11,11 @@ from django.conf import settings
from django_countries.fields import Country
from requests.exceptions import ConnectTimeout
-from .....checkout.calculations import checkout_shipping_price, checkout_total
+from .....checkout.calculations import (
+ checkout_line_unit_price,
+ checkout_shipping_price,
+ checkout_total,
+)
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....checkout.utils import is_shipping_required
@@ -266,14 +270,13 @@ def append_checkout_details(payment_information: "PaymentData", payment_data: di
line_items = []
for line_info in lines:
- address = checkout_info.shipping_address or checkout_info.billing_address
- unit_price = manager.calculate_checkout_line_unit_price(
- checkout_info,
- lines,
- line_info,
- address,
- discounts,
- ).price_with_sale
+ unit_price = checkout_line_unit_price(
+ manager=manager,
+ checkout_info=checkout_info,
+ lines=lines,
+ checkout_line_info=line_info,
+ discounts=discounts,
+ )
unit_gross = unit_price.gross.amount
unit_net = unit_price.net.amount
tax_amount = unit_price.tax.amount
diff --git a/saleor/payment/gateways/np_atobarai/tests/conftest.py b/saleor/payment/gateways/np_atobarai/tests/conftest.py
index d837a1f828..ee22b64902 100644
--- a/saleor/payment/gateways/np_atobarai/tests/conftest.py
+++ b/saleor/payment/gateways/np_atobarai/tests/conftest.py
@@ -5,9 +5,9 @@ from unittest.mock import patch
import pytest
from .....order.actions import create_refund_fulfillment
-from .....order.utils import recalculate_order
from .....plugins.manager import get_plugins_manager
from .....plugins.models import PluginConfiguration
+from .....tests.fixtures import recalculate_order
from ....interface import AddressData, PaymentLineData, PaymentLinesData
from ..api_types import get_api_config
from ..const import (
diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.py
index c8fd17d8cf..f06f596465 100644
--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py
+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py
@@ -4,6 +4,7 @@ from unittest.mock import Mock, patch
import pytest
from django.core.exceptions import ValidationError
+from django.utils import timezone
from stripe.stripe_object import StripeObject
from .....checkout.complete_checkout import complete_checkout
@@ -1360,6 +1361,8 @@ def test_finalize_checkout_not_created_checkout_variant_deleted_order_payment_re
checkout = payment_stripe_for_checkout.checkout
checkout.lines.first().delete()
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
_finalize_checkout(
checkout,
@@ -1417,6 +1420,8 @@ def test_finalize_checkout_not_created_checkout_variant_deleted_order_payment_vo
checkout = payment_stripe_for_checkout.checkout
checkout.lines.first().delete()
+ checkout.price_expiration = timezone.now()
+ checkout.save(update_fields=["price_expiration"])
_finalize_checkout(
checkout,
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index b166eb6415..89f782b469 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -71,7 +71,7 @@ def get_expected_checkout_payment_lines(
line_info,
address,
discounts,
- ).undiscounted_price.gross.amount
+ ).gross.amount
quantity = line_info.line.quantity
variant_id = line_info.variant.id
product_name = f"{line_info.variant.product.name}, {line_info.variant.name}"
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index d262f21209..7c14ebe243 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -81,7 +81,7 @@ def create_checkout_payment_lines_information(
address,
discounts,
)
- unit_gross = unit_price.price_with_sale.gross.amount
+ unit_gross = unit_price.gross.amount
quantity = line_info.line.quantity
product_name = f"{line_info.variant.product.name}, {line_info.variant.name}"
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index f936d0a1b7..ef38118546 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -289,19 +289,12 @@ def get_checkout_lines_data(
item_code = line_info.variant.sku or line_info.variant.get_global_id()
tax_code = retrieve_tax_code_from_meta(product, default=None)
tax_code = tax_code or retrieve_tax_code_from_meta(product_type)
- prices_data = base_calculations.base_checkout_line_total(
+ checkout_line_total = base_calculations.calculate_base_line_total_price(
line_info,
channel,
discounts,
)
- if tax_included:
- undiscounted_amount = prices_data.undiscounted_price.gross.amount
- price_with_discounts_amount = prices_data.price_with_discounts.gross.amount
- else:
- undiscounted_amount = prices_data.undiscounted_price.net.amount
- price_with_discounts_amount = prices_data.price_with_discounts.net.amount
-
# This is a workaround for Avatax and sending a lines with amount 0. Like
# order lines which are fully discounted for some reason. If we use a
# standard tax_code, Avatax will raise an exception: "When shipping
@@ -312,7 +305,7 @@ def get_checkout_lines_data(
# combination with caps, thresholds, or base rules."
tax_code = (
tax_code
- if undiscounted_amount and not tax_override_data
+ if checkout_line_total.amount and not tax_override_data
else DEFAULT_TAX_CODE
)
append_line_to_data_kwargs = {
@@ -328,7 +321,7 @@ def get_checkout_lines_data(
append_line_to_data(
**append_line_to_data_kwargs,
- amount=price_with_discounts_amount,
+ amount=checkout_line_total.amount,
ref1=line_info.variant.sku,
)
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index e3f0a14ccb..44325d2a55 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -14,7 +14,6 @@ from prices import Money, TaxedMoney, TaxedMoneyRange
from ...checkout import base_calculations
from ...checkout.fetch import fetch_checkout_lines
-from ...checkout.interface import CheckoutTaxedPricesData
from ...core.taxes import TaxError, TaxType, charge_taxes_on_shipping, zero_taxed_money
from ...discount import DiscountInfo
from ...order.interface import OrderTaxedPricesData
@@ -204,11 +203,7 @@ class AvataxPlugin(BasePlugin):
)
currency = checkout_info.checkout.currency
- taxed_total = CheckoutTaxedPricesData(
- price_with_discounts=zero_taxed_money(currency),
- price_with_sale=zero_taxed_money(currency),
- undiscounted_price=zero_taxed_money(currency),
- )
+ taxed_total = zero_taxed_money(currency)
for line in lines:
taxed_line_total_data = self._calculate_checkout_line_total_price(
@@ -218,16 +213,12 @@ class AvataxPlugin(BasePlugin):
# for some cases we will need a base_value but no need to call it for
# each line
base_value=SimpleLazyObject( # type:ignore
- lambda: base_calculations.base_checkout_line_total(
+ lambda: base_calculations.calculate_base_line_total_price(
line, checkout_info.channel, discounts
)
),
)
- taxed_total.undiscounted_price += taxed_line_total_data.undiscounted_price
- taxed_total.price_with_sale += taxed_line_total_data.price_with_sale
- taxed_total.price_with_discounts += (
- taxed_line_total_data.price_with_discounts
- )
+ taxed_total += taxed_line_total_data
base_shipping_price = base_calculations.base_checkout_delivery_price(
checkout_info, lines
@@ -236,21 +227,19 @@ class AvataxPlugin(BasePlugin):
currency, response.get("lines", []), base_shipping_price
)
- taxed_total.undiscounted_price += shipping_price
- taxed_total.price_with_sale += shipping_price
- taxed_total.price_with_discounts += shipping_price
+ taxed_total += shipping_price
return max(
- taxed_total.price_with_discounts,
- zero_taxed_money(taxed_total.price_with_discounts.currency),
+ taxed_total,
+ zero_taxed_money(taxed_total.currency),
)
def _calculate_checkout_shipping(
- self, currency: str, lines: List[Dict], shipping_price: TaxedMoney
+ self, currency: str, lines: List[Dict], shipping_price: Money
) -> TaxedMoney:
discount_amount = Decimal(0.0)
shipping_tax = Decimal(0.0)
- shipping_net = shipping_price.net.amount
+ shipping_net = shipping_price.amount
for line in lines:
if line["itemCode"] == "Shipping":
# The lineAmount does not include the discountAmount,
@@ -265,9 +254,7 @@ class AvataxPlugin(BasePlugin):
lambda: Site.objects.get_current().settings.include_taxes_in_prices
)
if currency == "JPY" and tax_included():
- shipping_gross = Money(
- amount=shipping_price.gross.amount - discount_amount, currency=currency
- )
+ shipping_gross = Money(amount=shipping_price.amount, currency=currency)
shipping_net = Money(
amount=shipping_gross.amount - shipping_tax, currency=currency
)
@@ -304,7 +291,7 @@ class AvataxPlugin(BasePlugin):
currency = str(response.get("currencyCode"))
return self._calculate_checkout_shipping(
- currency, response.get("lines", []), base_shipping_price
+ currency, response.get("lines", []), base_shipping_price.net
)
def preprocess_order_creation(
@@ -386,8 +373,8 @@ class AvataxPlugin(BasePlugin):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- previous_value: CheckoutTaxedPricesData,
- ) -> CheckoutTaxedPricesData:
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
if self._skip_plugin(previous_value):
return previous_value
@@ -417,13 +404,12 @@ class AvataxPlugin(BasePlugin):
taxes_data: Dict[str, Any],
item_code: str,
tax_included: Callable[[], bool],
- base_value: CheckoutTaxedPricesData,
- ) -> CheckoutTaxedPricesData:
+ base_value: TaxedMoney,
+ ) -> TaxedMoney:
if not taxes_data or "error" in taxes_data:
return base_value
currency = taxes_data.get("currencyCode")
- line_price = None
for line in taxes_data.get("lines", []):
if line.get("itemCode") != item_code:
@@ -436,24 +422,14 @@ class AvataxPlugin(BasePlugin):
net = Decimal(line["lineAmount"])
if currency == "JPY" and tax_included():
- line_gross = Money(
- base_value.price_with_sale.gross.amount - discount_amount, currency
- )
+ line_gross = base_value.gross
line_net = Money(amount=line_gross.amount - tax, currency=currency)
else:
net -= discount_amount
line_gross = Money(amount=net + tax, currency=currency)
line_net = Money(amount=net, currency=currency)
- line_price = TaxedMoney(net=line_net, gross=line_gross)
-
- if line_price is not None:
- return CheckoutTaxedPricesData(
- undiscounted_price=base_value.undiscounted_price,
- price_with_sale=line_price,
- price_with_discounts=line_price,
- )
-
+ return TaxedMoney(net=line_net, gross=line_gross)
return base_value
def calculate_order_line_total(
@@ -536,8 +512,8 @@ class AvataxPlugin(BasePlugin):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- previous_value: CheckoutTaxedPricesData,
- ) -> CheckoutTaxedPricesData:
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
if self._skip_plugin(previous_value):
return previous_value
@@ -555,23 +531,14 @@ class AvataxPlugin(BasePlugin):
quantity = checkout_line_info.line.quantity
taxes_data = get_checkout_tax_data(checkout_info, lines, discounts, self.config)
- default_total = CheckoutTaxedPricesData(
- price_with_discounts=previous_value.price_with_discounts * quantity,
- price_with_sale=previous_value.price_with_sale * quantity,
- undiscounted_price=previous_value.undiscounted_price * quantity,
- )
- taxed_total_prices_data = self._calculate_checkout_line_total_price(
+ default_total = previous_value * quantity
+ taxed_total_price = self._calculate_checkout_line_total_price(
taxes_data,
variant.sku or variant.get_global_id(),
tax_included,
default_total,
)
- return CheckoutTaxedPricesData(
- undiscounted_price=taxed_total_prices_data.undiscounted_price / quantity,
- price_with_sale=taxed_total_prices_data.price_with_sale / quantity,
- price_with_discounts=taxed_total_prices_data.price_with_discounts
- / quantity,
- )
+ return taxed_total_price / quantity
def calculate_order_line_unit(
self,
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml
index 3dec1c4122..c83811afea 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total[False-24.39-30.00-True].yaml
@@ -5,7 +5,7 @@ interactions:
true, "itemCode": "123", "discounted": false, "description": "Test product",
"ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":
true, "itemCode": "Shipping", "discounted": false, "description": null}], "code":
- "73aaa2e9-def5-42f8-9657-9f25c7f4524e", "date": "2022-06-10", "customerCode":
+ "e9fedee4-c581-4ea7-988f-e8842b140a18", "date": "2022-06-09", "customerCode":
0, "discount": null, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":
null, "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},
"shipTo": {"line1": "O\u0142awska 10", "line2": "", "city": "WROC\u0141AW",
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_with_voucher_once_per_order.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_with_voucher_once_per_order.yaml
index 858b35ffd4..e32cd2d7fa 100644
--- a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_with_voucher_once_per_order.yaml
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_with_voucher_once_per_order.yaml
@@ -1,3 +1,4 @@
+
interactions:
- request:
body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
diff --git a/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price[False].yaml b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price[False].yaml
new file mode 100644
index 0000000000..e731fef0fd
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_calculate_checkout_line_unit_price[False].yaml
@@ -0,0 +1,104 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "123", "description": "Test product"}, {"quantity": 1, "amount":
+ "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode": "Shipping",
+ "description": null}], "code": "4d2925ff-2b38-404a-a22a-dd29cea67736", "date":
+ "2021-12-20", "customerCode": 0, "addresses": {"shipFrom": {"line1": "Teczowa
+ 7", "line2": null, "city": "Wroclaw", "region": "", "country": "PL", "postalCode":
+ "53-601"}, "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW",
+ "region": "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":
+ "USD", "email": ""}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '756'
+ User-Agent:
+ - python-requests/2.26.0
+ method: POST
+ uri: https://rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: !!binary |
+ i/8BAICqqqrq/3QNkLOag5m6Le56c3CPgwMkeABEmOch8ySuKuaumaYLiIoFmEGYbeKHbMzajWpH
+ aS8SWYlERkay2816ZGVkhawbup4DgVTcPT/gHZhagU2OwEDr9FF301Tpx/5QtXWLFWqNlXP6aAn7
+ Ydj3oIArZIzb1YHRrT4OnQKHYgKfrnVTNbrSNSjIuAWKcimn3UVQlgIGRgo5MfIGCmTLPvB84Uzl
+ gx0xKHig2Ne5wzADBXZhpmg3lD33rwsooNW+MD7pE4XOpIUTuxRJgfhe8Enjn0LWmihetnshRxZg
+ R/Wboktc4zzPbjPCllYKWW4J1HSFyaZo/UwOzIRzIQVzsig+RR0LEGFyYvHx+aucMnlh+8JCw9Ng
+ rCZiirbLl5QNoWXi4v3mkCQ4n0JaooDZ612ncZb3PqmDqXc1yu3ii+WGAbcjrmCGXXvgsR5xxcdM
+ dh+zEdczznaZUeZEkSh0/5YiSWP+SVhSBAO3JKcKNXKg9gD5L8G2lv5NXDwV0uwQQ3T2fZrIiv+m
+ g1n4Ih9gmnGgKKCfYa9kQnJ+8uTUKc/Y9KbrTat33dANXdv/AUXs90J8vWG0w745bgwVV5NUHsH4
+ SAXM35/H8tDCGAvaaJEtaq1oNLst4UEMBho4l/jnxWlHxbLPhlifw6TIW+bkFisEbGHJKVpeIyt3
+ 9wtuZ2JpigtvPyPly1UopPo8EV5IgRcK5+QI/wMAAFVVVdX/6ZogZzUDNTOPBAi9WZpnADiAg5lD
+ uuUpIQ7ipuJmkqAu6qkqGhAGCWGyxW6D11rFHIe8i4uLxI9E4vtq7cSPhGjUTdXjXFKhapH9Bxw0
+ bQcGAgv1j1hEwbWHunu11sC/gqKsO7iutgYS3RtwACfSNuJvnjEpy3pEJXDQ2rapmrZqLRhQ/AT3
+ Un9vzBGOt9AmyaTBgGEpAZU8/epD9AVh0+uHH+UE0BMT3h1s0Cdtm5MsofiamNRUyIAnRQ4Z3J//
+ wB5cAYwTSsZFOcqZpTIdINLr1BpYYhFNOzi4nOHpqCtHycSWPunx1F64oFYlbH9L4jwrVl5O+oiP
+ oNnp3I9HMJAVlfqceRXyYxSTM9vn/RmowzhDNpjnSWkFy0yNAYkyy5rkITRtghpbt521W8TXWyj1
+ m6nos6jc7NdyQyBKGExpLg8ZXBXFY/LffnVDbtL3RbeYWPdr0Q4vGL3ZrkwoxH0tUbYgRbuzKxgo
+ wjrdf2DmrCbGlIaSEsmy/xYeE1OcxygXzHneUgF3x5AJgb8RZZanO3XWiuW6ZTA47xk+RiElZmst
+ oWTtoD8XTeX+Aayzwy8v/bYBw1JMfdsExhsHkYK8sqMQKMHX+ypJntLplmJZt6Nbl/puYDNTVPAi
+ ZrKeJJeEstBbIl43hZHYP1DFC6PL+Vq1nZ2q6mJYjD5Qx/K4UZr3bbLbL/MT3MP/AABAVVVV9X+6
+ BshZw0HNPAI8Qm8WFhEADuBgHhBufoqTuKm4uQSYiVqIigK4Qag4WdoNsBbQstv+ysrJysvLy8PR
+ onJySuKWbY9nV6KIuP6Nk+wjBO9gYqGuzBdSCFCDg6FkSzPpOeNI/boQBAAHJMa2njO1KRIEAAeR
+ 85CKWDO/IYbgN94B3WleLPzeW1Lrm2qedYmK5znvjeYe73iZCIJpIQdsNHdLwenGy8IyghNMC330
+ sqm23jv4KyiPOoRKA1zpWnGzK13rrxwsSY1lfEcbCcPa19VjVT/WHhwY3sthL7tPEh3WzDOxdClA
+ 0OI0lAmNYvajKeyf3/5BlU0AGdSfdrvXcvql624vw1QiJ+rIcSRDnjKEn3/g5fDAFCXjYJzkwMJM
+ 6pFn6eXewSAYB10hwNcBJoePnCSSq9vaDJXKkrbfopy1Yskrwd7hfGjueGi6d3CQDY2anHkUitvK
+ JVv7a8Hedj1Ek0VWSgvYNG0OJMlm06cI1UWQ+029NQ/FqbO110to9LtjsaWY29xP5YJAjDA4hrnN
+ EZwMJaLGh+9mKD2OTbFbUra1LNvTM0YXyxWBknjmEmMb0qwbncBBEbbj9Q0zZzMRk7ZFlWRYz8Iy
+ McW5S/KFOfc3LRCuOGVC0D+JIrf1bmo/O0u55ruX14TeJcl5Mb9xEkr3OunHT0et/Ausvbv3kdKS
+ 1FjGHu8tTnAcAACoqqqq/k/XAD6rG6ibh6cH6M3BAwLAAQzcDdwdIADSwQ9ipgLuGqCmaqAq6uEW
+ Dm6x8/4rhrFWbeHw8XF4GI4xDAPEMc6NjfFFzCT7+b54ErYw8+pjpeAddc47mU7TyDA4svec8Loo
+ hBhaylluKZbr7ZOFnM8w54vCLW+iZRhAoY9ZtiGXRKHnr8TuehMYXWmFO8kmWoZB2xxn9UJ/zWZt
+ A4U7ya4MHafTNPLWwujXRYGsTZwzZ5jzE87CaAVJFDL14mLYWrDY62IJltLU8J09DP67cYlpsAw8
+ h8GJ+7/4S28r8Nrrq2qW9EWou72TCQbfh/2mWX9DIfHVxSBQGmMW8iMGXi5m//Qcg8JLkFSJsW2g
+ IPQ41Em+1qLWy7muFTyJk2JNdB/DlUr+Uk/M9GlQir2nX3wdw0Uhl2EgW2DnJyw6Xp4Ww56fklx+
+ bBAMNrF4KS3TrH5JbUcDQO2+We8+zVZaF7nFtKVp732pkIWE1zm7a2C7izC7CBN6NAq8LzIWAS12
+ LF0mVrJ1saPQImFu3w4kDIVEwuJwpmvNjDrPMIu6WtZKncDoql5orXUTIZhV9f4Rim3I/7BUEx5i
+ OB0Ty69Y84OHUVwMMLrSr8tr
+ headers:
+ Connection:
+ - keep-alive
+ Content-Encoding:
+ - br
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 20 Dec 2021 16:56:42 GMT
+ Location:
+ - /api/v2/companies/242975/transactions/0
+ ServerDuration:
+ - '00:00:00.0195046'
+ Transfer-Encoding:
+ - chunked
+ Vary:
+ - Accept-Encoding
+ X-Content-Type-Options:
+ - nosniff
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - c7f084b3-949d-406a-9a18-fb6b8dbd92b8
+ x-correlation-id:
+ - c7f084b3-949d-406a-9a18-fb6b8dbd92b8
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 58f788c028..8963750b82 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -113,7 +113,7 @@ def test_calculate_checkout_line_total(
checkout_line_info,
checkout_with_item.shipping_address,
discounts,
- ).price_with_sale
+ )
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -158,7 +158,7 @@ def test_calculate_checkout_line_total_with_variant_on_sale(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_total(
+ line_price = manager.calculate_checkout_line_total(
checkout_info,
lines,
checkout_line,
@@ -167,10 +167,7 @@ def test_calculate_checkout_line_total_with_variant_on_sale(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("30.00"), currency), gross=Money(Decimal("30.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("12.20"), currency), gross=Money(Decimal("15.00"), currency)
)
@@ -226,7 +223,7 @@ def test_calculate_checkout_line_total_with_voucher(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_total(
+ line_price = manager.calculate_checkout_line_total(
checkout_info,
lines,
checkout_line_info,
@@ -235,10 +232,7 @@ def test_calculate_checkout_line_total_with_voucher(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("30.00"), currency), gross=Money(Decimal("30.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("17.07"), currency), gross=Money(Decimal("21.00"), currency)
)
@@ -291,7 +285,7 @@ def test_calculate_checkout_line_total_with_voucher_once_per_order(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_total(
+ line_price = manager.calculate_checkout_line_total(
checkout_info,
lines,
checkout_line_info,
@@ -300,10 +294,7 @@ def test_calculate_checkout_line_total_with_voucher_once_per_order(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("30.00"), currency), gross=Money(Decimal("30.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("21.95"), currency), gross=Money(Decimal("27.00"), currency)
)
@@ -356,7 +347,7 @@ def test_calculate_checkout_line_total_with_variant_on_sale_and_voucher(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_total(
+ line_price = manager.calculate_checkout_line_total(
checkout_info,
lines,
checkout_line_info,
@@ -365,13 +356,7 @@ def test_calculate_checkout_line_total_with_variant_on_sale_and_voucher(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("30.00"), currency), gross=Money(Decimal("30.00"), currency)
- )
- assert line_price_data.price_with_sale == TaxedMoney(
- net=Money(Decimal("4.88"), currency), gross=Money(Decimal("6.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("4.88"), currency), gross=Money(Decimal("6.00"), currency)
)
@@ -425,7 +410,7 @@ def test_calculate_checkout_line_total_with_variant_on_sale_and_voucher_only_onc
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_total(
+ line_price = manager.calculate_checkout_line_total(
checkout_info,
lines,
checkout_line_info,
@@ -434,10 +419,7 @@ def test_calculate_checkout_line_total_with_variant_on_sale_and_voucher_only_onc
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("30.00"), currency), gross=Money(Decimal("30.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("9.76"), currency), gross=Money(Decimal("12.00"), currency)
)
@@ -494,16 +476,14 @@ def test_calculate_checkout_line_without_sku_total(
checkout_info = fetch_checkout_info(checkout_with_item, lines, discounts, manager)
checkout_line_info = lines[0]
- total_prices_data = manager.calculate_checkout_line_total(
+ total_price = manager.calculate_checkout_line_total(
checkout_info,
lines,
checkout_line_info,
checkout_with_item.shipping_address,
discounts,
)
- total = quantize_price(
- total_prices_data.price_with_sale, total_prices_data.price_with_sale.currency
- )
+ total = quantize_price(total_price, total_price.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
)
@@ -2094,7 +2074,7 @@ def test_calculate_checkout_line_unit_price(
site_settings.save()
checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line,
@@ -2102,9 +2082,6 @@ def test_calculate_checkout_line_unit_price(
[],
)
- expected_undiscounted_line_price = TaxedMoney(
- net=Money("10.00", "USD"), gross=Money("10.00", "USD")
- )
if charge_taxes:
expected_line_price = TaxedMoney(
net=Money("8.13", "USD"), gross=Money("10.00", "USD")
@@ -2113,8 +2090,7 @@ def test_calculate_checkout_line_unit_price(
expected_line_price = TaxedMoney(
net=Money("10.00", "USD"), gross=Money("10.00", "USD")
)
- assert line_price_data.undiscounted_price == expected_undiscounted_line_price
- assert line_price_data.price_with_discounts == expected_line_price
+ assert line_price == expected_line_price
@pytest.mark.vcr
@@ -2147,20 +2123,14 @@ def test_calculate_checkout_line_unit_price_in_JPY(
site_settings.save()
checkout_info = fetch_checkout_info(checkout, lines, [], manager)
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line,
checkout.shipping_address,
[],
)
-
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money("1200", "JPY"), gross=Money("1200", "JPY")
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
- net=Money("976", "JPY"), gross=Money("1200", "JPY")
- )
+ assert line_price == TaxedMoney(net=Money("976", "JPY"), gross=Money("1200", "JPY"))
@pytest.mark.vcr
@@ -2197,7 +2167,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_sale(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line,
@@ -2206,10 +2176,9 @@ def test_calculate_checkout_line_unit_price_with_variant_on_sale(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("10.00"), currency), gross=Money(Decimal("10.00"), currency)
+ assert line_price == TaxedMoney(
+ net=Money(Decimal("4.07"), currency), gross=Money(Decimal("5.00"), currency)
)
- assert line_price_data.price_with_discounts == line_price_data.price_with_sale
@pytest.mark.vcr
@@ -2259,7 +2228,7 @@ def test_calculate_checkout_line_unit_price_with_voucher(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line_info,
@@ -2268,10 +2237,7 @@ def test_calculate_checkout_line_unit_price_with_voucher(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("10.00"), currency), gross=Money(Decimal("10.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("5.69"), currency), gross=Money(Decimal("7.00"), currency)
)
@@ -2324,7 +2290,7 @@ def test_calculate_checkout_line_unit_price_with_voucher_once_per_order(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line_info,
@@ -2333,11 +2299,8 @@ def test_calculate_checkout_line_unit_price_with_voucher_once_per_order(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("10.00"), currency), gross=Money(Decimal("10.00"), currency)
- )
# voucher with apply_once_per_order is added in calulation of total unit price
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("7.32"), currency), gross=Money(Decimal("9.00"), currency)
)
@@ -2390,7 +2353,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher(
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line_info,
@@ -2399,10 +2362,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher(
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("10.00"), currency), gross=Money(Decimal("10.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("1.63"), currency), gross=Money(Decimal("2.00"), currency)
)
@@ -2456,7 +2416,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher_onl
currency = checkout_info.checkout.currency
# when
- line_price_data = manager.calculate_checkout_line_unit_price(
+ line_price = manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line_info,
@@ -2465,10 +2425,7 @@ def test_calculate_checkout_line_unit_price_with_variant_on_sale_and_voucher_onl
)
# then
- assert line_price_data.undiscounted_price == TaxedMoney(
- net=Money(Decimal("10.00"), currency), gross=Money(Decimal("10.00"), currency)
- )
- assert line_price_data.price_with_discounts == TaxedMoney(
+ assert line_price == TaxedMoney(
net=Money(Decimal("3.25"), currency), gross=Money(Decimal("4.00"), currency)
)
diff --git a/saleor/plugins/avatax/tests/test_avatax_caching.py b/saleor/plugins/avatax/tests/test_avatax_caching.py
index 97915a525a..0d8ae3eb50 100644
--- a/saleor/plugins/avatax/tests/test_avatax_caching.py
+++ b/saleor/plugins/avatax/tests/test_avatax_caching.py
@@ -314,7 +314,7 @@ def test_calculate_checkout_line_total_use_cache(
# then
result = manager.calculate_checkout_line_total(
checkout_info, lines, checkout_line_info, checkout_info.shipping_address, []
- ).price_with_sale
+ )
# when
assert result == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5", "USD"))
@@ -353,7 +353,7 @@ def test_calculate_checkout_line_save_avatax_response_in_cache(
# then
result = manager.calculate_checkout_line_total(
checkout_info, lines, checkout_line_info, checkout_info.shipping_address, []
- ).price_with_sale
+ )
manager.calculate_checkout_line_total(
checkout_info, lines, checkout_line_info, checkout_info.shipping_address, []
)
@@ -409,7 +409,7 @@ def test_calculate_checkout_line_unit_price_use_cache(
checkout_line_info,
checkout_info.shipping_address,
[],
- ).price_with_sale
+ )
# when
assert result == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5", "USD"))
@@ -452,7 +452,7 @@ def test_calculate_checkout_line_unit_price_save_avatax_response_in_cache(
checkout_line_info,
checkout_info.shipping_address,
[],
- ).price_with_sale
+ )
manager.calculate_checkout_line_unit_price(
checkout_info,
lines,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 4810946b47..50cbcb5b84 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -24,7 +24,6 @@ from graphql.execution import ExecutionResult
from prices import Money, TaxedMoney
from promise.promise import Promise
-from ..checkout.interface import CheckoutTaxedPricesData
from ..core.models import EventDelivery
from ..payment.interface import (
CustomerSource,
@@ -46,7 +45,7 @@ if TYPE_CHECKING:
from ..checkout.models import Checkout
from ..core.middleware import Requestor
from ..core.notify_events import NotifyEventType
- from ..core.taxes import TaxType
+ from ..core.taxes import TaxData, TaxType
from ..discount import DiscountInfo, Voucher
from ..discount.models import Sale
from ..giftcard.models import GiftCard
@@ -265,7 +264,7 @@ class BasePlugin:
Iterable["DiscountInfo"],
TaxedMoney,
],
- CheckoutTaxedPricesData,
+ TaxedMoney,
]
# Calculate checkout line unit price.
@@ -278,7 +277,7 @@ class BasePlugin:
Iterable["DiscountInfo"],
Any,
],
- CheckoutTaxedPricesData,
+ TaxedMoney,
]
# Calculate the shipping costs for checkout.
@@ -506,6 +505,13 @@ class BasePlugin:
Any,
]
+ get_taxes_for_checkout: Callable[
+ ["CheckoutInfo", Iterable["CheckoutLineInfo"], Any],
+ Optional["TaxData"],
+ ]
+
+ get_taxes_for_order: Callable[["Order", Any], Optional["TaxData"]]
+
get_client_token: Callable[[Any, Any], Any]
get_order_line_tax_rate: Callable[
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 2860e5d0ae..074b1ea46a 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -26,12 +26,11 @@ from prices import Money, TaxedMoney
from ..channel.models import Channel
from ..checkout import base_calculations
-from ..checkout.interface import CheckoutTaxedPricesData
from ..core.models import EventDelivery
from ..core.payments import PaymentInterface
from ..core.prices import quantize_price
-from ..core.taxes import TaxType, zero_money, zero_taxed_money
-from ..discount import DiscountInfo, VoucherType
+from ..core.taxes import TaxData, TaxType, zero_money, zero_taxed_money
+from ..discount import DiscountInfo
from ..order.interface import OrderTaxedPricesData
from .base_plugin import ExcludedShippingMethod, ExternalAccessTokens
from .models import PluginConfiguration
@@ -226,17 +225,18 @@ class PluginsManager(PaymentInterface):
discounts,
lines,
)
+ taxed_default_value = TaxedMoney(net=default_value, gross=default_value)
- if default_value <= zero_taxed_money(currency):
+ if default_value <= zero_money(currency):
return quantize_price(
- default_value,
+ taxed_default_value,
currency,
)
return quantize_price(
self.__run_method_on_plugins(
"calculate_checkout_total",
- default_value,
+ taxed_default_value,
checkout_info,
lines,
address,
@@ -260,7 +260,7 @@ class PluginsManager(PaymentInterface):
line_info,
address,
discounts,
- ).price_with_discounts
+ )
for line_info in lines
]
currency = checkout_info.checkout.currency
@@ -277,9 +277,8 @@ class PluginsManager(PaymentInterface):
address: Optional["Address"],
discounts: Iterable[DiscountInfo],
) -> TaxedMoney:
- default_value = base_calculations.base_checkout_delivery_price(
- checkout_info, lines
- )
+ price = base_calculations.base_checkout_delivery_price(checkout_info, lines)
+ default_value = TaxedMoney(price, price)
return quantize_price(
self.__run_method_on_plugins(
"calculate_checkout_shipping",
@@ -364,15 +363,16 @@ class PluginsManager(PaymentInterface):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- ) -> CheckoutTaxedPricesData:
- default_value = base_calculations.base_checkout_line_total(
+ ) -> TaxedMoney:
+ default_value = base_calculations.calculate_base_line_total_price(
checkout_line_info,
checkout_info.channel,
discounts,
)
+ default_taxed_value = TaxedMoney(net=default_value, gross=default_value)
line_total = self.__run_method_on_plugins(
"calculate_checkout_line_total",
- default_value,
+ default_taxed_value,
checkout_info,
lines,
checkout_line_info,
@@ -381,16 +381,7 @@ class PluginsManager(PaymentInterface):
channel_slug=checkout_info.channel.slug,
)
currency = checkout_info.checkout.currency
- line_total.price_with_sale = quantize_price(
- line_total.price_with_sale, currency
- )
- line_total.price_with_discounts = quantize_price(
- line_total.price_with_discounts, currency
- )
- line_total.undiscounted_price = quantize_price(
- line_total.undiscounted_price, currency
- )
- return line_total
+ return quantize_price(line_total, currency)
def calculate_order_line_total(
self,
@@ -425,13 +416,14 @@ class PluginsManager(PaymentInterface):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- ) -> CheckoutTaxedPricesData:
- default_value = base_calculations.base_checkout_line_unit_price(
+ ) -> TaxedMoney:
+ default_value = base_calculations.calculate_base_line_unit_price(
checkout_line_info, checkout_info.channel, discounts
)
- line_unit = self.__run_method_on_plugins(
+ default_taxed_value = TaxedMoney(net=default_value, gross=default_value)
+ unit_price = self.__run_method_on_plugins(
"calculate_checkout_line_unit_price",
- default_value,
+ default_taxed_value,
checkout_info,
lines,
checkout_line_info,
@@ -440,14 +432,7 @@ class PluginsManager(PaymentInterface):
channel_slug=checkout_info.channel.slug,
)
currency = checkout_info.checkout.currency
- line_unit.price_with_sale = quantize_price(line_unit.price_with_sale, currency)
- line_unit.price_with_discounts = quantize_price(
- line_unit.price_with_discounts, currency
- )
- line_unit.undiscounted_price = quantize_price(
- line_unit.undiscounted_price, currency
- )
- return line_unit
+ return quantize_price(unit_price, currency)
def calculate_order_line_unit(
self,
@@ -532,6 +517,16 @@ class PluginsManager(PaymentInterface):
default_value = False
return self.__run_method_on_plugins("show_taxes_on_storefront", default_value)
+ def get_taxes_for_checkout(self, checkout_info, lines) -> Optional[TaxData]:
+ return self.__run_plugin_method_until_first_success(
+ "get_taxes_for_checkout", checkout_info, lines
+ )
+
+ def get_taxes_for_order(self, order: "Order") -> Optional[TaxData]:
+ return self.__run_plugin_method_until_first_success(
+ "get_taxes_for_order", order
+ )
+
def apply_taxes_to_product(
self, product: "Product", price: Money, country: Country, channel_slug: str
):
@@ -1225,7 +1220,7 @@ class PluginsManager(PaymentInterface):
channel_slug: Optional[str] = None,
active_only: bool = True,
) -> List["ShippingMethodData"]:
- channel_slug = checkout.channel.slug if checkout else channel_slug
+ channel_slug = channel_slug if channel_slug else checkout.channel.slug
plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)
shipping_plugins = [
plugin
@@ -1292,6 +1287,36 @@ class PluginsManager(PaymentInterface):
" payment method is inaccessible!"
)
+ def __run_plugin_method_until_first_success(
+ self,
+ method_name: str,
+ *args,
+ ):
+ plugins = self.get_plugins()
+ for plugin in plugins:
+ result = self.__run_method_on_single_plugin(
+ plugin, method_name, None, *args
+ )
+ if result is not None:
+ return result
+ return None
+
+ def _get_all_plugin_configs(self):
+ with opentracing.global_tracer().start_active_span("_get_all_plugin_configs"):
+ if not hasattr(self, "_plugin_configs"):
+ plugin_configurations = PluginConfiguration.objects.prefetch_related(
+ "channel"
+ ).all()
+ self._plugin_configs_per_channel = defaultdict(dict)
+ self._global_plugin_configs = {}
+ for pc in plugin_configurations:
+ channel = pc.channel
+ if channel is None:
+ self._global_plugin_configs[pc.identifier] = pc
+ else:
+ self._plugin_configs_per_channel[channel][pc.identifier] = pc
+ return self._global_plugin_configs, self._plugin_configs_per_channel
+
# FIXME these methods should be more generic
def assign_tax_code_to_object_meta(
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index bcb30c4d5e..ffdb19250d 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -4,6 +4,7 @@ from typing import (
Any,
DefaultDict,
Iterable,
+ List,
Optional,
Set,
Tuple,
@@ -19,8 +20,7 @@ from graphql.execution import ExecutionResult
from prices import Money, TaxedMoney
from ...account.models import User
-from ...checkout.interface import CheckoutTaxedPricesData
-from ...core.taxes import TaxType
+from ...core.taxes import TaxData, TaxLineData, TaxType
from ...order.interface import OrderTaxedPricesData
from ..base_plugin import BasePlugin, ConfigurationTypeField, ExternalAccessTokens
@@ -29,13 +29,37 @@ if TYPE_CHECKING:
from ...account.models import Address
from ...channel.models import Channel
from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo
- from ...checkout.models import Checkout
+ from ...checkout.models import Checkout, CheckoutLine
from ...discount import DiscountInfo
from ...discount.models import Sale
from ...order.models import Order, OrderLine
from ...product.models import Product, ProductType, ProductVariant
+def sample_tax_data(obj_with_lines: Union["Order", "Checkout"]) -> TaxData:
+
+ unit = Decimal("10.00")
+ unit_gross = Decimal("12.30")
+ lines = [
+ TaxLineData(
+ total_net_amount=unit * 3,
+ total_gross_amount=unit_gross * 3,
+ tax_rate=Decimal("23"),
+ )
+ for _ in obj_with_lines.lines.all()
+ ]
+
+ shipping = Decimal("50.00")
+ shipping_gross = Decimal("63.20")
+
+ return TaxData(
+ shipping_price_net_amount=shipping,
+ shipping_price_gross_amount=shipping_gross,
+ shipping_tax_rate=Decimal("23"),
+ lines=lines,
+ )
+
+
class PluginSample(BasePlugin):
PLUGIN_ID = "plugin.sample"
PLUGIN_NAME = "PluginSample"
@@ -107,17 +131,13 @@ class PluginSample(BasePlugin):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- previous_value: CheckoutTaxedPricesData,
+ previous_value: TaxedMoney,
):
# See if delivery method doesn't trigger infinite recursion
bool(checkout_info.delivery_method_info.delivery_method)
price = Money("1.0", currency=checkout_info.checkout.currency)
- return CheckoutTaxedPricesData(
- price_with_sale=TaxedMoney(price, price),
- price_with_discounts=TaxedMoney(price, price),
- undiscounted_price=TaxedMoney(price, price),
- )
+ return TaxedMoney(price, price)
def calculate_order_line_total(
self,
@@ -140,15 +160,11 @@ class PluginSample(BasePlugin):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- previous_value: CheckoutTaxedPricesData,
+ previous_value: TaxedMoney,
):
currency = checkout_info.checkout.currency
price = Money("10.0", currency)
- return CheckoutTaxedPricesData(
- price_with_sale=TaxedMoney(price, price),
- price_with_discounts=TaxedMoney(price, price),
- undiscounted_price=TaxedMoney(price, price),
- )
+ return TaxedMoney(price, price)
def calculate_order_line_unit(
self,
@@ -280,6 +296,16 @@ class PluginSample(BasePlugin):
def get_order_shipping_tax_rate(self, order: "Order", previous_value: Decimal):
return Decimal("0.080").quantize(Decimal(".01"))
+ def get_taxes_for_checkout(
+ self, checkout_info: "CheckoutInfo", lines, previous_value
+ ) -> Optional["TaxData"]:
+ return sample_tax_data(checkout_info.checkout)
+
+ def get_taxes_for_order(
+ self, order: "Order", previous_value
+ ) -> Optional["TaxData"]:
+ return sample_tax_data(order)
+
def sample_not_implemented(self, previous_value):
return NotImplemented
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 33ff711bf2..f7d13c5f93 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -10,7 +10,7 @@ from prices import Money, TaxedMoney
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
-from ...core.taxes import TaxType, zero_taxed_money
+from ...core.taxes import TaxType, zero_money, zero_taxed_money
from ...discount.utils import fetch_catalogue_info
from ...graphql.discount.mutations.utils import convert_catalogue_info_to_global_ids
from ...payment.interface import PaymentGateway
@@ -27,6 +27,7 @@ from ..tests.sample_plugins import (
InactivePaymentGateway,
PluginInactive,
PluginSample,
+ sample_tax_data,
)
@@ -239,16 +240,12 @@ def test_manager_calculates_checkout_line_total(
checkout_with_item, lines, [discount_info], manager
)
checkout_line_info = lines[0]
- taxed_total = (
- PluginsManager(plugins=plugins)
- .calculate_checkout_line_total(
- checkout_info,
- lines,
- checkout_line_info,
- checkout_with_item.shipping_address,
- [discount_info],
- )
- .price_with_sale
+ taxed_total = PluginsManager(plugins=plugins).calculate_checkout_line_total(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ checkout_with_item.shipping_address,
+ [discount_info],
)
assert TaxedMoney(expected_total, expected_total) == taxed_total
@@ -474,16 +471,12 @@ def test_manager_calculates_checkout_line_unit_price(
checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
checkout_line_info = lines[0]
- taxed_total = (
- PluginsManager(plugins=plugins)
- .calculate_checkout_line_unit_price(
- checkout_info,
- lines,
- checkout_line_info,
- address,
- [],
- )
- .price_with_sale
+ taxed_total = PluginsManager(plugins=plugins).calculate_checkout_line_unit_price(
+ checkout_info,
+ lines,
+ checkout_line_info,
+ address,
+ [],
)
currency = total_line_price.net.currency
expected_net = Money(
@@ -527,6 +520,10 @@ def test_manager_uses_get_tax_rate_choices(plugins, tax_rate_list):
assert tax_rate_list == PluginsManager(plugins=plugins).get_tax_rate_type_choices()
+def sample_none_data(obj):
+ return None
+
+
@pytest.mark.parametrize(
"plugins, show_taxes",
[(["saleor.plugins.tests.sample_plugins.PluginSample"], True), ([], False)],
@@ -535,6 +532,43 @@ def test_manager_show_taxes_on_storefront(plugins, show_taxes):
assert show_taxes == PluginsManager(plugins=plugins).show_taxes_on_storefront()
+ "plugins, expected_tax_data",
+ [
+ ([], sample_none_data),
+ (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
+ ],
+)
+def test_manager_get_taxes_for_checkout(
+ checkout,
+ plugins,
+ expected_tax_data,
+):
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager()
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ assert PluginsManager(plugins=plugins).get_taxes_for_checkout(
+ checkout_info, lines
+ ) == expected_tax_data(checkout)
+
+
+ "plugins, expected_tax_data",
+ [
+ ([], sample_none_data),
+ (["saleor.plugins.tests.sample_plugins.PluginSample"], sample_tax_data),
+ ],
+)
+def test_manager_get_taxes_for_order(
+ order,
+ plugins,
+ expected_tax_data,
+):
+ assert PluginsManager(plugins=plugins).get_taxes_for_order(
+ order
+ ) == expected_tax_data(order)
+
+
@pytest.mark.parametrize(
"plugins, price",
[(["saleor.plugins.tests.sample_plugins.PluginSample"], "1.0"), ([], "10.0")],
@@ -1097,7 +1131,7 @@ def test_calculate_checkout_total_zero_default_value(
# given
plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
currency = checkout_with_item.currency
- mocked_base_checkout_total.return_value = zero_taxed_money(currency)
+ mocked_base_checkout_total.return_value = zero_money(currency)
manager = PluginsManager(plugins=plugins)
lines, _ = fetch_checkout_lines(checkout_with_item)
checkout_info = fetch_checkout_info(
diff --git a/saleor/plugins/vatlayer/__init__.py b/saleor/plugins/vatlayer/__init__.py
index f8e73004a8..7cc8861b79 100644
--- a/saleor/plugins/vatlayer/__init__.py
+++ b/saleor/plugins/vatlayer/__init__.py
@@ -140,7 +140,7 @@ def apply_checkout_discount_on_checkout_line(
line_info,
checkout_info.channel,
discounts,
- ).price_with_discounts.amount
+ ).amount
* line_info.line.quantity
for line_info in lines
if line_info.line.id != checkout_line_info.line.id
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index 6a64dad711..441f764774 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -16,9 +16,8 @@ from django_prices_vatlayer.utils import (
from prices import Money, TaxedMoney, TaxedMoneyRange
from ...checkout import base_calculations, calculations
-from ...checkout.interface import CheckoutTaxedPricesData
from ...core.prices import quantize_price
-from ...core.taxes import TaxType, zero_money, zero_taxed_money
+from ...core.taxes import TaxType, zero_money
from ...discount import VoucherType
from ...order.interface import OrderTaxedPricesData
from ...order.utils import (
@@ -138,7 +137,6 @@ class VatlayerPlugin(BasePlugin):
TaxedMoney,
TaxedMoneyRange,
Decimal,
- CheckoutTaxedPricesData,
OrderTaxedPricesData,
],
) -> bool:
@@ -155,12 +153,6 @@ class VatlayerPlugin(BasePlugin):
if isinstance(previous_value, TaxedMoney):
return previous_value.net != previous_value.gross
- if isinstance(previous_value, CheckoutTaxedPricesData):
- return (
- previous_value.price_with_sale.net
- != previous_value.price_with_sale.gross
- )
-
if isinstance(previous_value, OrderTaxedPricesData):
return (
previous_value.price_with_discounts.net
@@ -181,18 +173,10 @@ class VatlayerPlugin(BasePlugin):
return previous_value
manager = get_plugins_manager()
- return calculations.checkout_subtotal(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- discounts=discounts,
- ) + calculations.checkout_shipping_price(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- discounts=discounts,
+ return manager.calculate_checkout_subtotal(
+ checkout_info, lines, address, discounts
+ ) + manager.calculate_checkout_shipping(
+ checkout_info, lines, address, discounts
)
def _get_taxes_for_country(self, country: Country):
@@ -374,9 +358,9 @@ class VatlayerPlugin(BasePlugin):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- previous_value: CheckoutTaxedPricesData,
- ) -> CheckoutTaxedPricesData:
- unit_taxed_prices_data = self.__calculate_checkout_line_unit_price(
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ unit_taxed_price = self.__calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line_info,
@@ -385,15 +369,11 @@ class VatlayerPlugin(BasePlugin):
address,
previous_value,
)
- if not unit_taxed_prices_data:
+ if unit_taxed_price is None:
return previous_value
quantity = checkout_line_info.line.quantity
- return CheckoutTaxedPricesData(
- price_with_discounts=unit_taxed_prices_data.price_with_discounts * quantity,
- price_with_sale=unit_taxed_prices_data.price_with_sale * quantity,
- undiscounted_price=unit_taxed_prices_data.undiscounted_price * quantity,
- )
+ return unit_taxed_price * quantity
def calculate_checkout_line_unit_price(
self,
@@ -402,9 +382,9 @@ class VatlayerPlugin(BasePlugin):
checkout_line_info: "CheckoutLineInfo",
address: Optional["Address"],
discounts: Iterable["DiscountInfo"],
- previous_value: CheckoutTaxedPricesData,
- ) -> CheckoutTaxedPricesData:
- unit_taxed_prices_data = self.__calculate_checkout_line_unit_price(
+ previous_value: TaxedMoney,
+ ) -> TaxedMoney:
+ unit_taxed_price = self.__calculate_checkout_line_unit_price(
checkout_info,
lines,
checkout_line_info,
@@ -413,7 +393,7 @@ class VatlayerPlugin(BasePlugin):
address,
previous_value,
)
- return unit_taxed_prices_data if unit_taxed_prices_data else previous_value
+ return unit_taxed_price if unit_taxed_price is not None else previous_value
def __calculate_checkout_line_unit_price(
self,
@@ -423,38 +403,29 @@ class VatlayerPlugin(BasePlugin):
channel: "Channel",
discounts: Iterable["DiscountInfo"],
address: Optional["Address"],
- previous_value: CheckoutTaxedPricesData,
+ previous_value: TaxedMoney,
):
if self._skip_plugin(previous_value):
return
- prices_data = base_calculations.calculate_base_line_unit_price(
+ unit_price = base_calculations.calculate_base_line_unit_price(
checkout_line_info,
channel,
discounts,
)
- prices_data.price_with_discounts = apply_checkout_discount_on_checkout_line(
+ unit_price = apply_checkout_discount_on_checkout_line(
checkout_info,
lines,
checkout_line_info,
discounts,
- prices_data.price_with_discounts,
+ unit_price,
)
country = address.country if address else None
- taxed_prices_data = CheckoutTaxedPricesData(
- price_with_sale=self.__apply_taxes_to_product(
- checkout_line_info.product, prices_data.price_with_sale, country
- ),
- undiscounted_price=self.__apply_taxes_to_product(
- checkout_line_info.product, prices_data.undiscounted_price, country
- ),
- price_with_discounts=self.__apply_taxes_to_product(
- checkout_line_info.product, prices_data.price_with_discounts, country
- ),
+ return self.__apply_taxes_to_product(
+ checkout_line_info.product, unit_price, country
)
- return taxed_prices_data
def get_checkout_line_tax_rate(
self,
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index 85a5bf90dd..f9dc3f77d7 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -368,10 +368,10 @@ def test_calculate_checkout_total_with_excluded_country(
@pytest.mark.parametrize(
"with_discount, expected_net, expected_gross, taxes_in_prices",
[
- (True, "25.00", "30.75", False),
+ (True, "20.35", "25.00", True),
(False, "40.65", "50.00", True),
+ (True, "25.00", "30.75", False),
(False, "50.00", "61.50", False),
- (True, "20.35", "25.00", True),
],
)
@override_settings(PLUGINS=["saleor.plugins.vatlayer.plugin.VatlayerPlugin"])
@@ -666,7 +666,7 @@ def test_calculate_checkout_line_total(
checkout_line_info,
address,
[],
- ).price_with_sale
+ )
assert line_price == TaxedMoney(
net=Money("8.13", "USD") * line.quantity,
@@ -713,7 +713,7 @@ def test_calculate_checkout_line_total_voucher_on_entire_order(
checkout_line_info,
address,
[],
- ).price_with_discounts
+ )
# then
currency = checkout_with_item.currency
@@ -757,7 +757,7 @@ def test_calculate_checkout_line_total_from_origin_country(
checkout_line_info,
address,
[],
- ).price_with_sale
+ )
# make sure that we applied DE taxes (19%)
assert line_price == TaxedMoney(
@@ -796,7 +796,7 @@ def test_calculate_checkout_line_total_with_excluded_country(
checkout_line_info,
address,
[],
- ).price_with_sale
+ )
assert line_price == TaxedMoney(
net=Money("10.00", "USD") * line.quantity,
@@ -968,7 +968,7 @@ def test_calculate_checkout_line_unit_price(
variant = line.variant
product = variant.product
- manager.assign_tax_code_to_object_meta(variant.product, "standard")
+ manager.assign_tax_code_to_object_meta(product, "standard")
product.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
@@ -981,7 +981,7 @@ def test_calculate_checkout_line_unit_price(
checkout_line_info,
address,
[],
- ).price_with_sale
+ )
assert line_price == TaxedMoney(
net=Money("8.13", "USD"), gross=Money("10.00", "USD")
@@ -1025,7 +1025,7 @@ def test_calculate_checkout_line_unit_price_with_voucher_one_line(
checkout_line_info,
address,
[],
- ).price_with_discounts
+ )
# then
currency = checkout_with_item.currency
@@ -1087,7 +1087,7 @@ def test_calculate_checkout_line_unit_price_with_voucher_multiple_lines(
checkout_line_info,
address,
[],
- ).price_with_discounts
+ )
# then
currency = checkout_with_item.currency
@@ -1157,7 +1157,7 @@ def test_calculate_checkout_line_unit_price_with_voucher_multiple_lines_last_lin
checkout_line_info,
address,
[],
- ).price_with_discounts
+ )
# then
discount_amount = (
@@ -1212,7 +1212,7 @@ def test_calculate_checkout_line_unit_price_with_shipping_voucher(
checkout_line_info,
address,
[],
- ).price_with_discounts
+ )
# then
assert line_price == TaxedMoney(
diff --git a/saleor/plugins/webhook/conftest.py b/saleor/plugins/webhook/conftest.py
new file mode 100644
index 0000000000..c2fdcb390d
--- /dev/null
+++ b/saleor/plugins/webhook/conftest.py
@@ -0,0 +1,76 @@
+import pytest
+
+from ...webhook.event_types import WebhookEventSyncType
+from ...webhook.models import Webhook
+from ..manager import get_plugins_manager
+
+
+def tax_line_data_response():
+ return {
+ "id": "1234",
+ "currency": "PLN",
+ "unit_net_amount": 12.34,
+ "unit_gross_amount": 12.34,
+ "total_gross_amount": 12.34,
+ "total_net_amount": 12.34,
+ "tax_rate": 23,
+ }
+
+
+def tax_data_response(tax_line_data_response):
+ return {
+ "currency": "PLN",
+ "total_net_amount": 12.34,
+ "total_gross_amount": 12.34,
+ "subtotal_net_amount": 12.34,
+ "subtotal_gross_amount": 12.34,
+ "shipping_price_gross_amount": 12.34,
+ "shipping_price_net_amount": 12.34,
+ "shipping_tax_rate": 23,
+ "lines": [tax_line_data_response] * 5,
+ }
+
+
+def tax_app(app, permission_handle_taxes, webhook):
+ app.permissions.add(permission_handle_taxes)
+ return app
+
+
+def tax_checkout_webhook(tax_app):
+ webhook = Webhook.objects.create(
+ name="Tax checkout webhook",
+ app=tax_app,
+ target_url="https://www.example.com/tax-checkout",
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+ return webhook
+
+
+def tax_order_webhook(tax_app):
+ webhook = Webhook.objects.create(
+ name="Tax order webhook",
+ app=tax_app,
+ target_url="https://www.example.com/tax-order",
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES)
+ return webhook
+
+
+def tax_app_with_webhooks(tax_app, tax_checkout_webhook, tax_order_webhook):
+ return tax_app
+
+
+def webhook_plugin(settings):
+ def factory():
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+ return manager.global_plugins[0]
+
+ return factory
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index b6254de162..12da522990 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -8,11 +8,13 @@ from ...app.models import App
from ...core import EventDeliveryStatus
from ...core.models import EventDelivery
from ...core.notify_events import NotifyEventType
+from ...core.taxes import TaxData, TaxType
from ...core.utils.json_serializer import CustomJsonEncoder
from ...payment import PaymentError, TransactionKind
from ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ...webhook.payloads import (
generate_checkout_payload,
+ generate_checkout_payload_for_tax_calculation,
generate_collection_payload,
generate_customer_payload,
generate_excluded_shipping_methods_for_checkout_payload,
@@ -22,6 +24,7 @@ from ...webhook.payloads import (
generate_list_gateways_payload,
generate_meta,
generate_order_payload,
+ generate_order_payload_for_tax_calculation,
generate_page_payload,
generate_payment_payload,
generate_product_deleted_payload,
@@ -40,14 +43,21 @@ from .const import CACHE_EXCLUDED_SHIPPING_KEY
from .shipping import get_excluded_shipping_data, parse_list_shipping_methods_response
from .tasks import (
send_webhook_request_async,
+ trigger_all_webhooks_sync,
trigger_webhook_sync,
trigger_webhooks_async,
)
from .utils import (
+ DEFAULT_TAX_CODE,
+ DEFAULT_TAX_DESCRIPTION,
delivery_update,
from_payment_app_id,
+ get_current_tax_app,
+ get_meta_code_key,
+ get_meta_description_key,
parse_list_payment_gateways_response,
parse_payment_action_response,
+ parse_tax_data,
)
if TYPE_CHECKING:
@@ -67,7 +77,13 @@ if TYPE_CHECKING:
PaymentGateway,
TransactionActionData,
)
- from ...product.models import Category, Collection, Product, ProductVariant
+ from ...product.models import (
+ Category,
+ Collection,
+ Product,
+ ProductType,
+ ProductVariant,
+ )
from ...shipping.interface import ShippingMethodData
from ...shipping.models import ShippingMethod, ShippingZone
from ...translation.models import Translation
@@ -1223,6 +1239,27 @@ class WebhookPlugin(BasePlugin):
**kwargs,
)
+ def get_taxes_for_checkout(
+ self, checkout_info, lines, previous_value
+ ) -> Optional["TaxData"]:
+ return trigger_all_webhooks_sync(
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ lambda: generate_checkout_payload_for_tax_calculation(
+ checkout_info,
+ lines,
+ ),
+ parse_tax_data,
+ )
+
+ def get_taxes_for_order(
+ self, order: "Order", previous_value
+ ) -> Optional["TaxData"]:
+ return trigger_all_webhooks_sync(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ lambda: generate_order_payload_for_tax_calculation(order),
+ parse_tax_data,
+ )
+
def get_shipping_methods_for_checkout(
self, checkout: "Checkout", previous_value: Any
) -> List["ShippingMethodData"]:
@@ -1245,6 +1282,34 @@ class WebhookPlugin(BasePlugin):
methods.extend(shipping_methods)
return methods
+ def get_tax_code_from_object_meta(
+ self, obj: Union["Product", "ProductType"], previous_value: Any
+ ):
+ """Get tax code and description for a product or product type.
+
+ If there is no active tax app, returns tax code from previous plugin.
+ If there is no tax code defined for the product/product type,
+ then return dummy values.
+ """
+ if not (tax_app := get_current_tax_app()):
+ return previous_value
+
+ meta_code_key = get_meta_code_key(tax_app)
+ meta_description_key = get_meta_description_key(tax_app)
+
+ default_tax_code = DEFAULT_TAX_CODE
+ default_tax_description = DEFAULT_TAX_DESCRIPTION
+
+ code = obj.get_value_from_metadata(meta_code_key, default_tax_code)
+ description = obj.get_value_from_metadata(
+ meta_description_key, default_tax_description
+ )
+
+ return TaxType(
+ code=code,
+ description=description,
+ )
+
def excluded_shipping_methods_for_order(
self,
order: "Order",
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 2f7eee8206..5fa2b41481 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -3,7 +3,7 @@ import logging
from dataclasses import dataclass
from enum import Enum
from json import JSONDecodeError
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar
from urllib.parse import unquote, urlparse, urlunparse
import boto3
@@ -179,6 +179,40 @@ def trigger_webhook_sync(
return send_webhook_request_sync(app.name, delivery, **kwargs)
+R = TypeVar("R")
+
+
+def trigger_all_webhooks_sync(
+ event_type: str,
+ generate_payload: Callable,
+ parse_response: Callable[[Any], Optional[R]],
+) -> Optional[R]:
+ """Send all synchronous webhook request for given event type.
+
+ Requests are send sequentially.
+ If the current webhook does not return expected response,
+ the next one is send.
+ If no webhook responds with expected response,
+ this function returns None.
+ """
+ webhooks = get_webhooks_for_event(event_type)
+ event_payload = None
+ if webhooks:
+ event_payload = EventPayload.objects.create(payload=generate_payload())
+ for webhook in webhooks:
+ delivery = EventDelivery.objects.create(
+ status=EventDeliveryStatus.PENDING,
+ event_type=event_type,
+ payload=event_payload,
+ webhook=webhook,
+ )
+ response_data = send_webhook_request_sync(webhook.app.name, delivery)
+ parsed_response = parse_response(response_data)
+ if parsed_response:
+ return parsed_response
+ return None
+
+
def send_webhook_using_http(
target_url, message, domain, signature, event_type, timeout=settings.WEBHOOK_TIMEOUT
):
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index acea4ce158..3ee56f873f 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -70,7 +70,7 @@ def test_subscription_query_with_meta(
requestor_type,
subscription_voucher_webhook_with_meta.app,
)
- assert deliveries[0].payload.payload == expected_payload
+ assert json.loads(deliveries[0].payload.payload) == json.loads(expected_payload)
assert len(deliveries) == len(webhooks)
assert deliveries[0].webhook == webhooks[0]
@@ -1190,7 +1190,7 @@ def test_fulfillment_created(fulfillment, subscription_fulfillment_created_webho
deliveries = create_deliveries_for_subscriptions(event_type, fulfillment, webhooks)
# then
- assert deliveries[0].payload.payload == json.dumps(expected_payload)
+ assert json.loads(deliveries[0].payload.payload) == expected_payload
assert len(deliveries) == len(webhooks)
assert deliveries[0].webhook == webhooks[0]
diff --git a/saleor/plugins/webhook/tests/test_shippping_exclude_cache.py b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
similarity index 99%
rename from saleor/plugins/webhook/tests/test_shippping_exclude_cache.py
rename to saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
index f434e1a83d..0a03117c55 100644
--- a/saleor/plugins/webhook/tests/test_shippping_exclude_cache.py
+++ b/saleor/plugins/webhook/tests/test_shipping_exclude_cache.py
@@ -227,12 +227,14 @@ def test_excluded_shipping_methods_for_checkout_use_cache(
ExcludedShippingMethod(id="1", reason=other_reason),
ExcludedShippingMethod(id="2", reason=other_reason),
]
+
# when
plugin.excluded_shipping_methods_for_checkout(
- checkout=checkout_with_items,
+ checkout_with_items,
available_shipping_methods=available_shipping_methods,
previous_value=previous_value,
)
+
# then
assert not mocked_webhook.called
@@ -281,12 +283,14 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_empty(
ExcludedShippingMethod(id="1", reason=other_reason),
ExcludedShippingMethod(id="2", reason=other_reason),
]
+
# when
plugin.excluded_shipping_methods_for_checkout(
- checkout=checkout_with_items,
+ checkout_with_items,
available_shipping_methods=available_shipping_methods,
previous_value=previous_value,
)
+
# then
assert mocked_webhook.called
@@ -348,7 +352,7 @@ def test_excluded_shipping_methods_for_checkout_stores_in_cache_when_payload_dif
]
# when
plugin.excluded_shipping_methods_for_checkout(
- checkout=checkout_with_items,
+ checkout_with_items,
available_shipping_methods=available_shipping_methods,
previous_value=previous_value,
)
diff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.py
index a56622ec8b..c5d2dcba0f 100644
--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py
+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py
@@ -4,6 +4,7 @@ from unittest import mock
import graphene
import pytest
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....core.models import EventDelivery
from ....graphql.tests.utils import get_graphql_content
from ....webhook.event_types import WebhookEventSyncType
@@ -12,6 +13,7 @@ from ....webhook.payloads import (
generate_excluded_shipping_methods_for_order_payload,
)
from ...base_plugin import ExcludedShippingMethod
+from ...manager import get_plugins_manager
from ..const import (
CACHE_EXCLUDED_SHIPPING_KEY,
CACHE_EXCLUDED_SHIPPING_TIME,
@@ -448,7 +450,7 @@ def test_excluded_shipping_methods_for_checkout(
]
# when
excluded_methods = plugin.excluded_shipping_methods_for_checkout(
- checkout=checkout_with_items,
+ checkout_with_items,
available_shipping_methods=available_shipping_methods,
previous_value=previous_value,
)
@@ -527,7 +529,7 @@ def test_multiple_app_with_excluded_shipping_methods_for_checkout(
# when
excluded_methods = plugin.excluded_shipping_methods_for_checkout(
- checkout=checkout_with_items,
+ checkout_with_items,
available_shipping_methods=available_shipping_methods,
previous_value=previous_value,
)
@@ -601,10 +603,14 @@ def test_generate_excluded_shipping_methods_for_checkout_payload(
):
# given
methods = available_shipping_methods_factory(num_methods=3)
+ lines, _ = fetch_checkout_lines(checkout_with_items)
+ manager = get_plugins_manager()
+ checkout_info = fetch_checkout_info(checkout_with_items, lines, [], manager)
+
# when
json_payload = json.loads(
generate_excluded_shipping_methods_for_checkout_payload(
- checkout=checkout_with_items, available_shipping_methods=methods
+ checkout_info, available_shipping_methods=methods
)
)
# then
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
new file mode 100644
index 0000000000..3669495e33
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -0,0 +1,143 @@
+from unittest import mock
+from unittest.mock import sentinel
+
+import pytest
+from freezegun import freeze_time
+
+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....core.taxes import TaxType
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.payloads import generate_order_payload_for_tax_calculation
+from ..utils import DEFAULT_TAX_CODE, DEFAULT_TAX_DESCRIPTION, parse_tax_data
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_taxes_for_checkout_no_permission(
+ mock_request,
+ webhook_plugin,
+ checkout,
+):
+ # given
+ plugin = webhook_plugin()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], plugin)
+
+ # when
+ tax_data = plugin.get_taxes_for_checkout(checkout_info, lines, None)
+
+ # then
+ assert mock_request.call_count == 0
+ assert tax_data is None
+
+
+@freeze_time()
[email protected]("saleor.order.calculations.fetch_order_prices_if_expired")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_taxes_for_order(
+ mock_request,
+ mock_fetch,
+ permission_handle_taxes,
+ webhook_plugin,
+ tax_order_webhook,
+ tax_data_response,
+ order,
+ tax_app_with_webhooks,
+):
+ # given
+ mock_request.return_value = tax_data_response
+ plugin = webhook_plugin()
+
+ # when
+ tax_data = plugin.get_taxes_for_order(order, None)
+
+ # then
+ payload = EventPayload.objects.get()
+ assert payload.payload == generate_order_payload_for_tax_calculation(order)
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.payload == payload
+ assert delivery.webhook == tax_order_webhook
+ mock_request.assert_called_once_with(tax_order_webhook.app.name, delivery)
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(tax_data_response)
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_taxes_for_order_no_permission(
+ mock_request,
+ webhook_plugin,
+ order,
+):
+ # given
+ plugin = webhook_plugin()
+
+ # when
+ tax_data = plugin.get_taxes_for_order(order, None)
+
+ # then
+ assert mock_request.call_count == 0
+ assert tax_data is None
+
+
+def tax_type():
+ return TaxType(
+ code="code_2",
+ description="description_2",
+ )
+
+
+def test_get_tax_code_from_object_meta_no_app(
+ webhook_plugin,
+ product,
+):
+ # given
+ plugin = webhook_plugin()
+ previous_value = sentinel.PREVIOUS_VALUE
+
+ # when
+ fetched_tax_type = plugin.get_tax_code_from_object_meta(product, previous_value)
+
+ # then
+ assert fetched_tax_type == previous_value
+
+
+def test_get_tax_code_from_object_meta(
+ webhook_plugin,
+ tax_app_with_webhooks,
+ tax_type,
+ product,
+):
+ # given
+ plugin = webhook_plugin()
+ product.metadata = {
+ f"{tax_app_with_webhooks.identifier}.code": tax_type.code,
+ f"{tax_app_with_webhooks.identifier}.description": tax_type.description,
+ }
+
+ # when
+ fetched_tax_type = plugin.get_tax_code_from_object_meta(product, None)
+
+ # then
+ assert fetched_tax_type == tax_type
+
+
+def test_get_tax_code_from_object_meta_default_code(
+ webhook_plugin,
+ tax_app_with_webhooks,
+ product,
+):
+ # given
+ plugin = webhook_plugin()
+
+ # when
+ fetched_tax_type = plugin.get_tax_code_from_object_meta(product, None)
+
+ # then
+ assert fetched_tax_type == TaxType(
+ code=DEFAULT_TAX_CODE,
+ description=DEFAULT_TAX_DESCRIPTION,
+ )
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py b/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py
new file mode 100644
index 0000000000..7603c56ac9
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_tax_webhook_tasks.py
@@ -0,0 +1,141 @@
+from unittest import mock
+
+import pytest
+
+from ....core import EventDeliveryStatus
+from ....core.models import EventDelivery, EventPayload
+from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook, WebhookEvent
+from ..tasks import trigger_all_webhooks_sync
+from ..utils import parse_tax_data
+
+
+def tax_checkout_webhooks(tax_app):
+ webhooks = [
+ Webhook(
+ name=f"Tax checkout webhook no {i}",
+ app=tax_app,
+ target_url=f"https://www.example.com/tax-checkout-{i}",
+ )
+ for i in range(3)
+ ]
+ Webhook.objects.bulk_create(webhooks)
+ WebhookEvent.objects.bulk_create(
+ WebhookEvent(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ webhook=webhook,
+ )
+ for webhook in webhooks
+ )
+
+ return list(
+ Webhook.objects.filter(
+ events__event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ )
+ )
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_trigger_tax_webhook_sync(
+ mock_request,
+ tax_checkout_webhook,
+ tax_data_response,
+):
+ # given
+ mock_request.return_value = tax_data_response
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ # when
+ tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+
+ # then
+ payload = EventPayload.objects.get()
+ assert payload.payload == data
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.payload == payload
+ assert delivery.webhook == tax_checkout_webhook
+ mock_request.assert_called_once_with(tax_checkout_webhook.app.name, delivery)
+ assert tax_data == parse_tax_data(tax_data_response)
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_trigger_tax_webhook_sync_multiple_webhooks_first(
+ mock_request,
+ tax_checkout_webhooks,
+ tax_data_response,
+):
+ # given
+ mock_request.side_effect = [tax_data_response, {}, {}]
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ # when
+ tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+
+ # then
+ successful_webhook = tax_checkout_webhooks[0]
+
+ payload = EventPayload.objects.get()
+ assert payload.payload == data
+ delivery = EventDelivery.objects.order_by("pk").first()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.payload == payload
+ assert delivery.webhook == successful_webhook
+ mock_request.assert_called_once_with(successful_webhook.app.name, delivery)
+ assert tax_data == parse_tax_data(tax_data_response)
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_trigger_tax_webhook_sync_multiple_webhooks_last(
+ mock_request,
+ tax_checkout_webhooks,
+ tax_data_response,
+):
+ # given
+ mock_request.side_effect = [{}, {}, tax_data_response]
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ # when
+ tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+
+ # then
+
+ payload = EventPayload.objects.get()
+ assert payload.payload == data
+ deliveries = list(EventDelivery.objects.order_by("pk"))
+ for call, delivery, webhook in zip(
+ mock_request.call_args_list, deliveries, tax_checkout_webhooks
+ ):
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == event_type
+ assert delivery.payload == payload
+ assert delivery.webhook == webhook
+ assert call[0] == (webhook.app.name, delivery)
+
+ assert mock_request.call_count == 3
+ assert tax_data == parse_tax_data(tax_data_response)
+
+
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_trigger_tax_webhook_sync_invalid_webhooks(
+ mock_request,
+ tax_checkout_webhooks,
+ tax_data_response,
+):
+ # given
+ mock_request.return_value = {}
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ data = '{"key": "value"}'
+
+ # when
+ tax_data = trigger_all_webhooks_sync(event_type, lambda: data, parse_tax_data)
+
+ # then
+ assert mock_request.call_count == len(tax_checkout_webhooks)
+ assert tax_data is None
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook_utils.py b/saleor/plugins/webhook/tests/test_tax_webhook_utils.py
new file mode 100644
index 0000000000..49a324872d
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_tax_webhook_utils.py
@@ -0,0 +1,129 @@
+import decimal
+
+import pytest
+
+from ....core.taxes import TaxData
+from ..utils import _unsafe_parse_tax_data, _unsafe_parse_tax_line_data, parse_tax_data
+
+
+def test_unsafe_parse_tax_line_data_success(tax_line_data_response):
+ # when
+ tax_line_data = _unsafe_parse_tax_line_data(tax_line_data_response)
+
+ # then
+ assert not tax_line_data.total_gross_amount.compare(
+ decimal.Decimal(tax_line_data_response["total_gross_amount"])
+ )
+ assert not tax_line_data.total_net_amount.compare(
+ decimal.Decimal(tax_line_data_response["total_net_amount"])
+ )
+ assert tax_line_data.tax_rate == tax_line_data_response["tax_rate"]
+
+
+def test_unsafe_parse_tax_line_data_keyerror(tax_line_data_response):
+ # given
+ tax_line_data_response["total_net_amount_v2"] = tax_line_data_response[
+ "total_net_amount"
+ ]
+ del tax_line_data_response["total_net_amount"]
+
+ # when
+ with pytest.raises(KeyError):
+ _unsafe_parse_tax_line_data(tax_line_data_response)
+
+
+def test_unsafe_parse_tax_line_data_decimalexception(tax_line_data_response):
+ # given
+ tax_line_data_response["total_net_amount"] = "invalid value"
+
+ # when
+ with pytest.raises(decimal.DecimalException):
+ _unsafe_parse_tax_line_data(tax_line_data_response)
+
+
+def test_unsafe_parse_tax_data_success(tax_data_response):
+ # when
+ tax_data = _unsafe_parse_tax_data(tax_data_response)
+
+ # then
+ assert not tax_data.shipping_price_gross_amount.compare(
+ decimal.Decimal(tax_data_response["shipping_price_gross_amount"])
+ )
+ assert not tax_data.shipping_price_net_amount.compare(
+ decimal.Decimal(tax_data_response["shipping_price_net_amount"])
+ )
+ assert tax_data.shipping_tax_rate == tax_data_response["shipping_tax_rate"]
+ assert tax_data.lines == [
+ _unsafe_parse_tax_line_data(line) for line in tax_data_response["lines"]
+ ]
+
+
+def test_unsafe_parse_tax_data_keyerror(tax_data_response):
+ # given
+ tax_data_response["shipping_tax_rate_2"] = tax_data_response["shipping_tax_rate"]
+ del tax_data_response["shipping_tax_rate"]
+
+ # when
+ with pytest.raises(KeyError):
+ _unsafe_parse_tax_data(tax_data_response)
+
+
+def test_unsafe_parse_tax_data_decimalexception(tax_data_response):
+ # given
+ tax_data_response["shipping_price_gross_amount"] = "invalid value"
+
+ # when
+ with pytest.raises(decimal.DecimalException):
+ _unsafe_parse_tax_data(tax_data_response)
+
+
+def test_parse_tax_data_success(tax_data_response):
+ # when
+ tax_data = parse_tax_data(tax_data_response)
+
+ # then
+ assert isinstance(tax_data, TaxData)
+
+
+def test_parse_tax_data_keyerror(tax_data_response):
+ # given
+ tax_data_response["shipping_tax_rate_2"] = tax_data_response["shipping_tax_rate"]
+ del tax_data_response["shipping_tax_rate"]
+
+ # when
+ tax_data = parse_tax_data(tax_data_response)
+
+ # then
+ assert tax_data is None
+
+
+def test_parse_tax_data_decimalexception(tax_data_response):
+ # given
+ tax_data_response["shipping_price_gross_amount"] = "invalid value"
+
+ # when
+ tax_data = parse_tax_data(tax_data_response)
+
+ # then
+ assert tax_data is None
+
+
+ "response_data",
+ [
+ [],
+ 1.0,
+ "text",
+ None,
+ {"lines": {}},
+ {"lines": 1.0},
+ {"lines": "text"},
+ {"lines": None},
+ {"lines": [[]]},
+ {"lines": [1.0]},
+ {"lines": ["text"]},
+ {"lines": [None]},
+ ],
+)
+def test_parse_tax_data_malformed(response_data):
+ assert parse_tax_data(response_data) is None
diff --git a/saleor/plugins/webhook/tests/test_webhook_tasks.py b/saleor/plugins/webhook/tests/test_webhook_tasks.py
new file mode 100644
index 0000000000..c99b403fb6
--- /dev/null
+++ b/saleor/plugins/webhook/tests/test_webhook_tasks.py
@@ -0,0 +1,35 @@
+import pytest
+
+from ....app.models import App
+from ....webhook.event_types import WebhookEventAsyncType
+from ....webhook.models import Webhook, WebhookEvent
+from ....webhook.utils import get_webhooks_for_event
+
+
+def webhooks_factory():
+ def factory(apps, event_type):
+ webhooks = [Webhook(name=f"Webhook {i}", app=app) for i, app in enumerate(apps)]
+ Webhook.objects.bulk_create(webhooks)
+ WebhookEvent.objects.bulk_create(
+ WebhookEvent(event_type=event_type, webhook=webhook) for webhook in webhooks
+ )
+
+ return factory
+
+
+def test_get_webhooks_for_event_webhook_ordering(webhooks_factory):
+ # given
+ apps = [App(name=f"App {i}", is_active=True) for i in range(3)]
+ App.objects.bulk_create(apps)
+ event_type = WebhookEventAsyncType.PRODUCT_CREATED
+ webhooks_factory([apps[1], apps[1], apps[2], apps[0]], event_type)
+
+ # when
+ webhooks = list(get_webhooks_for_event(event_type))
+
+ # then
+ for prev_webhook, next_webhook in zip(webhooks, webhooks[1:]):
+ assert prev_webhook.app_id <= next_webhook.app_id
+ if prev_webhook.app_id == next_webhook.app_id:
+ assert prev_webhook.pk < next_webhook.pk
diff --git a/saleor/plugins/webhook/utils.py b/saleor/plugins/webhook/utils.py
index fd7127ae07..08f912b80e 100644
--- a/saleor/plugins/webhook/utils.py
+++ b/saleor/plugins/webhook/utils.py
@@ -8,19 +8,22 @@ from typing import TYPE_CHECKING, Any, List, Optional
from django.db.models import QuerySet
+from ...app.models import App
from ...core.models import (
EventDelivery,
EventDeliveryAttempt,
EventDeliveryStatus,
EventPayload,
)
+from ...core.taxes import TaxData, TaxLineData
from ...payment.interface import GatewayResponse, PaymentGateway, PaymentMethodInfo
+from ...webhook.event_types import WebhookEventSyncType
if TYPE_CHECKING:
- from ...app.models import App
from ...payment.interface import PaymentData
from .tasks import WebhookResponse
+APP_GATEWAY_ID_PREFIX = "app"
APP_ID_PREFIX = "app"
@@ -39,7 +42,7 @@ class ShippingAppData:
shipping_method_id: str
-def to_payment_app_id(app: "App", gateway_id: str) -> "str":
+def to_payment_app_id(app: App, gateway_id: str) -> "str":
return f"{APP_ID_PREFIX}:{app.pk}:{gateway_id}"
@@ -56,7 +59,7 @@ def from_payment_app_id(app_gateway_id: str) -> Optional["PaymentAppData"]:
def parse_list_payment_gateways_response(
- response_data: Any, app: "App"
+ response_data: Any, app: App
) -> List["PaymentGateway"]:
gateways: List[PaymentGateway] = []
if not isinstance(response_data, list):
@@ -126,6 +129,57 @@ def parse_payment_action_response(
)
+def _unsafe_parse_tax_line_data(
+ tax_line_data_response: Any,
+) -> TaxLineData:
+ """Unsafe TaxLineData parser.
+
+ Raises KeyError or DecimalException on invalid data.
+ """
+ total_gross_amount = decimal.Decimal(tax_line_data_response["total_gross_amount"])
+ total_net_amount = decimal.Decimal(tax_line_data_response["total_net_amount"])
+ tax_rate = decimal.Decimal(tax_line_data_response["tax_rate"])
+
+ return TaxLineData(
+ total_gross_amount=total_gross_amount,
+ total_net_amount=total_net_amount,
+ tax_rate=tax_rate,
+ )
+
+
+def _unsafe_parse_tax_data(
+ tax_data_response: Any,
+) -> TaxData:
+ """Unsafe TaxData parser.
+
+ Raises KeyError or DecimalException on invalid data.
+ """
+ shipping_price_gross_amount = decimal.Decimal(
+ tax_data_response["shipping_price_gross_amount"]
+ )
+ shipping_price_net_amount = decimal.Decimal(
+ tax_data_response["shipping_price_net_amount"]
+ )
+ shipping_tax_rate = decimal.Decimal(tax_data_response["shipping_tax_rate"])
+ lines = [_unsafe_parse_tax_line_data(line) for line in tax_data_response["lines"]]
+
+ return TaxData(
+ shipping_price_gross_amount=shipping_price_gross_amount,
+ shipping_price_net_amount=shipping_price_net_amount,
+ shipping_tax_rate=shipping_tax_rate,
+ lines=lines,
+ )
+
+
+def parse_tax_data(
+ response_data: Any,
+) -> Optional[TaxData]:
+ try:
+ return _unsafe_parse_tax_data(response_data)
+ except (TypeError, KeyError, decimal.DecimalException):
+ return None
+
+
@contextmanager
def catch_duration_time():
start = time()
@@ -201,3 +255,25 @@ def clear_successful_delivery(delivery: "EventDelivery"):
delivery.delete()
if payload_id:
EventPayload.objects.filter(pk=payload_id, deliveries__isnull=True).delete()
+
+
+DEFAULT_TAX_CODE = "UNMAPPED"
+DEFAULT_TAX_DESCRIPTION = "Unmapped Product/Product Type"
+
+
+def get_current_tax_app() -> Optional[App]:
+ """Return currently used tax app or None, if there aren't any."""
+ return (
+ App.objects.order_by("pk")
+ .for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+ .for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
+ .last()
+ )
+
+
+def get_meta_code_key(app: App) -> str:
+ return f"{app.identifier}.code"
+
+
+def get_meta_description_key(app: App) -> str:
+ return f"{app.identifier}.description"
diff --git a/saleor/settings.py b/saleor/settings.py
index a7edae9bcb..f6d4556c18 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -722,6 +722,10 @@ JWT_TTL_REQUEST_EMAIL_CHANGE = timedelta(
seconds=parse(os.environ.get("JWT_TTL_REQUEST_EMAIL_CHANGE", "1 hour")),
)
+CHECKOUT_PRICES_TTL = timedelta(
+ seconds=parse(os.environ.get("CHECKOUT_PRICES_TTL", "1 hour"))
+)
+
# Patch SubscriberExecutionContext class from `graphql-core-legacy` package
# to fix bug causing not returning errors for subscription queries.
diff --git a/saleor/shipping/tasks.py b/saleor/shipping/tasks.py
index ad5f42d01a..b534a524f9 100644
--- a/saleor/shipping/tasks.py
+++ b/saleor/shipping/tasks.py
@@ -1,8 +1,10 @@
from typing import Iterable, Union
+from django.utils import timezone
+
from ..celeryconf import app
from ..checkout.models import Checkout
-from ..graphql.order.mutations.utils import ORDER_EDITABLE_STATUS
+from ..order import ORDER_EDITABLE_STATUS
from ..order.models import Order
@@ -15,9 +17,13 @@ def drop_invalid_shipping_methods_relations_for_given_channels(
# when method is no longer available in given channels
Checkout.objects.filter(
shipping_method_id__in=shipping_method_ids, channel_id__in=channel_ids
- ).update(shipping_method=None)
+ ).update(
+ shipping_method=None,
+ price_expiration=timezone.now(),
+ last_change=timezone.now(),
+ )
Order.objects.filter(
status__in=ORDER_EDITABLE_STATUS,
shipping_method_id__in=shipping_method_ids,
channel_id__in=channel_ids,
- ).update(shipping_method=None)
+ ).update(shipping_method=None, should_refresh_prices=True)
diff --git a/saleor/shipping/tests/test_tasks.py b/saleor/shipping/tests/test_tasks.py
index 9ce2c967bf..6bd944b201 100644
--- a/saleor/shipping/tests/test_tasks.py
+++ b/saleor/shipping/tests/test_tasks.py
@@ -1,9 +1,15 @@
+from datetime import timedelta
+
+from django.utils import timezone
+from freezegun import freeze_time
+
from ...checkout.models import Checkout
from ...order import OrderStatus
from ...order.models import Order
from ..tasks import drop_invalid_shipping_methods_relations_for_given_channels
+@freeze_time()
def test_drop_invalid_shipping_method_relations(
checkouts_list,
order_list,
@@ -14,22 +20,27 @@ def test_drop_invalid_shipping_method_relations(
channel_PLN,
):
# given
- # given
+ valid_time = timezone.now() + timedelta(hours=24)
+
checkout_PLN = checkouts_list[0]
checkout_PLN.shipping_method = shipping_method
checkout_PLN.channel = channel_PLN
+ checkout_PLN.price_expiration = valid_time
checkout_USD = checkouts_list[1]
checkout_USD.shipping_method = shipping_method
checkout_USD.channel = channel_USD
+ checkout_USD.price_expiration = valid_time
checkout_weight_shipping_method = checkouts_list[2]
checkout_weight_shipping_method.shipping_method = shipping_method_weight_based
checkout_weight_shipping_method.channel = channel_USD
+ checkout_weight_shipping_method.price_expiration = valid_time
checkout_another_shipping_method = checkouts_list[3]
checkout_another_shipping_method.shipping_method = other_shipping_method
checkout_another_shipping_method.channel = channel_USD
+ checkout_another_shipping_method.price_expiration = valid_time
Checkout.objects.bulk_update(
[
@@ -38,27 +49,30 @@ def test_drop_invalid_shipping_method_relations(
checkout_weight_shipping_method,
checkout_another_shipping_method,
],
- ["shipping_method", "channel"],
+ ["shipping_method", "channel", "price_expiration"],
)
order_confirmed = order_list[0]
order_confirmed.status = OrderStatus.UNFULFILLED
order_confirmed.shipping_method = shipping_method
order_confirmed.channel = channel_USD
+ order_confirmed.should_refresh_prices = False
order_draft = order_list[1]
order_draft.status = OrderStatus.DRAFT
order_draft.shipping_method = shipping_method
order_draft.channel = channel_USD
+ order_draft.should_refresh_prices = False
order_draft_PLN = order_list[2]
order_draft_PLN.status = OrderStatus.DRAFT
order_draft_PLN.shipping_method = shipping_method
order_draft_PLN.channel = channel_PLN
+ order_draft_PLN.should_refresh_prices = False
Order.objects.bulk_update(
[order_confirmed, order_draft, order_draft_PLN],
- ["status", "shipping_method", "channel"],
+ ["status", "shipping_method", "channel", "should_refresh_prices"],
)
# when
@@ -78,6 +92,11 @@ def test_drop_invalid_shipping_method_relations(
)
assert checkout_another_shipping_method.shipping_method is None
+ assert checkout_PLN.price_expiration == valid_time
+ assert checkout_USD.price_expiration == timezone.now()
+ assert checkout_weight_shipping_method.price_expiration == valid_time
+ assert checkout_another_shipping_method.price_expiration == timezone.now()
+
order_confirmed.refresh_from_db()
order_draft.refresh_from_db()
order_draft_PLN.refresh_from_db()
@@ -85,3 +104,7 @@ def test_drop_invalid_shipping_method_relations(
assert order_confirmed.shipping_method == shipping_method
assert order_draft.shipping_method is None
assert order_draft_PLN.shipping_method == shipping_method
+
+ assert not order_confirmed.should_refresh_prices
+ assert order_draft.should_refresh_prices
+ assert not order_draft_PLN.should_refresh_prices
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index eb5db90697..a9ad4f03dc 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -44,12 +44,14 @@ from ..checkout.utils import add_variant_to_checkout, add_voucher_to_checkout
from ..core import EventDeliveryStatus, JobStatus
from ..core.models import EventDelivery, EventDeliveryAttempt, EventPayload
from ..core.payments import PaymentInterface
+from ..core.taxes import zero_money
from ..core.units import MeasurementUnits
from ..core.utils.editorjs import clean_editor_js
from ..csv.events import ExportEvents
from ..csv.models import ExportEvent, ExportFile
from ..discount import DiscountInfo, DiscountValueType, VoucherType
from ..discount.models import (
+ NotApplicable,
Sale,
SaleChannelListing,
SaleTranslation,
@@ -77,7 +79,10 @@ from ..order.models import (
OrderLine,
)
from ..order.search import prepare_order_search_vector_value
-from ..order.utils import recalculate_order
+from ..order.utils import (
+ get_voucher_discount_assigned_to_order,
+ get_voucher_discount_for_order,
+)
from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
from ..payment.interface import AddressData, GatewayConfig, GatewayResponse, PaymentData
@@ -287,9 +292,12 @@ def site_settings_with_reservations(site_settings):
@pytest.fixture
-def checkout(db, channel_USD):
+def checkout(db, channel_USD, settings):
checkout = Checkout.objects.create(
- currency=channel_USD.currency_code, channel=channel_USD, email="[email protected]"
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ price_expiration=timezone.now() + settings.CHECKOUT_PRICES_TTL,
)
checkout.set_country("US", commit=True)
return checkout
@@ -412,11 +420,13 @@ def checkout_ready_to_complete(checkout_with_item, address, shipping_method, gif
@pytest.fixture
-def checkout_with_digital_item(checkout, digital_content):
+def checkout_with_digital_item(checkout, digital_content, address):
"""Create a checkout with a digital line."""
variant = digital_content.product_variant
checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
add_variant_to_checkout(checkout_info, variant, 1)
+ checkout.discount_amount = Decimal(0)
+ checkout.billing_address = address
checkout.email = "[email protected]"
checkout.save()
return checkout
@@ -490,6 +500,80 @@ def checkout_with_variant_without_inventory_tracking(
return checkout
+def checkout_with_variants(
+ checkout,
+ stock,
+ product_with_default_variant,
+ product_with_single_variant,
+ product_with_two_variants,
+):
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+
+ add_variant_to_checkout(
+ checkout_info, product_with_default_variant.variants.get(), 1
+ )
+ add_variant_to_checkout(
+ checkout_info, product_with_single_variant.variants.get(), 10
+ )
+ add_variant_to_checkout(
+ checkout_info, product_with_two_variants.variants.first(), 3
+ )
+ add_variant_to_checkout(checkout_info, product_with_two_variants.variants.last(), 5)
+
+ checkout.save()
+ return checkout
+
+
+def checkout_with_shipping_address(checkout_with_variants, address):
+ checkout = checkout_with_variants
+
+ checkout.shipping_address = address.get_copy()
+ checkout.save()
+
+ return checkout
+
+
+def checkout_with_variants_for_cc(
+ checkout, stocks_for_cc, product_variant_list, product_with_two_variants
+):
+ CheckoutLine.objects.bulk_create(
+ [
+ CheckoutLine(
+ checkout=checkout,
+ variant=product_variant_list[0],
+ quantity=3,
+ currency="USD",
+ ),
+ CheckoutLine(
+ checkout=checkout,
+ variant=product_variant_list[1],
+ quantity=10,
+ currency="USD",
+ ),
+ CheckoutLine(
+ checkout=checkout,
+ variant=product_with_two_variants.variants.last(),
+ quantity=5,
+ currency="USD",
+ ),
+ ]
+ )
+ return checkout
+
+
+def checkout_with_shipping_address_for_cc(checkout_with_variants_for_cc, address):
+ checkout = checkout_with_variants_for_cc
+
+ checkout.shipping_address = address.get_copy()
+ checkout.save()
+
+ return checkout
+
+
@pytest.fixture
def checkout_with_items(checkout, product_list, product):
variant = product.variants.get()
@@ -498,6 +582,7 @@ def checkout_with_items(checkout, product_list, product):
for prod in product_list:
variant = prod.variants.get()
add_variant_to_checkout(checkout_info, variant, 1)
+ checkout.save()
checkout.refresh_from_db()
return checkout
@@ -810,6 +895,7 @@ def order(customer_user, channel_USD):
user_email=customer_user.email,
user=customer_user,
origin=OrderOrigin.CHECKOUT,
+ should_refresh_prices=False,
metadata={"key": "value"},
private_metadata={"secret_key": "secret_value"},
)
@@ -1828,6 +1914,11 @@ def permission_manage_apps():
return Permission.objects.get(codename="manage_apps")
+def permission_handle_taxes():
+ return Permission.objects.get(codename="handle_taxes")
+
+
@pytest.fixture
def permission_manage_observability():
return Permission.objects.get(codename="manage_observability")
@@ -3609,6 +3700,33 @@ def gift_card_event(gift_card, order, app, staff_user):
)
+def recalculate_order(order):
+ lines = OrderLine.objects.filter(order_id=order.pk)
+ prices = [line.total_price for line in lines]
+ total = sum(prices, order.shipping_price)
+ undiscounted_total = TaxedMoney(total.net, total.gross)
+
+ try:
+ discount = get_voucher_discount_for_order(order)
+ except NotApplicable:
+ discount = zero_money(order.currency)
+
+ discount = min(discount, total.gross)
+ total -= discount
+
+ order.total = total
+ order.undiscounted_total = undiscounted_total
+
+ if discount:
+ assigned_order_discount = get_voucher_discount_assigned_to_order(order)
+ if assigned_order_discount:
+ assigned_order_discount.amount_value = discount.amount
+ assigned_order_discount.value = discount.amount
+ assigned_order_discount.save(update_fields=["value", "amount_value"])
+
+ order.save()
+
+
@pytest.fixture
def order_with_lines(
order, product_type, category, shipping_zone, warehouse, channel_USD
@@ -3689,10 +3807,10 @@ def order_with_lines(
)
stock.refresh_from_db()
- net = variant.get_price(product, [], channel_USD, channel_listing)
- currency = net.currency
- gross = Money(amount=net.amount * Decimal(1.23), currency=currency)
- unit_price = TaxedMoney(net=net, gross=gross)
+ base_price = variant.get_price(product, [], channel_USD, channel_listing)
+ currency = base_price.currency
+ gross = Money(amount=base_price.amount * Decimal(1.23), currency=currency)
+ unit_price = TaxedMoney(net=base_price, gross=gross)
quantity = 2
line = order.lines.create(
product_name=str(variant.product),
@@ -3707,8 +3825,8 @@ def order_with_lines(
total_price=unit_price * quantity,
undiscounted_unit_price=unit_price,
undiscounted_total_price=unit_price * quantity,
- base_unit_price=unit_price.gross,
- undiscounted_base_unit_price=unit_price.gross,
+ base_unit_price=base_price,
+ undiscounted_base_unit_price=base_price,
tax_rate=Decimal("0.23"),
)
Allocation.objects.create(
@@ -4241,7 +4359,6 @@ def draft_order(order_with_lines, shipping_method):
def draft_order_with_fixed_discount_order(draft_order):
value = Decimal("20")
discount = partial(fixed_discount, discount=Money(value, draft_order.currency))
- draft_order.undiscounted_total = draft_order.total
draft_order.total = discount(draft_order.total)
draft_order.discounts.create(
value_type=DiscountValueType.FIXED,
@@ -5247,7 +5364,10 @@ def other_description_json():
@pytest.fixture
def app(db):
- app = App.objects.create(name="Sample app objects", is_active=True)
+ app = App.objects.create(
+ name="Sample app objects",
+ is_active=True,
+ )
return app
@@ -5260,6 +5380,7 @@ def webhook_app(
permission_manage_menus,
permission_manage_products,
permission_manage_staff,
+ permission_manage_orders,
):
app = App.objects.create(name="Webhook app", is_active=True)
app.permissions.add(permission_manage_shipping)
@@ -5268,6 +5389,7 @@ def webhook_app(
app.permissions.add(permission_manage_menus)
app.permissions.add(permission_manage_products)
app.permissions.add(permission_manage_staff)
+ app.permissions.add(permission_manage_orders)
return app
@@ -5344,6 +5466,28 @@ def shipping_app(db, permission_manage_shipping):
return app
+def tax_app(db, permission_handle_taxes):
+ app = App.objects.create(name="Tax App", is_active=True)
+ app.permissions.add(permission_handle_taxes)
+
+ webhook = Webhook.objects.create(
+ name="tax-webhook-1",
+ app=app,
+ target_url="https://tax-app.com/api/",
+ )
+ webhook.events.bulk_create(
+ [
+ WebhookEvent(event_type=event_type, webhook=webhook)
+ for event_type in [
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ ]
+ ]
+ )
+ return app
+
+
@pytest.fixture
def observability_webhook(db, permission_manage_observability):
app = App.objects.create(name="Observability App", is_active=True)
@@ -5614,13 +5758,22 @@ def checkout_with_items_for_cc(checkout_for_cc, product_variant_list):
CheckoutLine.objects.bulk_create(
[
CheckoutLine(
- checkout=checkout_for_cc, variant=product_variant_list[0], quantity=1
+ checkout=checkout_for_cc,
+ variant=product_variant_list[0],
+ quantity=1,
+ currency=checkout_for_cc.currency,
),
CheckoutLine(
- checkout=checkout_for_cc, variant=product_variant_list[1], quantity=1
+ checkout=checkout_for_cc,
+ variant=product_variant_list[1],
+ quantity=1,
+ currency=checkout_for_cc.currency,
),
CheckoutLine(
- checkout=checkout_for_cc, variant=product_variant_list[2], quantity=1
+ checkout=checkout_for_cc,
+ variant=product_variant_list[2],
+ quantity=1,
+ currency=checkout_for_cc.currency,
),
]
)
@@ -5632,7 +5785,10 @@ def checkout_with_items_for_cc(checkout_for_cc, product_variant_list):
@pytest.fixture
def checkout_with_item_for_cc(checkout_for_cc, product_variant_list):
CheckoutLine.objects.create(
- checkout=checkout_for_cc, variant=product_variant_list[0], quantity=1
+ checkout=checkout_for_cc,
+ variant=product_variant_list[0],
+ quantity=1,
+ currency=checkout_for_cc.currency,
)
return checkout_for_cc
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index e7a4fd5eee..1645b28da2 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -432,6 +432,9 @@ class WebhookEventSyncType:
PAYMENT_CONFIRM = "payment_confirm"
PAYMENT_PROCESS = "payment_process"
+ CHECKOUT_CALCULATE_TAXES = "checkout_calculate_taxes"
+ ORDER_CALCULATE_TAXES = "order_calculate_taxes"
+
SHIPPING_LIST_METHODS_FOR_CHECKOUT = "shipping_list_methods_for_checkout"
CHECKOUT_FILTER_SHIPPING_METHODS = "checkout_filter_shipping_methods"
ORDER_FILTER_SHIPPING_METHODS = "order_filter_shipping_methods"
@@ -444,6 +447,8 @@ class WebhookEventSyncType:
PAYMENT_PROCESS: "Process payment",
PAYMENT_REFUND: "Refund payment",
PAYMENT_VOID: "Void payment",
+ CHECKOUT_CALCULATE_TAXES: "Checkout calculate taxes",
+ ORDER_CALCULATE_TAXES: "Order calculate taxes",
SHIPPING_LIST_METHODS_FOR_CHECKOUT: "Shipping list methods for checkout",
ORDER_FILTER_SHIPPING_METHODS: "Filter order shipping methods",
CHECKOUT_FILTER_SHIPPING_METHODS: "Filter checkout shipping methods",
@@ -457,6 +462,8 @@ class WebhookEventSyncType:
(PAYMENT_PROCESS, DISPLAY_LABELS[PAYMENT_PROCESS]),
(PAYMENT_REFUND, DISPLAY_LABELS[PAYMENT_REFUND]),
(PAYMENT_VOID, DISPLAY_LABELS[PAYMENT_VOID]),
+ (CHECKOUT_CALCULATE_TAXES, DISPLAY_LABELS[CHECKOUT_CALCULATE_TAXES]),
+ (ORDER_CALCULATE_TAXES, DISPLAY_LABELS[ORDER_CALCULATE_TAXES]),
(
SHIPPING_LIST_METHODS_FOR_CHECKOUT,
DISPLAY_LABELS[SHIPPING_LIST_METHODS_FOR_CHECKOUT],
@@ -488,6 +495,8 @@ class WebhookEventSyncType:
PAYMENT_PROCESS: PaymentPermissions.HANDLE_PAYMENTS,
PAYMENT_REFUND: PaymentPermissions.HANDLE_PAYMENTS,
PAYMENT_VOID: PaymentPermissions.HANDLE_PAYMENTS,
+ CHECKOUT_CALCULATE_TAXES: CheckoutPermissions.HANDLE_TAXES,
+ ORDER_CALCULATE_TAXES: CheckoutPermissions.HANDLE_TAXES,
SHIPPING_LIST_METHODS_FOR_CHECKOUT: ShippingPermissions.MANAGE_SHIPPING,
ORDER_FILTER_SHIPPING_METHODS: OrderPermissions.MANAGE_ORDERS,
CHECKOUT_FILTER_SHIPPING_METHODS: CheckoutPermissions.MANAGE_CHECKOUTS,
diff --git a/saleor/webhook/payload_serializers.py b/saleor/webhook/payload_serializers.py
index 93d8d3e3bc..2f5e4c93ab 100644
--- a/saleor/webhook/payload_serializers.py
+++ b/saleor/webhook/payload_serializers.py
@@ -41,11 +41,14 @@ class PayloadSerializer(JSONSerializer):
self.additional_fields = {}
self.extra_dict_data = {}
self.obj_id_name = "id"
+ self.pk_field_name = "id"
def serialize(self, queryset, **options):
self.additional_fields = options.pop("additional_fields", {})
self.extra_dict_data = options.pop("extra_dict_data", {})
self.obj_id_name = options.pop("obj_id_name", "id")
+ self.pk_field_name = options.pop("pk_field_name", "id")
+
return super().serialize(
queryset,
stream=options.pop("stream", None),
@@ -59,7 +62,7 @@ class PayloadSerializer(JSONSerializer):
def get_dump_object(self, obj):
obj_id = graphene.Node.to_global_id(
- obj._meta.object_name, getattr(obj, self.obj_id_name)
+ obj._meta.object_name, getattr(obj, self.pk_field_name)
)
data = OrderedDict(
[("type", str(obj._meta.object_name)), (self.obj_id_name, obj_id)]
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 1645d5be1d..3ddc661054 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -2,6 +2,7 @@ import json
import uuid
from collections import defaultdict
from dataclasses import asdict
+from decimal import Decimal
from typing import TYPE_CHECKING, Any, DefaultDict, Dict, Iterable, List, Optional, Set
import graphene
@@ -13,8 +14,11 @@ from graphene.utils.str_converters import to_camel_case
from .. import __version__
from ..account.models import User
from ..attribute.models import AttributeValueTranslation
+from ..checkout import base_calculations
+from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..core.prices import quantize_price, quantize_price_fields
+from ..core.taxes import include_taxes_in_prices
from ..core.utils import build_absolute_uri
from ..core.utils.anonymization import (
anonymize_checkout,
@@ -22,6 +26,7 @@ from ..core.utils.anonymization import (
generate_fake_user,
)
from ..core.utils.json_serializer import CustomJsonEncoder
+from ..discount import VoucherType
from ..discount.utils import fetch_active_discounts
from ..order import FulfillmentStatus, OrderStatus
from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
@@ -38,8 +43,10 @@ from .event_types import WebhookEventAsyncType
from .payload_serializers import PayloadSerializer
from .serializers import (
serialize_checkout_lines,
+ serialize_checkout_lines_for_tax_calculation,
serialize_product_or_variant_attributes,
)
+from .utils import get_base_price
if TYPE_CHECKING:
# pylint: disable=unused-import
@@ -69,6 +76,8 @@ ADDRESS_FIELDS = (
"phone",
)
+CHANNEL_FIELDS = ("slug", "currency_code")
+
ORDER_FIELDS = (
"status",
"origin",
@@ -259,8 +268,6 @@ def generate_order_payload(
)
discount_price_fields = ("amount_value",)
- channel_fields = ("slug", "currency_code")
-
lines = order.lines.all()
fulfillments = order.fulfillments.all()
payments = order.payments.all()
@@ -313,7 +320,7 @@ def generate_order_payload(
[order],
fields=ORDER_FIELDS,
additional_fields={
- "channel": (lambda o: o.channel, channel_fields),
+ "channel": (lambda o: o.channel, CHANNEL_FIELDS),
"shipping_address": (lambda o: o.shipping_address, ADDRESS_FIELDS),
"billing_address": (lambda o: o.billing_address, ADDRESS_FIELDS),
"discounts": (lambda _: discounts, discount_fields),
@@ -505,7 +512,6 @@ def generate_checkout_payload(
checkout_price_fields = ("discount_amount",)
quantize_price_fields(checkout, checkout_price_fields, checkout.currency)
user_fields = ("email", "first_name", "last_name")
- channel_fields = ("slug", "currency_code")
discounts = fetch_active_discounts()
lines_dict_data = serialize_checkout_lines(checkout, discounts)
@@ -521,8 +527,9 @@ def generate_checkout_payload(
[checkout],
fields=checkout_fields,
obj_id_name="token",
+ pk_field_name="token",
additional_fields={
- "channel": (lambda o: o.channel, channel_fields),
+ "channel": (lambda o: o.channel, CHANNEL_FIELDS),
"user": (lambda c: c.user, user_fields),
"billing_address": (lambda c: c.billing_address, ADDRESS_FIELDS),
"shipping_address": (lambda c: c.shipping_address, ADDRESS_FIELDS),
@@ -1140,10 +1147,10 @@ def generate_excluded_shipping_methods_for_order_payload(
@traced_payload_generator
def generate_excluded_shipping_methods_for_checkout_payload(
- checkout: "Checkout",
+ checkout_info: "CheckoutInfo",
available_shipping_methods: List[ShippingMethodData],
):
- checkout_data = json.loads(generate_checkout_payload(checkout))[0]
+ checkout_data = json.loads(generate_checkout_payload(checkout_info.checkout))[0]
payload = {
"checkout": checkout_data,
"shipping_methods": [
@@ -1154,6 +1161,181 @@ def generate_excluded_shipping_methods_for_checkout_payload(
return json.dumps(payload, cls=CustomJsonEncoder)
+@traced_payload_generator
+def generate_checkout_payload_for_tax_calculation(
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+):
+ checkout = checkout_info.checkout
+ included_taxes_in_prices = include_taxes_in_prices()
+ discount_infos = fetch_active_discounts()
+
+ serializer = PayloadSerializer()
+
+ checkout_fields = (
+ "currency",
+ "metadata",
+ )
+
+ # Prepare checkout data
+ address = checkout_info.shipping_address or checkout_info.billing_address
+
+ total_amount = quantize_price(
+ base_calculations.base_checkout_total(
+ checkout_info, discount_infos, lines
+ ).amount,
+ checkout.currency,
+ )
+
+ # Prepare user data
+ user = checkout_info.user
+ user_id = None
+ user_public_metadata = {}
+ if user:
+ user_id = graphene.Node.to_global_id("User", user.id)
+ user_public_metadata = user.metadata
+
+ # Prepare discount data
+ is_shipping_voucher = (
+ checkout_info.voucher.type == VoucherType.SHIPPING
+ if checkout_info.voucher
+ else False
+ )
+ discount_amount = quantize_price(checkout.discount_amount, checkout.currency)
+ discount_name = checkout.discount_name
+ discounts = (
+ [{"name": discount_name, "amount": discount_amount}]
+ if discount_amount and not is_shipping_voucher
+ else []
+ )
+
+ # Prepare shipping data
+ shipping_method = checkout.shipping_method
+ shipping_method_name = None
+ if shipping_method:
+ shipping_method_name = shipping_method.name
+ shipping_method_amount = quantize_price(
+ base_calculations.base_checkout_delivery_price(checkout_info, lines).amount,
+ checkout.currency,
+ )
+ if is_shipping_voucher:
+ shipping_method_amount = max(
+ shipping_method_amount - discount_amount, Decimal("0.0")
+ )
+
+ # Prepare line data
+ lines_dict_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines, discount_infos
+ )
+
+ checkout_data = serializer.serialize(
+ [checkout],
+ fields=checkout_fields,
+ pk_field_name="token",
+ additional_fields={
+ "channel": (lambda c: c.channel, CHANNEL_FIELDS),
+ "address": (lambda _: address, ADDRESS_FIELDS),
+ },
+ extra_dict_data={
+ "user_id": user_id,
+ "user_public_metadata": user_public_metadata,
+ "included_taxes_in_prices": included_taxes_in_prices,
+ "total_amount": total_amount,
+ "shipping_amount": shipping_method_amount,
+ "shipping_name": shipping_method_name,
+ "discounts": discounts,
+ "lines": lines_dict_data,
+ },
+ )
+ return checkout_data
+
+
+def _generate_order_lines_payload_for_tax_calculation(lines: Iterable[OrderLine]):
+
+ serializer = PayloadSerializer()
+ return serializer.serialize(
+ lines,
+ fields=("product_name", "variant_name", "quantity"),
+ extra_dict_data={
+ "variant_id": (lambda l: l.product_variant_id),
+ "full_name": (lambda l: l.variant.display_product() if l.variant else None),
+ "product_metadata": (
+ lambda l: l.variant.product.metadata if l.variant else {}
+ ),
+ "product_type_metadata": (
+ lambda l: l.variant.product.product_type.metadata if l.variant else {}
+ ),
+ "charge_taxes": (
+ lambda l: l.variant.product.charge_taxes if l.variant else None
+ ),
+ "sku": (lambda l: l.product_sku),
+ "unit_amount": (
+ lambda l: quantize_price(l.base_unit_price_amount, l.currency)
+ ),
+ "total_amount": (
+ lambda l: quantize_price(
+ l.base_unit_price_amount * l.quantity, l.currency
+ )
+ ),
+ },
+ )
+
+
+@traced_payload_generator
+def generate_order_payload_for_tax_calculation(order: "Order"):
+ serializer = PayloadSerializer()
+ included_taxes_in_prices = include_taxes_in_prices()
+
+ # Prepare Order data
+ address = order.shipping_address or order.billing_address
+ lines = order.lines.all()
+
+ # Prepare user data
+ user = order.user
+ user_id = None
+ user_public_metadata = {}
+ if user:
+ user_id = graphene.Node.to_global_id("User", user.id)
+ user_public_metadata = user.metadata
+
+ # Prepare discount data
+ discounts = order.discounts.all()
+ discounts_dict = []
+ for discount in discounts:
+ quantize_price_fields(discount, ("amount_value",), order.currency)
+ discount_amount = quantize_price(discount.amount_value, order.currency)
+ discounts_dict.append({"name": discount.name, "amount": discount_amount})
+
+ # 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_data = serializer.serialize(
+ [order],
+ fields=["currency", "metadata"],
+ additional_fields={
+ "channel": (lambda o: o.channel, CHANNEL_FIELDS),
+ "address": (lambda o: address, ADDRESS_FIELDS),
+ },
+ extra_dict_data={
+ "id": graphene.Node.to_global_id("Order", order.id),
+ "user_id": user_id,
+ "user_public_metadata": user_public_metadata,
+ "discounts": discounts_dict,
+ "included_taxes_in_prices": included_taxes_in_prices,
+ "shipping_amount": shipping_method_amount,
+ "shipping_name": shipping_method_name,
+ "lines": json.loads(
+ _generate_order_lines_payload_for_tax_calculation(lines)
+ ),
+ },
+ )
+ return order_data
+
+
@traced_payload_generator
def generate_transaction_action_request_payload(
transaction_data: "TransactionActionData",
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index 36089800fd..75d12a6d76 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import graphene
from ..attribute import AttributeEntityType, AttributeInputType
+from ..checkout import base_calculations
from ..checkout.fetch import fetch_checkout_lines
from ..core.prices import quantize_price
from ..discount import DiscountInfo
@@ -11,6 +12,7 @@ from ..product.models import Product
if TYPE_CHECKING:
# pylint: disable=unused-import
+ from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..product.models import ProductVariant
@@ -52,6 +54,51 @@ def serialize_checkout_lines(
return data
+def _get_checkout_line_payload_data(line_info: "CheckoutLineInfo") -> Dict[str, Any]:
+ line_id = graphene.Node.to_global_id("CheckoutLine", line_info.line.pk)
+ variant = line_info.variant
+ product = variant.product
+ return {
+ "id": line_id,
+ "sku": variant.sku,
+ "variant_id": variant.get_global_id(),
+ "quantity": line_info.line.quantity,
+ "charge_taxes": product.charge_taxes,
+ "full_name": variant.display_product(),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "product_metadata": line_info.product.metadata,
+ "product_type_metadata": line_info.product_type.metadata,
+ }
+
+
+def serialize_checkout_lines_for_tax_calculation(
+ checkout_info: "CheckoutInfo",
+ lines: Iterable["CheckoutLineInfo"],
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+) -> List[dict]:
+ channel = checkout_info.channel
+
+ return [
+ {
+ **_get_checkout_line_payload_data(line_info),
+ "unit_amount": quantize_price(
+ base_calculations.calculate_base_line_unit_price(
+ line_info, channel, discounts
+ ).amount,
+ checkout_info.checkout.currency,
+ ),
+ "total_amount": quantize_price(
+ base_calculations.calculate_base_line_total_price(
+ line_info, channel, discounts
+ ).amount,
+ checkout_info.checkout.currency,
+ ),
+ }
+ for line_info in lines
+ ]
+
+
def serialize_product_or_variant_attributes(
product_or_variant: Union["Product", "ProductVariant"]
) -> List[Dict]:
diff --git a/saleor/webhook/tests/conftest.py b/saleor/webhook/tests/conftest.py
new file mode 100644
index 0000000000..950b47af1c
--- /dev/null
+++ b/saleor/webhook/tests/conftest.py
@@ -0,0 +1,119 @@
+from decimal import Decimal
+from unittest.mock import Mock, patch
+
+import pytest
+
+from ...checkout import base_calculations
+from ...checkout.fetch import (
+ fetch_active_discounts,
+ fetch_checkout_info,
+ fetch_checkout_lines,
+)
+from ...plugins.manager import get_plugins_manager
+
+
+def checkout_with_prices(
+ checkout_with_items,
+ address,
+ address_other_country,
+ warehouse,
+ customer_user,
+ shipping_method,
+ voucher,
+):
+ # Need to save shipping_method before fetching checkout info.
+ checkout_with_items.shipping_method = shipping_method
+ checkout_with_items.save(update_fields=["shipping_method"])
+
+ manager = get_plugins_manager()
+ channel = checkout_with_items.channel
+ discounts_info = fetch_active_discounts()
+ lines = checkout_with_items.lines.all()
+ lines_info, _ = fetch_checkout_lines(checkout_with_items)
+ checkout_info = fetch_checkout_info(
+ checkout_with_items, lines, discounts_info, manager
+ )
+
+ for line, line_info in zip(lines, lines_info):
+ line.total_price_net_amount = base_calculations.calculate_base_line_total_price(
+ line_info, channel, discounts_info
+ ).amount
+ line.total_price_gross_amount = line.total_price_net_amount * Decimal("1.230")
+
+ checkout_with_items.discount_amount = Decimal("5.000")
+ checkout_with_items.discount_name = "Voucher 5 USD"
+ checkout_with_items.user = customer_user
+ checkout_with_items.billing_address = address
+ checkout_with_items.shipping_address = address_other_country
+ checkout_with_items.collection_point = warehouse
+ checkout_with_items.subtotal_net_amount = Decimal("100.000")
+ checkout_with_items.subtotal_gross_amount = Decimal("123.000")
+ checkout_with_items.total_net_amount = Decimal("150.000")
+ checkout_with_items.total_gross_amount = Decimal("178.000")
+ shipping_amount = base_calculations.base_checkout_delivery_price(
+ checkout_info, lines_info
+ ).amount
+ checkout_with_items.shipping_price_net_amount = shipping_amount
+ checkout_with_items.shipping_price_gross_amount = shipping_amount * Decimal("1.08")
+ checkout_with_items.metadata = {"meta_key": "meta_value"}
+ checkout_with_items.private_metadata = {"priv_meta_key": "priv_meta_value"}
+
+ checkout_with_items.lines.bulk_update(
+ lines,
+ [
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ ],
+ )
+
+ checkout_with_items.save(
+ update_fields=[
+ "discount_amount",
+ "discount_name",
+ "user",
+ "billing_address",
+ "shipping_address",
+ "collection_point",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "total_net_amount",
+ "total_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "metadata",
+ "private_metadata",
+ ]
+ )
+
+ user = checkout_with_items.user
+ user.metadata = {"user_public_meta_key": "user_public_meta_value"}
+ user.save(update_fields=["metadata"])
+
+ return checkout_with_items
+
+
+def mocked_fetch_checkout():
+ def mocked_fetch_side_effect(
+ checkout_info, manager, lines, address, discounts, force_update=False
+ ):
+ return checkout_info, lines
+
+ with patch(
+ "saleor.checkout.calculations.fetch_checkout_prices_if_expired",
+ new=Mock(side_effect=mocked_fetch_side_effect),
+ ) as mocked_fetch:
+ yield mocked_fetch
+
+
+def mocked_fetch_order():
+ def mocked_fetch_side_effect(order, manager, lines, force_update=False):
+ return order, lines
+
+ with patch(
+ "saleor.order.calculations.fetch_order_prices_if_expired",
+ new=Mock(side_effect=mocked_fetch_side_effect),
+ ) as mocked_fetch:
+ yield mocked_fetch
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 3c880cf0d0..c8a92f57d3 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
+from unittest.mock import ANY, Mock, patch, sentinel
import graphene
import pytest
@@ -16,9 +16,12 @@ from measurement.measures import Weight
from prices import Money
from ... import __version__
+from ...checkout import base_calculations
+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
from ...core.utils.json_serializer import CustomJsonEncoder
from ...discount import DiscountValueType, OrderDiscountType
+from ...discount.utils import fetch_active_discounts
from ...graphql.utils import get_user_or_app_from_context
from ...order import OrderOrigin
from ...order.actions import fulfill_order_lines
@@ -36,6 +39,7 @@ from ..payloads import (
PRODUCT_VARIANT_FIELDS,
_generate_collection_point_payload,
generate_checkout_payload,
+ generate_checkout_payload_for_tax_calculation,
generate_collection_payload,
generate_customer_payload,
generate_excluded_shipping_methods_for_checkout_payload,
@@ -45,6 +49,7 @@ from ..payloads import (
generate_list_gateways_payload,
generate_meta,
generate_order_payload,
+ generate_order_payload_for_tax_calculation,
generate_payment_payload,
generate_product_variant_payload,
generate_product_variant_with_stock_payload,
@@ -53,6 +58,7 @@ from ..payloads import (
generate_sale_toggle_payload,
generate_transaction_action_request_payload,
generate_translation_payload,
+ get_base_price,
)
from ..serializers import serialize_checkout_lines
@@ -61,27 +67,9 @@ def parse_django_datetime(date):
return json.loads(json.dumps(date, cls=DjangoJSONEncoder))
-@freeze_time()
[email protected]("saleor.webhook.payloads.generate_order_lines_payload")
[email protected]("saleor.webhook.payloads.generate_fulfillment_lines_payload")
-def test_generate_order_payload(
- mocked_fulfillment_lines,
- mocked_order_lines,
- fulfilled_order,
- payment_txn_captured,
- customer_user,
-):
- # given
- fulfillment_lines = '"fulfillment_lines"'
- mocked_fulfillment_lines.return_value = fulfillment_lines
- order_lines = '"order_lines"'
- mocked_order_lines.return_value = order_lines
-
+def order_for_payload(fulfilled_order):
order = fulfilled_order
- payment = payment_txn_captured
-
- payment.psp_reference = "123"
- payment.save(update_fields=["psp_reference"])
new_order = Order.objects.create(
channel=order.channel,
@@ -91,14 +79,14 @@ def test_generate_order_payload(
order.original = new_order
order.save(update_fields=["origin", "original"])
- discount_1 = order.discounts.create(
+ order.discounts.create(
type=OrderDiscountType.MANUAL,
value_type=DiscountValueType.PERCENTAGE,
value=Decimal("20"),
amount_value=Decimal("33.0"),
reason="Discount from staff",
)
- discount_2 = order.discounts.create(
+ discount = order.discounts.create(
type=OrderDiscountType.VOUCHER,
value_type=DiscountValueType.PERCENTAGE,
value=Decimal("10"),
@@ -106,16 +94,43 @@ def test_generate_order_payload(
name="Voucher",
)
- discount_2.created_at = datetime.now(pytz.utc) + timedelta(days=1)
- discount_2.save(update_fields=["created_at"])
+ discount.created_at = datetime.now(pytz.utc) + timedelta(days=1)
+ discount.save(update_fields=["created_at"])
line_without_sku = order.lines.last()
line_without_sku.product_sku = None
line_without_sku.save()
- assert order.fulfillments.count() == 1
+ return order
+
+
+def payment_for_payload(payment_txn_captured):
+ payment_txn_captured.psp_reference = "123"
+ payment_txn_captured.save(update_fields=["psp_reference"])
+ return payment_txn_captured
+
+@freeze_time()
[email protected]("saleor.webhook.payloads.generate_order_lines_payload")
[email protected]("saleor.webhook.payloads.generate_fulfillment_lines_payload")
+def test_generate_order_payload(
+ mocked_fulfillment_lines,
+ mocked_order_lines,
+ mocked_fetch_order,
+ order_for_payload,
+ payment_for_payload,
+ customer_user,
+):
+ fulfillment_lines = '"fulfillment_lines"'
+ mocked_fulfillment_lines.return_value = fulfillment_lines
+ order_lines = '"order_lines"'
+ mocked_order_lines.return_value = order_lines
+
+ order = order_for_payload
+ payment = payment_for_payload
fulfillment = order.fulfillments.first()
+ discount_1, discount_2 = list(order.discounts.all())
shipping_method_channel_listing = order.shipping_method.channel_listings.filter(
channel=order.channel,
).first()
@@ -125,6 +140,7 @@ def test_generate_order_payload(
# then
currency = order.currency
+
assert payload == {
"id": graphene.Node.to_global_id("Order", order.id),
"type": "Order",
@@ -278,6 +294,79 @@ def test_generate_order_payload(
mocked_fulfillment_lines.assert_called_with(fulfillment)
+@freeze_time()
[email protected]("taxes_included", [True, False])
[email protected]("saleor.webhook.payloads._generate_order_lines_payload_for_tax_calculation")
+def test_generate_order_payload_for_tax_calculation(
+ mocked_order_lines,
+ order_for_payload,
+ taxes_included,
+ site_settings,
+ customer_user,
+):
+ site_settings.include_taxes_in_prices = taxes_included
+ site_settings.save(update_fields=["include_taxes_in_prices"])
+
+ order_lines = '"order_lines"'
+ mocked_order_lines.return_value = order_lines
+
+ order = order_for_payload
+ discount_1, discount_2 = list(order.discounts.all())
+ user = order.user
+
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+ currency = order.currency
+
+ assert payload == {
+ "type": "Order",
+ "id": graphene.Node.to_global_id("Order", order.id),
+ "channel": {
+ "id": graphene.Node.to_global_id("Channel", order.channel_id),
+ "type": "Channel",
+ "slug": order.channel.slug,
+ "currency_code": order.channel.currency_code,
+ },
+ "address": {
+ "id": graphene.Node.to_global_id("Address", order.shipping_address_id),
+ "type": "Address",
+ "first_name": order.shipping_address.first_name,
+ "last_name": order.shipping_address.last_name,
+ "company_name": order.shipping_address.company_name,
+ "street_address_1": order.shipping_address.street_address_1,
+ "street_address_2": order.shipping_address.street_address_2,
+ "city": order.shipping_address.city,
+ "city_area": order.shipping_address.city_area,
+ "postal_code": order.shipping_address.postal_code,
+ "country": order.shipping_address.country.code,
+ "country_area": order.shipping_address.country_area,
+ "phone": str(order.shipping_address.phone),
+ },
+ "user_id": graphene.Node.to_global_id("User", user.pk),
+ "user_public_metadata": user.metadata,
+ "included_taxes_in_prices": taxes_included,
+ "currency": order.currency,
+ "shipping_name": order.shipping_method.name,
+ "shipping_amount": str(
+ quantize_price(
+ get_base_price(order.shipping_price, taxes_included), currency
+ )
+ ),
+ "metadata": order.metadata,
+ "discounts": [
+ {
+ "name": discount_1.name,
+ "amount": str(quantize_price(discount_1.amount_value, currency)),
+ },
+ {
+ "name": discount_2.name,
+ "amount": str(quantize_price(discount_2.amount_value, currency)),
+ },
+ ],
+ "lines": json.loads(order_lines),
+ }
+ mocked_order_lines.assert_called_once()
+
+
@freeze_time()
@mock.patch("saleor.webhook.payloads.generate_order_lines_payload")
@mock.patch("saleor.webhook.payloads.generate_fulfillment_lines_payload")
@@ -386,7 +475,9 @@ def test_generate_fulfillment_lines_payload_deleted_variant(order_with_lines):
assert payload["weight"] is None
-def test_order_lines_have_all_required_fields(order, order_line_with_one_allocation):
+def test_order_lines_have_all_required_fields(
+ mocked_fetch_order, order, order_line_with_one_allocation
+):
order.lines.add(order_line_with_one_allocation)
line = order_line_with_one_allocation
line.voucher_code = "Voucher001"
@@ -464,6 +555,102 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat
}
[email protected]("taxes_included", [True]) # , False])
+def test_order_lines_for_tax_calculation_have_all_required_fields(
+ order,
+ order_line_with_one_allocation,
+ taxes_included,
+ site_settings,
+):
+ site_settings.include_taxes_in_prices = taxes_included
+ site_settings.save(update_fields=["include_taxes_in_prices"])
+
+ order.lines.add(order_line_with_one_allocation)
+ currency = order.currency
+ line = order_line_with_one_allocation
+ line.voucher_code = "Voucher001"
+ line.unit_discount_amount = Decimal("10.0")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
+ line.sale_id = graphene.Node.to_global_id("Sale", 1)
+ line.save()
+ variant = line.variant
+ product = variant.product
+ product_type = product.product_type
+ product.metadata = {"product_meta": "value"}
+ product.save()
+ product_type.metadata = {"product_type_meta": "value"}
+ product_type.save()
+
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+ lines_payload = payload.get("lines")
+
+ assert len(lines_payload) == 1
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ line_payload = lines_payload[0]
+ assert line_payload == {
+ "type": "OrderLine",
+ "id": line_id,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "full_name": variant.display_product(),
+ "product_name": line.product_name,
+ "variant_name": line.variant_name,
+ "product_metadata": {"product_meta": "value"},
+ "product_type_metadata": {"product_type_meta": "value"},
+ "quantity": line.quantity,
+ "sku": line.product_sku,
+ "charge_taxes": variant.product.charge_taxes,
+ "unit_amount": str(quantize_price(line.base_unit_price_amount, currency)),
+ "total_amount": str(
+ quantize_price(line.base_unit_price_amount * line.quantity, currency)
+ ),
+ }
+
+
+def test_order_lines_for_tax_calculation_with_removed_variant(
+ order,
+ order_line_with_one_allocation,
+):
+
+ order.lines.add(order_line_with_one_allocation)
+ currency = order.currency
+ line = order_line_with_one_allocation
+ line.voucher_code = "Voucher001"
+ line.unit_discount_amount = Decimal("10.0")
+ line.unit_discount_type = DiscountValueType.FIXED
+ line.undiscounted_unit_price = line.unit_price + line.unit_discount
+ line.undiscounted_total_price = line.undiscounted_unit_price * line.quantity
+ line.sale_id = graphene.Node.to_global_id("Sale", 1)
+ variant = line.variant
+ line.variant = None
+ line.save()
+
+ payload = json.loads(generate_order_payload_for_tax_calculation(order))[0]
+ lines_payload = payload.get("lines")
+
+ assert len(lines_payload) == 1
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ line_payload = lines_payload[0]
+ assert line_payload == {
+ "type": "OrderLine",
+ "id": line_id,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.id),
+ "full_name": None,
+ "product_name": line.product_name,
+ "variant_name": line.variant_name,
+ "product_metadata": {},
+ "product_type_metadata": {},
+ "quantity": line.quantity,
+ "sku": line.product_sku,
+ "charge_taxes": None,
+ "unit_amount": str(quantize_price(line.base_unit_price_amount, currency)),
+ "total_amount": str(
+ quantize_price(line.base_unit_price_amount * line.quantity, currency)
+ ),
+ }
+
+
def test_order_line_without_sku_still_has_id(order, order_line_with_one_allocation):
order.lines.add(order_line_with_one_allocation)
line = order_line_with_one_allocation
@@ -962,7 +1149,6 @@ def test_generate_unique_page_attribute_value_translation_payload(
@freeze_time("1914-06-28 10:50")
def test_generate_customer_payload(customer_user, address_other_country, address):
-
customer = customer_user
customer.default_billing_address = address_other_country
customer.save()
@@ -1166,22 +1352,190 @@ def test_generate_sale_toggle_payload(sale):
assert set(payload["variants"]) == current_info["variants"]
+@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
[email protected]("taxes_included", [True, False])
+def test_generate_checkout_payload_for_tax_calculation(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_prices,
+ site_settings,
+ taxes_included,
+):
+ checkout = checkout_with_prices
+ currency = checkout.currency
+
+ discounts_info = fetch_active_discounts()
+
+ site_settings.include_taxes_in_prices = taxes_included
+ site_settings.save(update_fields=["include_taxes_in_prices"])
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+
+ # when
+ lines, _ = fetch_checkout_lines(checkout_with_prices)
+ manager = get_plugins_manager()
+ discounts = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, discounts, manager)
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.shipping_address
+
+ # then
+ shipping_price = str(
+ quantize_price(
+ checkout.shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price.amount,
+ currency,
+ )
+ )
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [{"amount": "5.00", "name": "Voucher 5 USD"}],
+ "included_taxes_in_prices": taxes_included,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {"meta_key": "meta_value"},
+ "shipping_name": checkout.shipping_method.name,
+ "user_id": graphene.Node.to_global_id("User", checkout.user.pk),
+ "user_public_metadata": {"user_public_meta_key": "user_public_meta_value"},
+ "total_amount": str(
+ quantize_price(
+ base_calculations.base_checkout_total(
+ checkout_info, discounts_info, lines
+ ).amount,
+ currency,
+ )
+ ),
+ "shipping_amount": shipping_price,
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ discounts_info,
+ )
+
+
+@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")
+def test_generate_checkout_payload_for_tax_calculation_digital_checkout(
+ mocked_serialize_checkout_lines_for_tax_calculation,
+ mocked_fetch_checkout,
+ checkout_with_digital_item,
+ site_settings,
+):
+ taxes_included = True
+ discounts_info = fetch_active_discounts()
+ checkout = checkout_with_digital_item
+ currency = checkout.currency
+
+ site_settings.include_taxes_in_prices = taxes_included
+ site_settings.save(update_fields=["include_taxes_in_prices"])
+
+ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}
+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (
+ mocked_serialized_checkout_lines
+ )
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager()
+ discounts = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout, lines, discounts, manager)
+
+ # when
+ payload = json.loads(
+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)
+ )[0]
+ address = checkout.billing_address
+
+ # then
+ assert payload == {
+ "type": "Checkout",
+ "id": graphene.Node.to_global_id("Checkout", checkout.token),
+ "address": {
+ "type": "Address",
+ "id": graphene.Node.to_global_id("Address", address.pk),
+ "first_name": address.first_name,
+ "last_name": address.last_name,
+ "company_name": address.company_name,
+ "street_address_1": address.street_address_1,
+ "street_address_2": address.street_address_2,
+ "city": address.city,
+ "city_area": address.city_area,
+ "postal_code": address.postal_code,
+ "country": address.country.code,
+ "country_area": address.country_area,
+ "phone": str(address.phone),
+ },
+ "channel": {
+ "type": "Channel",
+ "id": graphene.Node.to_global_id("Channel", checkout.channel_id),
+ "currency_code": checkout.channel.currency_code,
+ "slug": checkout.channel.slug,
+ },
+ "currency": currency,
+ "discounts": [],
+ "included_taxes_in_prices": taxes_included,
+ "lines": mocked_serialized_checkout_lines,
+ "metadata": {},
+ "shipping_name": None,
+ "shipping_amount": str(quantize_price(Decimal("0.00"), currency)),
+ "user_id": None,
+ "user_public_metadata": {},
+ "total_amount": str(
+ quantize_price(
+ base_calculations.base_checkout_total(
+ checkout_info, discounts_info, lines
+ ).amount,
+ currency,
+ )
+ ),
+ }
+ mocked_fetch_checkout.assert_not_called()
+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(
+ checkout_info,
+ lines,
+ discounts_info,
+ )
+
+
@freeze_time()
[email protected]("taxes_included", [True, False])
def test_generate_checkout_payload(
- checkout_with_items,
+ checkout_with_prices,
+ site_settings,
+ taxes_included,
customer_user,
- address,
- address_other_country,
- shipping_method,
- warehouse,
):
- checkout = checkout_with_items
+ checkout = checkout_with_prices
- checkout.user = customer_user
- checkout.billing_address = address
- checkout.shipping_address = address_other_country
- checkout.shipping_method = shipping_method
- checkout.collection_point = warehouse
+ site_settings.include_taxes_in_prices = taxes_included
+ site_settings.save(update_fields=["include_taxes_in_prices"])
# when
payload = json.loads(generate_checkout_payload(checkout, customer_user))[0]
@@ -1262,7 +1616,7 @@ def test_generate_checkout_payload(
)
),
},
- "lines": serialize_checkout_lines(checkout),
+ "lines": serialize_checkout_lines(checkout, []),
"collection_point": json.loads(
_generate_collection_point_payload(checkout.collection_point)
)[0],
@@ -1271,7 +1625,8 @@ def test_generate_checkout_payload(
}
-def test_generate_excluded_shipping_methods_for_order(order):
+@patch("saleor.order.calculations.fetch_order_prices_if_expired")
+def test_generate_excluded_shipping_methods_for_order(mocked_fetch, order):
shipping_method = ShippingMethodData(
id="123",
price=Money(Decimal("10.59"), "USD"),
@@ -1298,6 +1653,7 @@ def test_generate_excluded_shipping_methods_for_order(order):
"minimum_delivery_days": 2,
}
]
+ mocked_fetch.assert_not_called()
def test_generate_excluded_shipping_methods_for_checkout(checkout):
@@ -1310,9 +1666,12 @@ def test_generate_excluded_shipping_methods_for_checkout(checkout):
maximum_delivery_days=10,
minimum_delivery_days=2,
)
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager()
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
response = json.loads(
generate_excluded_shipping_methods_for_checkout_payload(
- checkout, [shipping_method]
+ checkout_info, [shipping_method]
)
)
@@ -1370,6 +1729,19 @@ def test_generate_meta(app, rf):
}
+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/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.py
index 6cb66500c5..22a3117f60 100644
--- a/saleor/webhook/tests/test_webhook_serializers.py
+++ b/saleor/webhook/tests/test_webhook_serializers.py
@@ -1,80 +1,27 @@
from operator import itemgetter
-from unittest.mock import ANY
+from unittest.mock import ANY, sentinel
import graphene
import pytest
-from ...attribute.models import AttributeValue
-from ...attribute.utils import associate_attribute_values_to_instance
-from ...checkout.fetch import fetch_checkout_lines
+from ...checkout import base_calculations
+from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...core.prices import quantize_price
+from ...discount.utils import fetch_active_discounts
+from ...plugins.manager import get_plugins_manager
from ..serializers import (
serialize_checkout_lines,
+ serialize_checkout_lines_for_tax_calculation,
serialize_product_or_variant_attributes,
)
[email protected]("taxes_calculated", [True, False])
-def test_serialize_checkout_lines(
- checkout_with_items_for_cc, taxes_calculated, site_settings
-):
- # given
- checkout = checkout_with_items_for_cc
- channel = checkout.channel
- checkout_lines, _ = fetch_checkout_lines(checkout, prefetch_variant_attributes=True)
-
- # when
- checkout_lines_data = serialize_checkout_lines(checkout)
-
- # then
- checkout_with_items_for_cc.refresh_from_db()
- for data, line_info in zip(checkout_lines_data, checkout_lines):
- variant = line_info.line.variant
- product = variant.product
- collections = line_info.collections
- variant_channel_listing = line_info.channel_listing
-
- base_price = variant.get_price(
- product, collections, channel, variant_channel_listing
- )
- currency = checkout.currency
- assert data == {
- "sku": variant.sku,
- "quantity": line_info.line.quantity,
- "base_price": str(quantize_price(base_price.amount, currency)),
- "currency": channel.currency_code,
- "full_name": variant.display_product(),
- "product_name": product.name,
- "variant_name": variant.name,
- "attributes": serialize_product_or_variant_attributes(variant),
- "variant_id": variant.get_global_id(),
- }
- assert len(checkout_lines_data) == len(list(checkout_lines))
-
-
def test_serialize_product_attributes(
- product_with_variant_with_two_attributes,
- product_with_multiple_values_attributes,
- product_type_page_reference_attribute,
- page,
+ product_with_variant_with_two_attributes, product_with_multiple_values_attributes
):
variant_data = serialize_product_or_variant_attributes(
product_with_variant_with_two_attributes.variants.first()
)
-
- product_type = product_with_multiple_values_attributes.product_type
- product_type.product_attributes.add(product_type_page_reference_attribute)
- attr_value = AttributeValue.objects.create(
- attribute=product_type_page_reference_attribute,
- name=page.title,
- slug=f"{product_with_multiple_values_attributes.pk}_{page.pk}",
- reference_page=page,
- )
- associate_attribute_values_to_instance(
- product_with_multiple_values_attributes,
- product_type_page_reference_attribute,
- attr_value,
- )
product_data = serialize_product_or_variant_attributes(
product_with_multiple_values_attributes
)
@@ -101,7 +48,7 @@ def test_serialize_product_attributes(
],
}
- assert len(product_data) == 2
+ assert len(product_data) == 1
assert product_data[0]["name"] == "Available Modes"
assert sorted(product_data[0]["values"], key=itemgetter("name")) == [
{
@@ -127,19 +74,98 @@ def test_serialize_product_attributes(
"value": "",
},
]
- assert product_data[1]["name"] == "Page reference"
- assert sorted(product_data[1]["values"], key=itemgetter("name")) == [
- {
- "name": "Test page",
- "slug": attr_value.slug,
- "file": None,
- "reference": graphene.Node.to_global_id(
- attr_value.attribute.entity_type, page.pk
- ),
- "rich_text": None,
- "date_time": None,
- "date": None,
- "boolean": None,
- "value": "",
- },
- ]
+
+
+ATTRIBUTES = sentinel.ATTRIBUTES
+
+
[email protected]("taxes_calculated", [True, False])
+def test_serialize_checkout_lines(
+ checkout_with_items_for_cc, taxes_calculated, site_settings
+):
+ # given
+ checkout = checkout_with_items_for_cc
+ channel = checkout.channel
+ checkout_lines, _ = fetch_checkout_lines(checkout, prefetch_variant_attributes=True)
+
+ # when
+ checkout_lines_data = serialize_checkout_lines(checkout)
+
+ # then
+ checkout_with_items_for_cc.refresh_from_db()
+ for data, line_info in zip(checkout_lines_data, checkout_lines):
+ variant = line_info.line.variant
+ product = variant.product
+ collections = line_info.collections
+ variant_channel_listing = line_info.channel_listing
+
+ base_price = variant.get_price(
+ product, collections, channel, variant_channel_listing
+ )
+ currency = checkout.currency
+ assert data == {
+ "sku": variant.sku,
+ "quantity": line_info.line.quantity,
+ "base_price": str(quantize_price(base_price.amount, currency)),
+ "currency": channel.currency_code,
+ "full_name": variant.display_product(),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "attributes": serialize_product_or_variant_attributes(variant),
+ "variant_id": variant.get_global_id(),
+ }
+ assert len(checkout_lines_data) == len(list(checkout_lines))
+
+
[email protected]("taxes_included", [True, False])
+def test_serialize_checkout_lines_for_tax_calculation(
+ checkout_with_prices, taxes_included, site_settings
+):
+ # We should be sure that we always sends base prices to tax app.
+ # We shouldn't use previously calculated prices because they can be
+ # changed by tax app due to e.g.
+ # Checkout discount
+ # Propagating shipping tax to lines.
+
+ # given
+ checkout = checkout_with_prices
+ lines, _ = fetch_checkout_lines(checkout)
+ manager = get_plugins_manager()
+ discounts_info = fetch_active_discounts()
+ checkout_info = fetch_checkout_info(checkout, lines, discounts_info, manager)
+ site_settings.include_taxes_in_prices = taxes_included
+ site_settings.save()
+
+ # when
+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(
+ checkout_info, lines, discounts_info
+ )
+
+ # then
+ for data, line_info in zip(checkout_lines_data, lines):
+ line = line_info.line
+ variant = line.variant
+ product = variant.product
+
+ total_price = base_calculations.calculate_base_line_total_price(
+ line_info, checkout_info.channel, discounts_info
+ ).amount
+ unit_price = base_calculations.calculate_base_line_unit_price(
+ line_info, checkout_info.channel, discounts_info
+ ).amount
+
+ assert data == {
+ "id": graphene.Node.to_global_id("CheckoutLine", line.pk),
+ "sku": variant.sku,
+ "quantity": line.quantity,
+ "charge_taxes": product.charge_taxes,
+ "full_name": variant.display_product(),
+ "product_name": product.name,
+ "variant_name": variant.name,
+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "product_metadata": product.metadata,
+ "product_type_metadata": product.product_type.metadata,
+ "unit_amount": unit_price,
+ "total_amount": total_price,
+ }
+ assert len(checkout_lines_data) == len(list(lines))
diff --git a/saleor/webhook/utils.py b/saleor/webhook/utils.py
index 3151ff02c6..a44b8a0b6a 100644
--- a/saleor/webhook/utils.py
+++ b/saleor/webhook/utils.py
@@ -1,7 +1,9 @@
+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
@@ -39,3 +41,9 @@ 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