Skip to content

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

Subscription for sync tax webooks (#10433)

Maciej Korycinski06ee0593edcf
diff --git a/saleor/graphql/core/types/taxes.py b/saleor/graphql/core/types/taxes.py
new file mode 100644
index 0000000000..dede8766c8
--- /dev/null
+++ b/saleor/graphql/core/types/taxes.py
@@ -0,0 +1,404 @@
+from decimal import Decimal
+from typing import List, Union
+
+import graphene
+from promise import Promise
+
+from ....checkout import base_calculations
+from ....checkout.models import Checkout, CheckoutLine
+from ....core.prices import quantize_price
+from ....core.taxes import include_taxes_in_prices, zero_money
+from ....discount import VoucherType
+from ....order.models import Order, OrderLine
+from ....shipping.models import ShippingMethodChannelListing
+from ...account.dataloaders import AddressByIdLoader
+from ...channel.dataloaders import ChannelByIdLoader
+from ...channel.types import Channel
+from ...checkout import types as checkout_types
+from ...checkout.dataloaders import (
+ CheckoutByTokenLoader,
+ CheckoutInfoByCheckoutTokenLoader,
+ CheckoutLinesByCheckoutTokenLoader,
+ CheckoutLinesInfoByCheckoutTokenLoader,
+)
+from ...discount.dataloaders import (
+ DiscountsByDateTimeLoader,
+ OrderDiscountsByOrderIDLoader,
+)
+from ...order import types as order_types
+from ...order.dataloaders import OrderLinesByOrderIdLoader
+from ...product.dataloaders.products import (
+ ProductByVariantIdLoader,
+ ProductVariantByIdLoader,
+)
+from ...shipping.dataloaders import ShippingMethodChannelListingByShippingMethodIdLoader
+from .common import NonNullList
+from .money import Money
+
+
+class TaxSourceObject(graphene.Union):
+ class Meta:
+ types = (checkout_types.Checkout, order_types.Order)
+
+ @classmethod
+ def resolve_type(cls, instance, info):
+ if isinstance(instance, Checkout):
+ return checkout_types.Checkout
+ if isinstance(instance, Order):
+ return order_types.Order
+ return super(TaxSourceObject, cls).resolve_type(instance, info)
+
+
+class TaxSourceLine(graphene.Union):
+ class Meta:
+ types = (checkout_types.CheckoutLine, order_types.OrderLine)
+
+ @classmethod
+ def resolve_type(cls, instance, info):
+ if isinstance(instance, CheckoutLine):
+ return checkout_types.CheckoutLine
+ if isinstance(instance, OrderLine):
+ return order_types.OrderLine
+ return super(TaxSourceObject, cls).resolve_type(instance, info)
+
+
+class TaxableObjectLine(graphene.ObjectType):
+ source_line = graphene.Field(
+ TaxSourceLine,
+ required=True,
+ description="The source line related to this tax line.",
+ )
+ quantity = graphene.Int(required=True, description="Number of items.")
+ charge_taxes = graphene.Boolean(
+ required=True,
+ description="Determines if taxes are being charged for the product.",
+ )
+ product_name = graphene.String(description="The product name.", required=True)
+ variant_name = graphene.String(description="The variant name.", required=True)
+ product_sku = graphene.String(description="The product sku.")
+
+ unit_price = graphene.Field(
+ Money, description="Price of the single item in the order line.", required=True
+ )
+ total_price = graphene.Field(
+ Money, description="Price of the order line.", required=True
+ )
+
+ @staticmethod
+ def resolve_variant_name(root: Union[CheckoutLine, OrderLine], info):
+ if isinstance(root, CheckoutLine):
+
+ def get_name(variant):
+ return variant.name
+
+ if not root.variant_id:
+ return ""
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(root.variant_id)
+ .then(get_name)
+ )
+ return root.variant_name
+
+ @staticmethod
+ def resolve_product_name(root: Union[CheckoutLine, OrderLine], info):
+ if isinstance(root, CheckoutLine):
+
+ def get_name(product):
+ return product.name
+
+ if not root.variant_id:
+ return ""
+ return (
+ ProductByVariantIdLoader(info.context)
+ .load(root.variant_id)
+ .then(get_name)
+ )
+ return root.product_name
+
+ @staticmethod
+ def resolve_product_sku(root: Union[CheckoutLine, OrderLine], info):
+ if isinstance(root, CheckoutLine):
+ if not root.variant_id:
+ return None
+
+ def get_sku(variant):
+ return variant.sku
+
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(root.variant_id)
+ .then(get_sku)
+ )
+ return root.product_sku
+
+ @staticmethod
+ def resolve_source_line(root: Union[CheckoutLine, OrderLine], info):
+ return root
+
+ @staticmethod
+ def resolve_charge_taxes(root: Union[CheckoutLine, OrderLine], info):
+
+ if not root.variant_id:
+ # By default charge taxes are set to True
+ return True
+
+ def get_charge_taxes(product):
+ return product.charge_taxes
+
+ return (
+ ProductByVariantIdLoader(info.context)
+ .load(root.variant_id)
+ .then(get_charge_taxes)
+ )
+
+ @staticmethod
+ def resolve_unit_price(root: Union[CheckoutLine, OrderLine], info):
+ if isinstance(root, CheckoutLine):
+
+ def with_checkout(checkout):
+ discounts = DiscountsByDateTimeLoader(info.context).load(
+ info.context.request_time
+ )
+ checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
+ checkout.token
+ )
+ lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
+ checkout.token
+ )
+
+ def calculate_line_unit_price(data):
+ (
+ discounts,
+ checkout_info,
+ lines,
+ ) = data
+ for line_info in lines:
+ if line_info.line.pk == root.pk:
+ return base_calculations.calculate_base_line_unit_price(
+ line_info=line_info,
+ channel=checkout_info.channel,
+ discounts=discounts,
+ )
+ return None
+
+ return Promise.all(
+ [
+ discounts,
+ checkout_info,
+ lines,
+ ]
+ ).then(calculate_line_unit_price)
+
+ return (
+ CheckoutByTokenLoader(info.context)
+ .load(root.checkout_id)
+ .then(with_checkout)
+ )
+ return root.base_unit_price
+
+ @staticmethod
+ def resolve_total_price(root: Union[CheckoutLine, OrderLine], info):
+ if isinstance(root, CheckoutLine):
+
+ def with_checkout(checkout):
+ discounts = DiscountsByDateTimeLoader(info.context).load(
+ info.context.request_time
+ )
+ checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
+ checkout.token
+ )
+ lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
+ checkout.token
+ )
+
+ def calculate_line_total_price(data):
+ (
+ discounts,
+ checkout_info,
+ lines,
+ ) = data
+ for line_info in lines:
+ if line_info.line.pk == root.pk:
+ return base_calculations.calculate_base_line_total_price(
+ line_info=line_info,
+ channel=checkout_info.channel,
+ discounts=discounts,
+ )
+ return None
+
+ return Promise.all(
+ [
+ discounts,
+ checkout_info,
+ lines,
+ ]
+ ).then(calculate_line_total_price)
+
+ return (
+ CheckoutByTokenLoader(info.context)
+ .load(root.checkout_id)
+ .then(with_checkout)
+ )
+ return root.base_unit_price * root.quantity
+
+
+class TaxableObjectDiscount(graphene.ObjectType):
+ name = graphene.String(description="The name of the discount.")
+ amount = graphene.Field(
+ Money, description="The amount of the discount.", required=True
+ )
+
+ class Meta:
+ description = "Taxable object discount."
+
+
+class TaxableObject(graphene.ObjectType):
+ source_object = graphene.Field(
+ TaxSourceObject,
+ required=True,
+ description="The source object related to this tax object.",
+ )
+ prices_entered_with_tax = graphene.Boolean(
+ required=True, description="Determines if prices contain entered tax.."
+ )
+ currency = graphene.String(required=True, description="The currency of the object.")
+ shipping_price = graphene.Field(
+ Money, required=True, description="The price of shipping method."
+ )
+ address = graphene.Field(
+ "saleor.graphql.account.types.Address",
+ description="The address data.",
+ )
+ discounts = NonNullList(
+ TaxableObjectDiscount, description="List of discounts.", required=True
+ )
+ lines = NonNullList(
+ TaxableObjectLine,
+ description="List of lines assigned to the object.",
+ required=True,
+ )
+ channel = graphene.Field(Channel, required=True)
+
+ class Meta:
+ description = "Taxable object."
+
+ @staticmethod
+ def resolve_channel(root: Union[Checkout, Order], info):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
+
+ @staticmethod
+ def resolve_address(root: Union[Checkout, Order], info):
+ address_id = root.shipping_address_id or root.billing_address_id
+ if not address_id:
+ return None
+ return AddressByIdLoader(info.context).load(address_id)
+
+ @staticmethod
+ def resolve_source_object(root: Union[Checkout, Order], info):
+ return root
+
+ @staticmethod
+ def resolve_prices_entered_with_tax(root: Union[Checkout, Order], info):
+ return include_taxes_in_prices()
+
+ @staticmethod
+ def resolve_currency(root: Union[Checkout, Order], info):
+ return root.currency
+
+ @staticmethod
+ def resolve_shipping_price(root: Union[Checkout, Order], info):
+ if isinstance(root, Checkout):
+
+ def calculate_shipping_price(data):
+ checkout_info, lines = data
+ is_shipping_voucher = (
+ checkout_info.voucher.type == VoucherType.SHIPPING
+ if checkout_info.voucher
+ else False
+ )
+ price = base_calculations.base_checkout_delivery_price(
+ checkout_info, lines
+ )
+ if is_shipping_voucher:
+ price.amount = max(
+ price.amount - checkout_info.checkout.discount_amount,
+ Decimal("0.0"),
+ )
+
+ return quantize_price(
+ price,
+ checkout_info.checkout.currency,
+ )
+
+ checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load(
+ root.token
+ )
+ lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(
+ root.token
+ )
+ return Promise.all(
+ [
+ checkout_info,
+ lines,
+ ]
+ ).then(calculate_shipping_price)
+
+ def calculate_base_shipping_method(
+ channel_listins: List[ShippingMethodChannelListing],
+ ):
+ for listing in channel_listins:
+ if listing.channel_id == root.channel_id:
+ return listing.price
+ return zero_money(root.currency)
+
+ if not root.shipping_method:
+ return zero_money(root.currency)
+
+ return (
+ ShippingMethodChannelListingByShippingMethodIdLoader(info.context)
+ .load(root.shipping_method_id)
+ .then(calculate_base_shipping_method)
+ )
+
+ @staticmethod
+ def resolve_discounts(root: Union[Checkout, Order], info):
+ if isinstance(root, Checkout):
+
+ def calculate_checkout_discounts(checkout_info):
+ is_shipping_voucher = (
+ checkout_info.voucher.type == VoucherType.SHIPPING
+ if checkout_info.voucher
+ else False
+ )
+ checkout = checkout_info.checkout
+ discount_name = checkout.discount_name
+ return (
+ [{"name": discount_name, "amount": checkout.discount}]
+ if checkout.discount and not is_shipping_voucher
+ else []
+ )
+
+ return (
+ CheckoutInfoByCheckoutTokenLoader(info.context)
+ .load(root.token)
+ .then(calculate_checkout_discounts)
+ )
+
+ def map_discounts(discounts):
+ return [
+ {"name": discount.name, "amount": discount.amount}
+ for discount in discounts
+ ]
+
+ return (
+ OrderDiscountsByOrderIDLoader(info.context)
+ .load(root.id)
+ .then(map_discounts)
+ )
+
+ @staticmethod
+ def resolve_lines(root: Union[Checkout, Order], info):
+ if isinstance(root, Checkout):
+ return CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
+ return OrderLinesByOrderIdLoader(info.context).load(root.id)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 94709fb7b3..bcd9a352dd 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -969,7 +969,7 @@ class Order(ModelObjectType):
delivery_method = graphene.Field(
DeliveryMethod,
description=(
- "The delivery method selected for this checkout."
+ "The delivery method selected for this order."
+ ADDED_IN_31
+ PREVIEW_FEATURE
),
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a88195423f..972543f0f8 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -8576,7 +8576,7 @@ type Order implements Node & ObjectWithMetadata {
isShippingRequired: Boolean!
"""
- The delivery method selected for this checkout.
+ The delivery method selected for this order.
Added in Saleor 3.1.
@@ -24074,6 +24074,92 @@ type ShippingListMethodsForCheckout implements Event {
shippingMethods: [ShippingMethod!]
}
+"""
+Synchronous webhook for calculating checkout/order taxes.
+
+Added in Saleor 3.7.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type CalculateTaxes implements Event {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+ taxBase: TaxableObject!
+}
+
+"""Taxable object."""
+type TaxableObject {
+ """The source object related to this tax object."""
+ sourceObject: TaxSourceObject!
+
+ """Determines if prices contain entered tax.."""
+ pricesEnteredWithTax: Boolean!
+
+ """The currency of the object."""
+ currency: String!
+
+ """The price of shipping method."""
+ shippingPrice: Money!
+
+ """The address data."""
+ address: Address
+
+ """List of discounts."""
+ discounts: [TaxableObjectDiscount!]!
+
+ """List of lines assigned to the object."""
+ lines: [TaxableObjectLine!]!
+ channel: Channel!
+}
+
+union TaxSourceObject = Checkout | Order
+
+"""Taxable object discount."""
+type TaxableObjectDiscount {
+ """The name of the discount."""
+ name: String
+
+ """The amount of the discount."""
+ amount: Money!
+}
+
+type TaxableObjectLine {
+ """The source line related to this tax line."""
+ sourceLine: TaxSourceLine!
+
+ """Number of items."""
+ quantity: Int!
+
+ """Determines if taxes are being charged for the product."""
+ chargeTaxes: Boolean!
+
+ """The product name."""
+ productName: String!
+
+ """The variant name."""
+ variantName: String!
+
+ """The product sku."""
+ productSku: String
+
+ """Price of the single item in the order line."""
+ unitPrice: Money!
+
+ """Price of the order line."""
+ totalPrice: Money!
+}
+
+union TaxSourceLine = CheckoutLine | OrderLine
+
"""_Any value scalar as defined by Federation spec."""
scalar _Any
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 22fc9390b9..9e858e8576 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -30,6 +30,7 @@ from ..core.descriptions import (
ADDED_IN_34,
ADDED_IN_35,
ADDED_IN_36,
+ ADDED_IN_37,
PREVIEW_FEATURE,
)
from ..core.scalars import PositiveDecimal
@@ -1358,6 +1359,24 @@ class ShippingListMethodsForCheckout(ObjectType, CheckoutBase):
)
+class CalculateTaxes(ObjectType):
+ tax_base = graphene.Field(
+ "saleor.graphql.core.types.taxes.TaxableObject", required=True
+ )
+
+ class Meta:
+ interfaces = (Event,)
+ description = (
+ "Synchronous webhook for calculating checkout/order taxes."
+ + ADDED_IN_37
+ + PREVIEW_FEATURE
+ )
+
+ def resolve_tax_base(root, info):
+ _, tax_base = root
+ return tax_base
+
+
class CheckoutFilterShippingMethods(ObjectType, CheckoutBase):
shipping_methods = NonNullList(
ShippingMethod,
@@ -1549,4 +1568,6 @@ WEBHOOK_TYPES_MAP = {
WebhookEventSyncType.SHIPPING_LIST_METHODS_FOR_CHECKOUT: (
ShippingListMethodsForCheckout
),
+ WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES: CalculateTaxes,
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES: CalculateTaxes,
}
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 17d95d47bc..f9cfdb4d98 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1330,6 +1330,8 @@ class WebhookPlugin(BasePlugin):
lines,
),
parse_tax_data,
+ checkout_info.checkout,
+ self.requestor,
)
def get_taxes_for_order(
@@ -1339,6 +1341,8 @@ class WebhookPlugin(BasePlugin):
WebhookEventSyncType.ORDER_CALCULATE_TAXES,
lambda: generate_order_payload_for_tax_calculation(order),
parse_tax_data,
+ order,
+ self.requestor,
)
def get_shipping_methods_for_checkout(
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index d53e6e98bb..e61bc805bd 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -118,7 +118,7 @@ def create_deliveries_for_subscriptions(
def create_delivery_for_subscription_sync_event(
- event_type, subscribable_object, webhook, requestor=None
+ event_type, subscribable_object, webhook, requestor=None, request=None
) -> Optional[EventDelivery]:
"""Generate webhook payload based on subscription query and create delivery object.
@@ -129,6 +129,7 @@ def create_delivery_for_subscription_sync_event(
:param subscribable_object: subscribable object to process via subscription query.
:param webhook: webhook object for which delivery will be created.
:param requestor: used in subscription webhooks to generate meta data for payload.
+ :param request: used to share context between sync event calls
:return: List of event deliveries to send via webhook tasks.
"""
if event_type not in WEBHOOK_TYPES_MAP:
@@ -137,11 +138,14 @@ def create_delivery_for_subscription_sync_event(
)
return None
+ if not request:
+ request = initialize_request(requestor, event_type in WebhookEventSyncType.ALL)
+
data = generate_payload_from_subscription(
event_type=event_type,
subscribable_object=subscribable_object,
subscription_query=webhook.subscription_query,
- request=initialize_request(requestor, event_type in WebhookEventSyncType.ALL),
+ request=request,
app=webhook.app,
)
if not data:
@@ -225,7 +229,6 @@ def trigger_webhook_sync(
)
if not delivery:
return None
-
else:
event_payload = EventPayload.objects.create(payload=data)
delivery = EventDelivery.objects.create(
@@ -247,6 +250,8 @@ def trigger_all_webhooks_sync(
event_type: str,
generate_payload: Callable,
parse_response: Callable[[Any], Optional[R]],
+ subscribable_object=None,
+ requestor=None,
) -> Optional[R]:
"""Send all synchronous webhook request for given event type.
@@ -257,19 +262,35 @@ def trigger_all_webhooks_sync(
this function returns None.
"""
webhooks = get_webhooks_for_event(event_type)
+ request_context = None
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,
- )
+ if webhook.subscription_query:
+ if request_context is None:
+ request_context = initialize_request(
+ requestor, event_type in WebhookEventSyncType.ALL
+ )
+ delivery = create_delivery_for_subscription_sync_event(
+ event_type=event_type,
+ subscribable_object=subscribable_object,
+ webhook=webhook,
+ request=request_context,
+ requestor=requestor,
+ )
+ if not delivery:
+ return None
+ else:
+ if event_payload is None:
+ event_payload = EventPayload.objects.create(payload=generate_payload())
+ 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:
+ if parsed_response := parse_response(response_data):
return parsed_response
return None
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
new file mode 100644
index 0000000000..cfa89305de
--- /dev/null
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -0,0 +1,467 @@
+import json
+from decimal import Decimal
+from functools import partial
+
+from freezegun import freeze_time
+from prices import Money, fixed_discount
+
+from .....core.prices import quantize_price
+from .....discount import DiscountValueType, VoucherType
+from .....graphql.core.utils import to_global_id_or_none
+from .....order.models import Order
+from .....tests.fixtures import recalculate_order
+from .....webhook.event_types import WebhookEventSyncType
+from .....webhook.models import Webhook
+from ...tasks import create_delivery_for_subscription_sync_event
+
+TAXES_SUBSCRIPTION_QUERY = """
+subscription {
+ event {
+ __typename
+ ... on CalculateTaxes {
+ taxBase {
+ pricesEnteredWithTax
+ currency
+ shippingPrice {
+ amount
+ }
+ address {
+ id
+ }
+ channel {
+ id
+ }
+
+ discounts {
+ amount {
+ amount
+ }
+ }
+
+ lines {
+ quantity
+ chargeTaxes
+ productName
+ variantName
+ productSku
+ unitPrice {
+ amount
+ }
+
+ totalPrice {
+ amount
+ }
+ sourceLine {
+ __typename
+ ... on CheckoutLine {
+ id
+ }
+ ... on OrderLine {
+ id
+ }
+ }
+ }
+ sourceObject {
+ __typename
+ ... on Checkout {
+ id
+ }
+ ... on Order {
+ id
+ }
+ }
+ }
+ }
+ }
+}
+
+
+"""
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_checkout_calculate_taxes(
+ checkout_ready_to_complete,
+ webhook_app,
+ permission_handle_taxes,
+):
+ # given
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ event_type, checkout_ready_to_complete, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {
+ "id": to_global_id_or_none(checkout_ready_to_complete.shipping_address)
+ },
+ "currency": "USD",
+ "discounts": [],
+ "channel": {"id": to_global_id_or_none(checkout_ready_to_complete.channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": "Test product",
+ "productSku": "123",
+ "quantity": 3,
+ "sourceLine": {
+ "id": to_global_id_or_none(
+ checkout_ready_to_complete.lines.first()
+ ),
+ "__typename": "CheckoutLine",
+ },
+ "totalPrice": {"amount": 30.0},
+ "unitPrice": {"amount": 10.0},
+ "variantName": "",
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 10.0},
+ "sourceObject": {
+ "id": to_global_id_or_none(checkout_ready_to_complete),
+ "__typename": "Checkout",
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_checkout_calculate_taxes_with_voucher(
+ checkout_with_voucher,
+ webhook_app,
+ permission_handle_taxes,
+):
+
+ # given
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ event_type, checkout_with_voucher, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": None,
+ "currency": "USD",
+ "discounts": [{"amount": {"amount": 20.0}}],
+ "channel": {"id": to_global_id_or_none(checkout_with_voucher.channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": "Test product",
+ "productSku": "123",
+ "quantity": 3,
+ "sourceLine": {
+ "id": to_global_id_or_none(checkout_with_voucher.lines.first()),
+ "__typename": "CheckoutLine",
+ },
+ "totalPrice": {"amount": 30.0},
+ "unitPrice": {"amount": 10.0},
+ "variantName": "",
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "sourceObject": {
+ "id": to_global_id_or_none(checkout_with_voucher),
+ "__typename": "Checkout",
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_checkout_calculate_taxes_with_shipping_voucher(
+ checkout_with_voucher,
+ voucher,
+ webhook_app,
+ permission_handle_taxes,
+):
+
+ # given
+ voucher.type = VoucherType.SHIPPING
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ event_type, checkout_with_voucher, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": None,
+ "currency": "USD",
+ "discounts": [{"amount": {"amount": 20.0}}],
+ "channel": {"id": to_global_id_or_none(checkout_with_voucher.channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": "Test product",
+ "productSku": "123",
+ "quantity": 3,
+ "sourceLine": {
+ "id": to_global_id_or_none(checkout_with_voucher.lines.first()),
+ "__typename": "CheckoutLine",
+ },
+ "totalPrice": {"amount": 30.0},
+ "unitPrice": {"amount": 10.0},
+ "variantName": "",
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "sourceObject": {
+ "id": to_global_id_or_none(checkout_with_voucher),
+ "__typename": "Checkout",
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_checkout_calculate_taxes_empty_checkout(
+ checkout,
+ webhook_app,
+ permission_handle_taxes,
+):
+ # given
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(
+ event_type, checkout, webhook
+ )
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": None,
+ "channel": {"id": to_global_id_or_none(checkout.channel)},
+ "currency": "USD",
+ "discounts": [],
+ "lines": [],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "sourceObject": {
+ "id": to_global_id_or_none(checkout),
+ "__typename": "Checkout",
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes(
+ order_line, webhook_app, permission_handle_taxes, shipping_zone
+):
+
+ # given
+ order = order_line.order
+ shipping_method = shipping_zone.shipping_methods.first()
+ order.shipping_method = shipping_method
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)
+
+ # then
+ shipping_price_amount = shipping_method.channel_listings.get(
+ channel=order.channel
+ ).price.amount
+ shipping_price_amount = quantize_price(shipping_price_amount, order.currency)
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [],
+ "channel": {"id": to_global_id_or_none(order.channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": "Test product",
+ "productSku": "SKU_A",
+ "quantity": 3,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(order_line),
+ },
+ "totalPrice": {"amount": 36.9},
+ "unitPrice": {"amount": 12.3},
+ "variantName": "SKU_A",
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": shipping_price_amount},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ },
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes_with_discounts(
+ order_line,
+ webhook_app,
+ permission_handle_taxes,
+):
+
+ # given
+ order = order_line.order
+ order.total = order_line.total_price + order.shipping_price
+ order.undiscounted_total = order.total
+ order.save()
+
+ value = Decimal("20")
+ discount = partial(fixed_discount, discount=Money(value, order.currency))
+ order.total = discount(order.total)
+ order.save()
+ order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=value,
+ reason="Discount reason",
+ amount=(order.undiscounted_total - order.total).gross, # type: ignore
+ )
+ recalculate_order(order)
+ order.refresh_from_db()
+
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": {"id": to_global_id_or_none(order.shipping_address)},
+ "currency": "USD",
+ "discounts": [{"amount": {"amount": 20.0}}],
+ "channel": {"id": to_global_id_or_none(order.channel)},
+ "lines": [
+ {
+ "chargeTaxes": True,
+ "productName": "Test product",
+ "productSku": "SKU_A",
+ "quantity": 3,
+ "sourceLine": {
+ "__typename": "OrderLine",
+ "id": to_global_id_or_none(order_line),
+ },
+ "totalPrice": {"amount": 36.9},
+ "unitPrice": {"amount": 12.3},
+ "variantName": "SKU_A",
+ }
+ ],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "sourceObject": {"__typename": "Order", "id": to_global_id_or_none(order)},
+ },
+ }
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_calculate_taxes_empty_order(
+ order, webhook_app, permission_handle_taxes, channel_USD
+):
+
+ # given
+ order = Order.objects.create(channel=channel_USD, currency="USD")
+ webhook_app.permissions.add(permission_handle_taxes)
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook = Webhook.objects.create(
+ name="Webhook",
+ app=webhook_app,
+ target_url="http://www.example.com/any",
+ subscription_query=TAXES_SUBSCRIPTION_QUERY,
+ )
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ webhook.events.create(event_type=event_type)
+
+ # when
+ deliveries = create_delivery_for_subscription_sync_event(event_type, order, webhook)
+
+ # then
+ assert json.loads(deliveries.payload.payload) == {
+ "__typename": "CalculateTaxes",
+ "taxBase": {
+ "address": None,
+ "currency": "USD",
+ "discounts": [],
+ "lines": [],
+ "pricesEnteredWithTax": True,
+ "shippingPrice": {"amount": 0.0},
+ "channel": {"id": to_global_id_or_none(order.channel)},
+ "sourceObject": {
+ "__typename": "Order",
+ "id": to_global_id_or_none(order),
+ },
+ },
+ }
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index 3669495e33..f90ef1acff 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -1,3 +1,4 @@
+import json
from unittest import mock
from unittest.mock import sentinel
@@ -9,7 +10,9 @@ from ....core import EventDeliveryStatus
from ....core.models import EventDelivery, EventPayload
from ....core.taxes import TaxType
from ....webhook.event_types import WebhookEventSyncType
+from ....webhook.models import Webhook
from ....webhook.payloads import generate_order_payload_for_tax_calculation
+from ...manager import get_plugins_manager
from ..utils import DEFAULT_TAX_CODE, DEFAULT_TAX_DESCRIPTION, parse_tax_data
@@ -141,3 +144,84 @@ def test_get_tax_code_from_object_meta_default_code(
code=DEFAULT_TAX_CODE,
description=DEFAULT_TAX_DESCRIPTION,
)
+
+
+@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_with_sync_subscription(
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ order,
+ tax_app,
+):
+ # given
+ mock_request.return_value = tax_data_response
+ plugin = webhook_plugin()
+ webhook = Webhook.objects.create(
+ name="Tax checkout webhook",
+ app=tax_app,
+ target_url="https://localhost:8888/tax-order",
+ subscription_query=(
+ "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ ),
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES)
+
+ # when
+ tax_data = plugin.get_taxes_for_order(order, None)
+
+ # then
+ payload = EventPayload.objects.get()
+ assert payload.payload == json.dumps({"taxBase": {"currency": "USD"}})
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.payload == payload
+ assert delivery.webhook == webhook
+ mock_request.assert_called_once_with(webhook.app.name, delivery)
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(tax_data_response)
+
+
+@freeze_time()
[email protected]("saleor.checkout.calculations.fetch_checkout_prices_if_expired")
[email protected]("saleor.plugins.webhook.tasks.send_webhook_request_sync")
+def test_get_taxes_for_checkout_with_sync_subscription(
+ mock_request,
+ mock_fetch,
+ webhook_plugin,
+ tax_data_response,
+ checkout,
+ tax_app,
+):
+ # given
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ mock_request.return_value = tax_data_response
+ plugin = webhook_plugin()
+ webhook = Webhook.objects.create(
+ name="Tax checkout webhook",
+ app=tax_app,
+ target_url="https://localhost:8888/tax-order",
+ subscription_query=(
+ "subscription{event{... on CalculateTaxes{taxBase{currency}}}}"
+ ),
+ )
+ webhook.events.create(event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+
+ # when
+ tax_data = plugin.get_taxes_for_checkout(checkout_info, [], None)
+
+ # then
+ payload = EventPayload.objects.get()
+ assert payload.payload == json.dumps({"taxBase": {"currency": "USD"}})
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ assert delivery.payload == payload
+ assert delivery.webhook == webhook
+ mock_request.assert_called_once_with(webhook.app.name, delivery)
+ mock_fetch.assert_not_called()
+ assert tax_data == parse_tax_data(tax_data_response)