Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add hook order_fullypaid, upgrade serizalizer
Maciej Korycinski9480cbe0379d
diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.pyindex 7827a591ac..975cc19602 100644--- a/saleor/extensions/manager.py+++ b/saleor/extensions/manager.py@@ -182,6 +182,10 @@ class ExtensionsManager:default_value = Nonereturn self.__run_method_on_plugins("customer_created", default_value, customer)+ def order_fully_paid(self, order: "Order"):+ default_value = None+ return self.__run_method_on_plugins("order_fully_paid", default_value, order)+# FIXME these methods should be more genericdef assign_tax_code_to_object_meta(self, obj: Union["Product", "ProductType"], tax_code: strdiff --git a/saleor/extensions/plugins/webhook/payloads.py b/saleor/extensions/plugins/webhook/payloads.pyindex 8ffc192433..cf829d4355 100644--- a/saleor/extensions/plugins/webhook/payloads.py+++ b/saleor/extensions/plugins/webhook/payloads.py@@ -1,49 +1,84 @@from typing import TYPE_CHECKING-from .serializer import WebhookSerializer+from .serializers import WebhookSerializerif TYPE_CHECKING:from ....order.models import Orderfrom ....account.models import User+ADDRESS_FIELDS = (+ "first_name",+ "last_name",+ "company_name",+ "street_address_1",+ "street_address_2",+ "city",+ "city_area",+ "postal_code",+ "country",+ "country_area",+ "phone",+)+def generate_order_payload(order: "Order"):serializer = WebhookSerializer()- lines_data = serializer.serialize(- order.lines.all(),- fields=(- "product_name",- "variant_name",- "translated_product_name",- "translated_variant_name",- "product_sku",- "quantity",- "currency",- "unit_price_net_amount",- "unit_price_gross_amount",- "tax_rate",- ),+ payment_fields = (+ "gateway"+ "is_active"+ "created"+ "modified"+ "charge_status"+ "total"+ "captured_amount"+ "currency"+ "billing_email"+ "billing_first_name"+ "billing_last_name"+ "billing_company_name"+ "billing_address_1"+ "billing_address_2"+ "billing_city"+ "billing_city_area"+ "billing_postal_code"+ "billing_country_code"+ "billing_country_area"+ )+ line_fields = (+ "product_name",+ "variant_name",+ "translated_product_name",+ "translated_variant_name",+ "product_sku",+ "quantity",+ "currency",+ "unit_price_net_amount",+ "unit_price_gross_amount",+ "tax_rate",+ )+ order_fields = (+ "created",+ "status",+ "user_email",+ "product_name",+ "variant_name",+ "translated_product_name",+ "translated_variant_name",+ "product_sku",+ "quantity",+ "currency",+ "unit_price_net_amount",+ "unit_price_gross_amount",+ "tax_rate",)order_data = serializer.serialize([order],- fields=(- "created"- "status"- "user_email"- "currency"- "shipping_method_name"- "shipping_price_net_amount"- "shipping_price_gross_amount"- "token"- "total_net_amount"- "total_gross_amount"- "discount_amount"- "discount_name"- ),+ fields=order_fields,additional_fields={- "lines": lines_data,- "shipping_address": order.shipping_address.as_data(),- "billing_address": order.billing_address.as_data(),+ "lines": (lambda o: o.lines.all(), line_fields),+ "payments": (lambda o: o.payments.all(), payment_fields),+ "shipping_address": (lambda o: o.shipping_address, ADDRESS_FIELDS),+ "billing_address": (lambda o: o.billing_address, ADDRESS_FIELDS),},)return order_data@@ -63,8 +98,14 @@ def generate_customer_payload(customer: "User"):"default_billing_address",],additional_fields={- "default_shipping_address": customer.default_billing_address.as_data(),- "default_billing_address": customer.default_shipping_address.as_data(),+ "default_shipping_address": (+ lambda c: c.default_billing_address,+ ADDRESS_FIELDS,+ ),+ "default_billing_address": (+ lambda c: c.default_shipping_address,+ ADDRESS_FIELDS,+ ),},)return datadiff --git a/saleor/extensions/plugins/webhook/plugin.py b/saleor/extensions/plugins/webhook/plugin.pyindex 37316afeb5..db15e71967 100644--- a/saleor/extensions/plugins/webhook/plugin.py+++ b/saleor/extensions/plugins/webhook/plugin.py@@ -35,6 +35,14 @@ class WebhookPlugin(BasePlugin):WebhookEventType.CUSTOMER_CREATED, customer_data)+ def order_fully_paid(self, order: "Order", previous_value: Any) -> Any:+ self._initialize_plugin_configuration()+ if not self.active:+ return previous_value+ order.lines.prefetch_related("lines")+ order_data = generate_order_payload(order)+ trigger_webhooks_for_event.delay(WebhookEventType.ORDER_FULLYPAID, order_data)+@classmethoddef _get_default_configuration(cls):defaults = {diff --git a/saleor/extensions/plugins/webhook/serializer.py b/saleor/extensions/plugins/webhook/serializer.pydeleted file mode 100644index e059a4097a..0000000000--- a/saleor/extensions/plugins/webhook/serializer.py+++ /dev/null@@ -1,43 +0,0 @@-from collections import OrderedDict--import graphene-from django.core.serializers.json import Serializer---class WebhookSerializer(Serializer):- def __init__(self):- super().__init__()- self.additional_fields = {}-- def serialize(- self,- queryset,- *,- stream=None,- fields=None,- use_natural_foreign_keys=False,- use_natural_primary_keys=False,- progress_output=None,- object_count=0,- **options,- ):- self.additional_fields = options.pop("additional_fields", {})- return super().serialize(- queryset,- stream=None,- fields=None,- use_natural_foreign_keys=False,- use_natural_primary_keys=False,- progress_output=None,- object_count=0,- **options,- )-- def get_dump_object(self, obj):- obj_id = graphene.Node.to_global_id(obj._meta.object_name, obj.id)- data = OrderedDict([("type", str(obj._meta.object_name)), ("id", obj_id)])- if not self.use_natural_primary_keys or not hasattr(obj, "natural_key"):- data["id"] = self._value_from_field(obj, obj._meta.pk)- data.update(self._current)- data.update(self.additional_fields)- return datadiff --git a/saleor/extensions/plugins/webhook/serializers.py b/saleor/extensions/plugins/webhook/serializers.pynew file mode 100644index 0000000000..2ad76fcbe5--- /dev/null+++ b/saleor/extensions/plugins/webhook/serializers.py@@ -0,0 +1,61 @@+from collections import OrderedDict+from collections.abc import Iterable++import graphene+from django.core.serializers.json import Serializer as JSONSerializer+from django.core.serializers.python import Serializer as PythonBaseSerializer+++class PythonSerializer(PythonBaseSerializer):+ def get_dump_object(self, obj):+ obj_id = graphene.Node.to_global_id(obj._meta.object_name, obj.id)+ data = OrderedDict([("type", str(obj._meta.object_name)), ("id", obj_id)])+ data.update(self._current)+ return data+++class WebhookSerializer(JSONSerializer):+ def __init__(self):+ super().__init__()+ self.additional_fields = {}++ def serialize(+ self,+ queryset,+ *,+ stream=None,+ fields=None,+ use_natural_foreign_keys=False,+ use_natural_primary_keys=False,+ progress_output=None,+ object_count=0,+ **options,+ ):+ self.additional_fields = options.pop("additional_fields", {})+ return super().serialize(+ queryset,+ stream=stream,+ fields=fields,+ use_natural_foreign_keys=use_natural_foreign_keys,+ use_natural_primary_keys=use_natural_primary_keys,+ progress_output=progress_output,+ object_count=object_count,+ **options,+ )++ def get_dump_object(self, obj):+ obj_id = graphene.Node.to_global_id(obj._meta.object_name, obj.id)+ data = OrderedDict([("type", str(obj._meta.object_name)), ("id", obj_id)])+ python_serializer = PythonSerializer()+ for field_name, (qs, fields) in self.additional_fields.items():+ data_to_serialize = qs(obj)+ if isinstance(data_to_serialize, Iterable):+ data[field_name] = python_serializer.serialize(+ data_to_serialize, fields=fields+ )+ else:+ data[field_name] = python_serializer.serialize(+ [data_to_serialize], fields=fields+ )[0]+ data.update(self._current)+ return datadiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 8adeea044f..f30af5e9ba 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -12,6 +12,7 @@ from django.utils.translation import pgettext_lazyfrom ..account.models import Address, Userfrom ..checkout.models import Checkoutfrom ..core import analytics+from ..extensions.manager import get_extensions_managerfrom ..order import events, utils as order_utilsfrom ..order.emails import send_payment_confirmationfrom ..order.models import Order@@ -102,6 +103,7 @@ def create_payment_information(def handle_fully_paid_order(order):events.order_fully_paid_event(order=order)+ get_extensions_manager().order_fully_paid(order)if order.get_customer_email():events.email_sent_event(diff --git a/saleor/webhook/__init__.py b/saleor/webhook/__init__.pyindex 2c0d9b4a2e..cde7d3c7b4 100644--- a/saleor/webhook/__init__.py+++ b/saleor/webhook/__init__.py@@ -3,10 +3,13 @@ from django.utils.translation import pgettext_lazyclass WebhookEventType:ORDER_CREATED = "order_created"+ ORDER_FULLYPAID = "order_fully_paid"+CUSTOMER_CREATED = "customer_created"CHOICES = [(ORDER_CREATED, pgettext_lazy("Order has been placed", "Order created")),+ (ORDER_FULLYPAID, pgettext_lazy("Order has been fully paid", "Order paid")),(CUSTOMER_CREATED,pgettext_lazy("Customer has been created", "Customer created"),@@ -14,5 +17,6 @@ class WebhookEventType:]PERMISSIONS = {ORDER_CREATED: "order.manage_orders",+ ORDER_FULLYPAID: "order.manage_orders",CUSTOMER_CREATED: "account.manage_users",}diff --git a/tests/extensions/plugins/test_webhook.py b/tests/extensions/plugins/test_webhook.pyindex c5f64783c1..275e3bae64 100644--- a/tests/extensions/plugins/test_webhook.py+++ b/tests/extensions/plugins/test_webhook.py@@ -90,3 +90,15 @@ def test_customer_created(mocked_webhook_trigger, settings, customer_user):mocked_webhook_trigger.assert_called_once_with(WebhookEventType.CUSTOMER_CREATED, expected_data)++[email protected]("saleor.extensions.plugins.webhook.plugin.trigger_webhooks_for_event.delay")+def test_order_fully_paid(mocked_webhook_trigger, settings, order_with_lines):+ settings.PLUGINS = ["saleor.extensions.plugins.webhook.plugin.WebhookPlugin"]+ manager = get_extensions_manager()+ manager.order_fully_paid(order_with_lines)++ expected_data = generate_order_payload(order_with_lines)+ mocked_webhook_trigger.assert_called_once_with(+ WebhookEventType.ORDER_FULLYPAID, expected_data+ )