Skip to content

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

Add hook customer_created and basic logic to generate payloads

Maciej Korycinski9c8ac4329b88
diff --git a/saleor/account/forms.py b/saleor/account/forms.py
index cde19f0d4e..5f9048dd9b 100644
--- a/saleor/account/forms.py
+++ b/saleor/account/forms.py
@@ -7,6 +7,7 @@ from phonenumbers.phonenumberutil import country_code_for_region
from ..account import events as account_events
from ..account.models import User
+from ..extensions.manager import get_extensions_manager
from . import emails
from .i18n import AddressMetaForm, get_address_form_class
@@ -109,6 +110,7 @@ class SignupForm(forms.ModelForm, FormWithReCaptcha):
if commit:
user.save()
account_events.customer_account_created_event(user=user)
+ get_extensions_manager().customer_created(customer=user)
return user
diff --git a/saleor/dashboard/customer/forms.py b/saleor/dashboard/customer/forms.py
index 7d28be62a2..21a824fffb 100644
--- a/saleor/dashboard/customer/forms.py
+++ b/saleor/dashboard/customer/forms.py
@@ -3,6 +3,7 @@ from django.utils.translation import pgettext_lazy
from ...account import events as account_events
from ...account.models import CustomerNote, User
+from ...extensions.manager import get_extensions_manager
def get_name_placeholder(name):
@@ -77,6 +78,7 @@ class CustomerForm(forms.ModelForm):
instance = super(CustomerForm, self).save(commit=commit) # type: User
if is_user_creation:
account_events.customer_account_created_event(user=instance)
+ get_extensions_manager().customer_created(customer=instance)
return instance
has_new_email = "email" in self.changed_data
diff --git a/saleor/extensions/base_plugin.py b/saleor/extensions/base_plugin.py
index 458d8d6715..8c042a1a49 100644
--- a/saleor/extensions/base_plugin.py
+++ b/saleor/extensions/base_plugin.py
@@ -11,7 +11,7 @@ if TYPE_CHECKING:
from ..core.taxes import TaxType
from ..checkout.models import Checkout, CheckoutLine
from ..product.models import Product
- from ..account.models import Address
+ from ..account.models import Address, User
from ..order.models import OrderLine, Order
@@ -136,6 +136,9 @@ class BasePlugin:
) -> Decimal:
return NotImplemented
+ def customer_created(self, customer: "User", previous_value: Any) -> Any:
+ return NotImplemented
+
@classmethod
def _update_config_items(
cls, configuration_to_update: List[dict], current_config: List[dict]
diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.py
index 63d033d276..7827a591ac 100644
--- a/saleor/extensions/manager.py
+++ b/saleor/extensions/manager.py
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
from .base_plugin import BasePlugin
from ..checkout.models import Checkout, CheckoutLine
from ..product.models import Product
- from ..account.models import Address
+ from ..account.models import Address, User
from ..order.models import OrderLine, Order
@@ -178,6 +178,10 @@ class ExtensionsManager:
"postprocess_order_creation", default_value, order
)
+ def customer_created(self, customer: "User"):
+ default_value = None
+ return self.__run_method_on_plugins("customer_created", default_value, customer)
+
# FIXME these methods should be more generic
def assign_tax_code_to_object_meta(
self, obj: Union["Product", "ProductType"], tax_code: str
diff --git a/saleor/extensions/plugins/webhook/payloads.py b/saleor/extensions/plugins/webhook/payloads.py
new file mode 100644
index 0000000000..8ffc192433
--- /dev/null
+++ b/saleor/extensions/plugins/webhook/payloads.py
@@ -0,0 +1,70 @@
+from typing import TYPE_CHECKING
+
+from .serializer import WebhookSerializer
+
+if TYPE_CHECKING:
+ from ....order.models import Order
+ from ....account.models import User
+
+
+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",
+ ),
+ )
+ 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"
+ ),
+ additional_fields={
+ "lines": lines_data,
+ "shipping_address": order.shipping_address.as_data(),
+ "billing_address": order.billing_address.as_data(),
+ },
+ )
+ return order_data
+
+
+def generate_customer_payload(customer: "User"):
+ serializer = WebhookSerializer()
+ data = serializer.serialize(
+ [customer],
+ fields=[
+ "email",
+ "first_name",
+ "last_name",
+ "is_active",
+ "date_joined",
+ "default_shipping_address",
+ "default_billing_address",
+ ],
+ additional_fields={
+ "default_shipping_address": customer.default_billing_address.as_data(),
+ "default_billing_address": customer.default_shipping_address.as_data(),
+ },
+ )
+ return data
diff --git a/saleor/extensions/plugins/webhook/plugin.py b/saleor/extensions/plugins/webhook/plugin.py
index 73206385d0..37316afeb5 100644
--- a/saleor/extensions/plugins/webhook/plugin.py
+++ b/saleor/extensions/plugins/webhook/plugin.py
@@ -1,13 +1,13 @@
from typing import TYPE_CHECKING, Any
-from django.core import serializers
-
from ....webhook import WebhookEventType
from ...base_plugin import BasePlugin
+from .payloads import generate_customer_payload, generate_order_payload
from .tasks import trigger_webhooks_for_event
if TYPE_CHECKING:
from ....order.models import Order
+ from ....account.models import User
class WebhookPlugin(BasePlugin):
@@ -19,11 +19,21 @@ class WebhookPlugin(BasePlugin):
def postprocess_order_creation(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_CREATED, order_data)
+ def customer_created(self, customer: "User", previous_value: Any) -> Any:
+ self._initialize_plugin_configuration()
if not self.active:
return previous_value
- data = serializers.serialize("json", [order])
- trigger_webhooks_for_event.delay(WebhookEventType.ORDER_CREATED, data)
+
+ customer_data = generate_customer_payload(customer)
+ trigger_webhooks_for_event.delay(
+ WebhookEventType.CUSTOMER_CREATED, customer_data
+ )
@classmethod
def _get_default_configuration(cls):
diff --git a/saleor/extensions/plugins/webhook/serializer.py b/saleor/extensions/plugins/webhook/serializer.py
new file mode 100644
index 0000000000..e059a4097a
--- /dev/null
+++ b/saleor/extensions/plugins/webhook/serializer.py
@@ -0,0 +1,43 @@
+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 data
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 34a8c28bce..d6f98f44fa 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -38,6 +38,7 @@ class AccountRegister(ModelMutation):
user.set_password(password)
user.save()
account_events.customer_account_created_event(user=user)
+ info.context.extensions.customer_created(customer=user)
class AccountInput(graphene.InputObjectType):
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index aad6df1a3b..7cda7306cc 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -310,6 +310,7 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
# The instance is a new object in db, create an event
if is_creation:
+ info.context.extensions.customer_created(customer=instance)
account_events.customer_account_created_event(user=instance)
if cleaned_input.get("send_password_email"):
diff --git a/saleor/graphql/account/mutations/deprecated_account.py b/saleor/graphql/account/mutations/deprecated_account.py
index 2bce0f18dc..68b50b3256 100644
--- a/saleor/graphql/account/mutations/deprecated_account.py
+++ b/saleor/graphql/account/mutations/deprecated_account.py
@@ -37,6 +37,7 @@ class CustomerRegister(ModelMutation):
user.set_password(password)
user.save()
account_events.customer_account_created_event(user=user)
+ info.context.extensions.customer_created(customer=user)
class LoggedUserUpdate(BaseCustomerCreate):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5c9412d76f..63123508d7 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3812,6 +3812,7 @@ type WebhookEvent {
enum WebhookEventTypeEnum {
ORDER_CREATED
+ CUSTOMER_CREATED
}
type WebhookUpdate {
diff --git a/saleor/webhook/__init__.py b/saleor/webhook/__init__.py
index 95986dad88..2c0d9b4a2e 100644
--- a/saleor/webhook/__init__.py
+++ b/saleor/webhook/__init__.py
@@ -3,6 +3,16 @@ from django.utils.translation import pgettext_lazy
class WebhookEventType:
ORDER_CREATED = "order_created"
+ CUSTOMER_CREATED = "customer_created"
- CHOICES = [(ORDER_CREATED, pgettext_lazy("Order has been placed", "Order created"))]
- PERMISSIONS = {ORDER_CREATED: "order.manage_orders"}
+ CHOICES = [
+ (ORDER_CREATED, pgettext_lazy("Order has been placed", "Order created")),
+ (
+ CUSTOMER_CREATED,
+ pgettext_lazy("Customer has been created", "Customer created"),
+ ),
+ ]
+ PERMISSIONS = {
+ ORDER_CREATED: "order.manage_orders",
+ CUSTOMER_CREATED: "account.manage_users",
+ }
diff --git a/tests/extensions/plugins/cassettes/test_preprocess_order_creation.yaml b/tests/extensions/plugins/cassettes/test_preprocess_order_creation.yaml
deleted file mode 100644
index 47b3b6122d..0000000000
--- a/tests/extensions/plugins/cassettes/test_preprocess_order_creation.yaml
+++ /dev/null
@@ -1,97 +0,0 @@
-interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "15.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": ""}, {"quantity": 1, "amount": "10.00",
- "taxCode": "FR020100", "taxIncluded": true, "itemCode": "Shipping", "description":
- ""}], "code": "aaac0cac-a6f0-4091-9d29-d0f096a8cd4d", "date": "2019-07-23",
- "customerCode": 0, "addresses": {"shipFrom": {"line1": "2000 Main Street", "line2":
- "", "city": "Irvine", "region": "CA", "country": "US", "postalCode": "92614"},
- "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
- Authorization:
- - Basic Og==
- Connection:
- - keep-alive
- Content-Length:
- - '746'
- User-Agent:
- - python-requests/2.22.0
- method: POST
- uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: "{\"id\":0,\"code\":\"aaac0cac-a6f0-4091-9d29-d0f096a8cd4d\",\"companyId\"\
- :242975,\"date\":\"2019-07-23\",\"paymentDate\":\"2019-07-23\",\"status\"\
- :\"Temporary\",\"type\":\"SalesOrder\",\"currencyCode\":\"USD\",\"customerVendorCode\"\
- :\"0\",\"customerCode\":\"0\",\"reconciled\":false,\"totalAmount\":20.33,\"\
- totalExempt\":0.0,\"totalDiscount\":0.0,\"totalTax\":4.67,\"totalTaxable\"\
- :20.33,\"totalTaxCalculated\":4.67,\"adjustmentReason\":\"NotAdjusted\",\"\
- locked\":false,\"version\":1,\"exchangeRateEffectiveDate\":\"2019-07-23\"\
- ,\"exchangeRate\":1.0,\"email\":\"\",\"modifiedDate\":\"2019-07-23T13:43:31.8029148Z\"\
- ,\"modifiedUserId\":283192,\"taxDate\":\"2019-07-23T00:00:00\",\"lines\":[{\"\
- id\":0,\"transactionId\":0,\"lineNumber\":\"1\",\"description\":\"\",\"discountAmount\"\
- :0.0,\"exemptAmount\":0.0,\"exemptCertId\":0,\"isItemTaxable\":true,\"itemCode\"\
- :\"123\",\"lineAmount\":12.2,\"quantity\":3.0,\"reportingDate\":\"2019-07-23\"\
- ,\"tax\":2.8,\"taxableAmount\":12.2,\"taxCalculated\":2.8,\"taxCode\":\"O9999999\"\
- ,\"taxCodeId\":5340,\"taxDate\":\"2019-07-23\",\"taxIncluded\":true,\"details\"\
- :[{\"id\":0,\"transactionLineId\":0,\"transactionId\":0,\"country\":\"PL\"\
- ,\"region\":\"PL\",\"exemptAmount\":0.0,\"jurisCode\":\"PL\",\"jurisName\"\
- :\"POLAND\",\"stateAssignedNo\":\"\",\"jurisType\":\"CNT\",\"jurisdictionType\"\
- :\"Country\",\"nonTaxableAmount\":0.0,\"rate\":0.230000,\"tax\":2.8,\"taxableAmount\"\
- :12.2,\"taxType\":\"Output\",\"taxSubTypeId\":\"O\",\"taxName\":\"Standard\
- \ Rate\",\"taxAuthorityTypeId\":45,\"taxCalculated\":2.8,\"rateType\":\"Standard\"\
- ,\"rateTypeCode\":\"S\",\"unitOfBasis\":\"PerCurrencyUnit\",\"isNonPassThru\"\
- :false}],\"nonPassthroughDetails\":[],\"hsCode\":\"\",\"costInsuranceFreight\"\
- :0.0,\"vatCode\":\"PLS-2300O--US\",\"vatNumberTypeId\":0},{\"id\":0,\"transactionId\"\
- :0,\"lineNumber\":\"2\",\"description\":\"\",\"discountAmount\":0.0,\"exemptAmount\"\
- :0.0,\"exemptCertId\":0,\"isItemTaxable\":true,\"itemCode\":\"Shipping\",\"\
- lineAmount\":8.13,\"quantity\":1.0,\"reportingDate\":\"2019-07-23\",\"tax\"\
- :1.87,\"taxableAmount\":8.13,\"taxCalculated\":1.87,\"taxCode\":\"FR020100\"\
- ,\"taxCodeId\":4784,\"taxDate\":\"2019-07-23\",\"taxIncluded\":true,\"details\"\
- :[{\"id\":0,\"transactionLineId\":0,\"transactionId\":0,\"country\":\"PL\"\
- ,\"region\":\"PL\",\"exemptAmount\":0.0,\"jurisCode\":\"PL\",\"jurisName\"\
- :\"POLAND\",\"stateAssignedNo\":\"\",\"jurisType\":\"CNT\",\"jurisdictionType\"\
- :\"Country\",\"nonTaxableAmount\":0.0,\"rate\":0.230000,\"tax\":1.87,\"taxableAmount\"\
- :8.13,\"taxType\":\"Output\",\"taxSubTypeId\":\"O\",\"taxName\":\"Standard\
- \ Rate\",\"taxAuthorityTypeId\":45,\"taxCalculated\":1.87,\"rateType\":\"\
- Standard\",\"rateTypeCode\":\"S\",\"unitOfBasis\":\"PerCurrencyUnit\",\"isNonPassThru\"\
- :false}],\"nonPassthroughDetails\":[],\"hsCode\":\"\",\"costInsuranceFreight\"\
- :0.0,\"vatCode\":\"PLS-2300F--US\",\"vatNumberTypeId\":0}],\"addresses\":[{\"\
- id\":0,\"transactionId\":0,\"boundaryLevel\":\"Zip5\",\"line1\":\"T\u0119\
- czowa 7\",\"line2\":\"\",\"line3\":\"\",\"city\":\"WROCLAW\",\"region\":\"\
- \",\"postalCode\":\"53-601\",\"country\":\"PL\",\"taxRegionId\":205102,\"\
- latitude\":\"0\",\"longitude\":\"0\"},{\"id\":0,\"transactionId\":0,\"boundaryLevel\"\
- :\"Zip5\",\"line1\":\"2000 Main Street\",\"line2\":\"\",\"line3\":\"\",\"\
- city\":\"Irvine\",\"region\":\"CA\",\"postalCode\":\"92614\",\"country\":\"\
- US\",\"taxRegionId\":4017409,\"latitude\":\"0\",\"longitude\":\"0\"}],\"summary\"\
- :[{\"country\":\"PL\",\"region\":\"PL\",\"jurisType\":\"Country\",\"jurisCode\"\
- :\"PL\",\"jurisName\":\"POLAND\",\"taxAuthorityType\":45,\"stateAssignedNo\"\
- :\"\",\"taxType\":\"Output\",\"taxSubType\":\"O\",\"taxName\":\"Standard Rate\"\
- ,\"rateType\":\"Standard\",\"taxable\":20.33,\"rate\":0.230000,\"tax\":4.67,\"\
- taxCalculated\":4.67,\"nonTaxable\":0.0,\"exemption\":0.0}]}"
- headers:
- Connection:
- - keep-alive
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Tue, 23 Jul 2019 13:43:42 GMT
- Location:
- - /api/v2/companies/242975/transactions/0
- ServerDuration:
- - '00:00:00.0911840'
- Transfer-Encoding:
- - chunked
- X-Content-Type-Options:
- - nosniff
- status:
- code: 201
- message: Created
-version: 1
diff --git a/tests/extensions/plugins/cassettes/test_preprocess_order_creation_wrong_data.yaml b/tests/extensions/plugins/cassettes/test_preprocess_order_creation_wrong_data.yaml
deleted file mode 100644
index 90507f635b..0000000000
--- a/tests/extensions/plugins/cassettes/test_preprocess_order_creation_wrong_data.yaml
+++ /dev/null
@@ -1,51 +0,0 @@
-interactions:
-- request:
- body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
- "lines": [{"quantity": 3, "amount": "15.00", "taxCode": "O9999999", "taxIncluded":
- true, "itemCode": "123", "description": ""}, {"quantity": 1, "amount": "10.00",
- "taxCode": "FR020100", "taxIncluded": true, "itemCode": "Shipping", "description":
- ""}], "code": "69a838ee-0c2e-4768-9f5d-ee4cb32a152e", "date": "2019-07-23",
- "customerCode": 0, "addresses": {"shipFrom": {"line1": null, "line2": null,
- "city": null, "region": null, "country": null, "postalCode": null}, "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
- Authorization:
- - Basic Tm9uZTpOb25l
- Connection:
- - keep-alive
- Content-Length:
- - '727'
- User-Agent:
- - python-requests/2.22.0
- method: POST
- uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
- response:
- body:
- string: '{"error":{"code":"AuthenticationException","message":"Authentication
- failed.","target":"HttpRequestHeaders","details":[{"code":"AuthenticationException","number":30,"message":"Authentication
- failed.","description":"Unable to authenticate the user or the account.","faultCode":"Client","helpLink":"http://developer.avalara.com/avatax/errors/AuthenticationException","severity":"Exception"},{"code":"StringLengthError","number":13,"message":"Field
- ''password'' has an invalid length.","description":"Field ''password'' must
- be between 5 and 50 characters in length.","faultCode":"Client","helpLink":"http://developer.avalara.com/avatax/errors/StringLengthError","severity":"Error"}]}}'
- headers:
- Connection:
- - keep-alive
- Content-Type:
- - application/json; charset=utf-8
- Date:
- - Tue, 23 Jul 2019 14:05:25 GMT
- ServerDuration:
- - '00:00:00.0009998'
- Transfer-Encoding:
- - chunked
- X-Content-Type-Options:
- - nosniff
- status:
- code: 401
- message: Unauthorized
-version: 1
diff --git a/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event.yaml b/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event.yaml
index 1802012169..49906e4e59 100644
--- a/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event.yaml
+++ b/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event.yaml
@@ -1,10 +1,10 @@
interactions:
- request:
- body: '[{"model": "order.order", "pk": 65, "fields": {"created": "2019-09-16T11:26:04.813Z",
- "status": "unfulfilled", "user": 65, "language_code": "en", "tracking_client_id":
- "", "billing_address": 259, "shipping_address": 260, "user_email": "[email protected]",
- "currency": "USD", "shipping_method": 65, "shipping_method_name": "DHL", "shipping_price_net_amount":
- "10.00", "shipping_price_gross_amount": "12.30", "token": "d885f09b-b922-4f69-9174-f89c938e6431",
+ body: '[{"model": "order.order", "pk": 84, "fields": {"created": "2019-09-17T13:54:55.227Z",
+ "status": "unfulfilled", "user": 92, "language_code": "en", "tracking_client_id":
+ "", "billing_address": 351, "shipping_address": 352, "user_email": "[email protected]",
+ "currency": "USD", "shipping_method": 84, "shipping_method_name": "DHL", "shipping_price_net_amount":
+ "10.00", "shipping_price_gross_amount": "12.30", "token": "ce7b260c-f70d-430b-b88b-3519624a7974",
"checkout_token": "", "total_net_amount": "80.00", "total_gross_amount": "98.40",
"voucher": null, "discount_amount": "0.00", "discount_name": "", "translated_discount_name":
"", "display_gross_prices": true, "customer_note": "", "weight": "0.0 kg", "gift_cards":
@@ -38,7 +38,7 @@ interactions:
Content-Type:
- text/plain; charset=UTF-8
Date:
- - Mon, 16 Sep 2019 11:26:05 GMT
+ - Tue, 17 Sep 2019 13:54:59 GMT
Server:
- nginx/1.10.3
Transfer-Encoding:
@@ -48,9 +48,9 @@ interactions:
X-RateLimit-Limit:
- '30'
X-RateLimit-Remaining:
- - '27'
+ - '29'
X-Request-Id:
- - 65d089ee-a86f-463e-93da-f6ae93b615b3
+ - 33161af9-c306-4918-ad9b-fad2b5b9897f
X-Token-Id:
- f0fc9979-cbd4-47b7-8705-1acb03fff1d0
status:
diff --git a/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event_with_secret_key.yaml b/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event_with_secret_key.yaml
index a377694969..00740f3818 100644
--- a/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event_with_secret_key.yaml
+++ b/tests/extensions/plugins/cassettes/test_trigger_webhooks_for_event_with_secret_key.yaml
@@ -1,10 +1,10 @@
interactions:
- request:
- body: '[{"model": "order.order", "pk": 66, "fields": {"created": "2019-09-16T11:26:30.411Z",
- "status": "unfulfilled", "user": 66, "language_code": "en", "tracking_client_id":
- "", "billing_address": 263, "shipping_address": 264, "user_email": "[email protected]",
- "currency": "USD", "shipping_method": 66, "shipping_method_name": "DHL", "shipping_price_net_amount":
- "10.00", "shipping_price_gross_amount": "12.30", "token": "af83c25c-bb0e-49a3-acaf-73d88cfeca20",
+ body: '[{"model": "order.order", "pk": 85, "fields": {"created": "2019-09-17T13:55:00.075Z",
+ "status": "unfulfilled", "user": 93, "language_code": "en", "tracking_client_id":
+ "", "billing_address": 355, "shipping_address": 356, "user_email": "[email protected]",
+ "currency": "USD", "shipping_method": 85, "shipping_method_name": "DHL", "shipping_price_net_amount":
+ "10.00", "shipping_price_gross_amount": "12.30", "token": "c71a5c72-7d0a-4505-ac1e-217b877fce24",
"checkout_token": "", "total_net_amount": "80.00", "total_gross_amount": "98.40",
"voucher": null, "discount_amount": "0.00", "discount_name": "", "translated_discount_name":
"", "display_gross_prices": true, "customer_note": "", "weight": "0.0 kg", "gift_cards":
@@ -25,7 +25,7 @@ interactions:
X-Saleor-Event:
- order_created
X-Saleor-HMAC-SHA256:
- - sha1=b6a1c8302e65fb86e0af147e8215708221cb801702bc9323b05ca7c50dffb5f2
+ - sha1=43c77ab2a62add6e6a18dbf3346f87c55c4e50aefebc39f31160764686ed9048
method: POST
uri: https://webhook.site/f0fc9979-cbd4-47b7-8705-1acb03fff1d0
response:
@@ -40,7 +40,7 @@ interactions:
Content-Type:
- text/plain; charset=UTF-8
Date:
- - Mon, 16 Sep 2019 11:26:30 GMT
+ - Tue, 17 Sep 2019 13:55:02 GMT
Server:
- nginx/1.10.3
Transfer-Encoding:
@@ -50,9 +50,9 @@ interactions:
X-RateLimit-Limit:
- '30'
X-RateLimit-Remaining:
- - '29'
+ - '28'
X-Request-Id:
- - 9a670045-2d90-4de5-8d82-8161334b6612
+ - a731d727-0404-4bb9-b3d0-c0ba40491bce
X-Token-Id:
- f0fc9979-cbd4-47b7-8705-1acb03fff1d0
status:
diff --git a/tests/extensions/plugins/test_webhook.py b/tests/extensions/plugins/test_webhook.py
index 0b53422730..c5f64783c1 100644
--- a/tests/extensions/plugins/test_webhook.py
+++ b/tests/extensions/plugins/test_webhook.py
@@ -6,6 +6,10 @@ from django.core.serializers import serialize
from saleor.extensions.manager import get_extensions_manager
from saleor.extensions.plugins.webhook import create_hmac_signature
+from saleor.extensions.plugins.webhook.payloads import (
+ generate_customer_payload,
+ generate_order_payload,
+)
from saleor.extensions.plugins.webhook.tasks import trigger_webhooks_for_event
from saleor.webhook import WebhookEventType
@@ -40,7 +44,7 @@ def test_trigger_webhooks_for_event(
"saleor.extensions.plugins.webhook.tasks.requests.post", wraps=requests.post
)
def test_trigger_webhooks_for_event_with_secret_key(
- mock_request, webhook, settings, order_with_lines, permission_manage_orders
+ mock_request, webhook, order_with_lines, permission_manage_orders
):
webhook.service_account.permissions.add(permission_manage_orders)
webhook.target_url = "https://webhook.site/f0fc9979-cbd4-47b7-8705-1acb03fff1d0"
@@ -70,7 +74,19 @@ def test_postprocess_order_creation(mocked_webhook_trigger, settings, order_with
manager = get_extensions_manager()
manager.postprocess_order_creation(order_with_lines)
- expected_data = serialize("json", [order_with_lines])
+ expected_data = generate_order_payload(order_with_lines)
mocked_webhook_trigger.assert_called_once_with(
WebhookEventType.ORDER_CREATED, expected_data
)
+
+
[email protected]("saleor.extensions.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
+def test_customer_created(mocked_webhook_trigger, settings, customer_user):
+ settings.PLUGINS = ["saleor.extensions.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_extensions_manager()
+ manager.customer_created(customer_user)
+
+ expected_data = generate_customer_payload(customer_user)
+ mocked_webhook_trigger.assert_called_once_with(
+ WebhookEventType.CUSTOMER_CREATED, expected_data
+ )