Skip to content

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

Update after review comments

Maciej Korycinski643bec664c96
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 4a137a3d33..0880ed04ed 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -20,6 +20,7 @@ from ...order.actions import (
cancel_fulfillment,
cancel_order,
clean_mark_order_as_paid,
+ fulfill_order_line,
mark_order_as_paid,
order_shipping_updated,
)
@@ -27,7 +28,6 @@ from ...order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ...order.utils import (
add_variant_to_order,
change_order_line_quantity,
- fulfill_order_line,
recalculate_order,
)
from ...payment import ChargeStatus, CustomPaymentChoices, PaymentError, gateway
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index a8a72de429..f4c239475a 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -13,6 +13,7 @@ from ...order import error_codes as order_error_codes
from ...payment import error_codes as payment_error_codes
from ...product import error_codes as product_error_codes
from ...shipping import error_codes as shipping_error_codes
+from ...webhook import error_codes as webhook_error_codes
from .utils import str_to_enum
# FIXME CoreTaxRateType should be removed after we will drop old api fields dedicated
@@ -82,3 +83,4 @@ PaymentErrorCode = graphene.Enum.from_enum(payment_error_codes.PaymentErrorCode)
ProductErrorCode = graphene.Enum.from_enum(product_error_codes.ProductErrorCode)
ShopErrorCode = graphene.Enum.from_enum(shop_error_codes.ShopErrorCode)
ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)
+WebhookErrorCode = graphene.Enum.from_enum(webhook_error_codes.WebhookErrorCode)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 728306f9c0..b6cecd8c6d 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -14,6 +14,7 @@ from ..enums import (
ProductErrorCode,
ShippingErrorCode,
ShopErrorCode,
+ WebhookErrorCode,
)
from .money import VAT
@@ -77,6 +78,10 @@ class ExtensionsError(Error):
code = ExtensionsErrorCode(description="The error code.")
+class WebhookError(Error):
+ code = WebhookErrorCode(description="The error code.")
+
+
class LanguageDisplay(graphene.ObjectType):
code = LanguageCodeEnum(description="Language code.", required=True)
language = graphene.String(description="Language.", required=True)
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index a8405466bb..e625c8e790 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -5,11 +5,11 @@ from django.utils.translation import npgettext_lazy, pgettext_lazy
from ....order import models
from ....order.actions import (
cancel_fulfillment,
+ fulfill_order_line,
fulfillment_tracking_updated,
order_fulfilled,
)
from ....order.error_codes import OrderErrorCode
-from ....order.utils import fulfill_order_line
from ...core.mutations import BaseMutation
from ...core.types.common import OrderError
from ...order.types import Fulfillment, Order
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 8c041188b2..89b4560674 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4197,6 +4197,7 @@ type WebhookCountableEdge {
type WebhookCreate {
errors: [Error!]
+ webhookErrors: [WebhookError!]
webhook: Webhook
}
@@ -4211,6 +4212,21 @@ input WebhookCreateInput {
type WebhookDelete {
errors: [Error!]
webhook: Webhook
+ webhookErrors: [WebhookError!]
+}
+
+type WebhookError {
+ field: String
+ message: String
+ code: WebhookErrorCode
+}
+
+enum WebhookErrorCode {
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ REQUIRED
+ UNIQUE
}
type WebhookEvent {
@@ -4230,6 +4246,7 @@ enum WebhookEventTypeEnum {
type WebhookUpdate {
errors: [Error!]
webhook: Webhook
+ webhookErrors: [WebhookError!]
}
input WebhookUpdateInput {
diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.py
index b5f74756a2..208b67979b 100644
--- a/saleor/graphql/webhook/mutations.py
+++ b/saleor/graphql/webhook/mutations.py
@@ -2,24 +2,28 @@ import graphene
from django.core.exceptions import ValidationError
from ...webhook import models
+from ...webhook.error_codes import WebhookErrorCode
from ..core.mutations import ModelDeleteMutation, ModelMutation
+from ..core.types.common import WebhookError
from .enums import WebhookEventTypeEnum
from .types import Webhook
class WebhookCreateInput(graphene.InputObjectType):
- target_url = graphene.String(description="The url to receive the payload")
+ target_url = graphene.String(description="The url to receive the payload.")
events = graphene.List(
- WebhookEventTypeEnum, description="The event that webhook wants to subscribe"
+ WebhookEventTypeEnum, description="The events that webhook wants to subscribe."
)
service_account = graphene.ID(
- required=False, description="serviceAccount ID of which webhook belongs to"
+ required=False,
+ description="ID of the service account to which webhook belongs.",
)
is_active = graphene.Boolean(
description="Determine if webhook will be set active or not.", required=False
)
secret_key = graphene.String(
- description="Use to create a hash signature with each payload", required=False
+ description="The secret key used to create a hash signature with each payload.",
+ required=False,
)
@@ -30,9 +34,11 @@ class WebhookCreate(ModelMutation):
)
class Meta:
- description = "Creates a new webhook subscription"
+ description = "Creates a new webhook subscription."
model = models.Webhook
permissions = ("webhook.manage_webhooks",)
+ error_type_class = WebhookError
+ error_type_field = "webhook_errors"
@classmethod
def clean_input(cls, info, instance, data):
@@ -44,7 +50,9 @@ class WebhookCreate(ModelMutation):
# We need to confirm that cleaned_data has service_account_id or
# context has assigned service account instance
if not instance.service_account_id and not service_account:
- raise ValidationError("Missing token or serviceAccount")
+ raise ValidationError(
+ "Missing token or serviceAccount", code=WebhookErrorCode.INVALID
+ )
if instance.service_account_id:
# Let's skip service_account id in case when context has
@@ -54,7 +62,8 @@ class WebhookCreate(ModelMutation):
if not service_account or not service_account.is_active:
raise ValidationError(
- {"serviceAccount": "Service account doesn't exist or is disabled"}
+ "Service account doesn't exist or is disabled",
+ code=WebhookErrorCode.NOT_FOUND,
)
return cleaned_data
@@ -85,15 +94,16 @@ class WebhookCreate(ModelMutation):
class WebhookUpdateInput(graphene.InputObjectType):
target_url = graphene.String(
- description="The url to receive the payload", required=False
+ description="The url to receive the payload.", required=False
)
events = graphene.List(
WebhookEventTypeEnum,
- description="The event that webhook wants to subscribe",
+ description="The events that webhook wants to subscribe.",
required=False,
)
service_account = graphene.ID(
- required=False, description="serviceAccount ID of which webhook belongs to"
+ required=False,
+ description="ID of the service account to which webhook belongs.",
)
is_active = graphene.Boolean(
description="Determine if webhook will be set active or not.", required=False
@@ -113,9 +123,11 @@ class WebhookUpdate(ModelMutation):
)
class Meta:
- description = "Updates a webhook subscription"
+ description = "Updates a webhook subscription."
model = models.Webhook
permissions = ("webhook.manage_webhooks",)
+ error_type_class = WebhookError
+ error_type_field = "webhook_errors"
class WebhookDelete(ModelDeleteMutation):
@@ -128,6 +140,8 @@ class WebhookDelete(ModelDeleteMutation):
description = "Deletes a webhook subscription."
model = models.Webhook
permissions = ("webhook.manage_webhooks",)
+ error_type_class = WebhookError
+ error_type_field = "webhook_errors"
@classmethod
def check_permissions(cls, context):
@@ -144,16 +158,15 @@ class WebhookDelete(ModelDeleteMutation):
if service_account:
if not service_account.is_active:
raise ValidationError(
- {
- "serviceAccount": "Service account needs to be active to "
- "delete webhook"
- }
+ "Service account needs to be active to delete webhook",
+ code=WebhookErrorCode.INVALID,
)
try:
service_account.webhooks.get(id=object_id)
except models.Webhook.DoesNotExist:
raise ValidationError(
- {"id": "Couldn't resolve to a node: %s" % node_id}
+ "Couldn't resolve to a node: %s" % node_id,
+ code=WebhookErrorCode.GRAPHQL_ERROR,
)
return super().perform_mutation(_root, info, **data)
diff --git a/saleor/graphql/webhook/schema.py b/saleor/graphql/webhook/schema.py
index 81bd6b2d6c..83670b3570 100644
--- a/saleor/graphql/webhook/schema.py
+++ b/saleor/graphql/webhook/schema.py
@@ -9,7 +9,9 @@ from .types import Webhook
class WebhookQueries(graphene.ObjectType):
webhook = graphene.Field(
Webhook,
- id=graphene.Argument(graphene.ID, required=True),
+ id=graphene.Argument(
+ graphene.ID, required=True, description="ID of the webhook"
+ ),
description="Lookup a webhook by ID.",
)
webhooks = PrefetchingConnectionField(Webhook, description="List of webhooks")
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index d8521548b3..04ba227143 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -8,12 +8,19 @@ from django.utils.translation import pgettext_lazy
from ..core import analytics
from ..extensions.manager import get_extensions_manager
from ..payment import ChargeStatus, CustomPaymentChoices, PaymentError
-from . import FulfillmentStatus, OrderStatus, events, utils
+from ..product.utils import decrease_stock
+from . import FulfillmentStatus, OrderStatus, emails, events, utils
from .emails import send_fulfillment_confirmation_to_customer, send_payment_confirmation
-from .utils import recalculate_order, restock_fulfillment_lines, update_order_status
+from .models import Fulfillment, FulfillmentLine
+from .utils import (
+ order_line_needs_automatic_fulfillment,
+ recalculate_order,
+ restock_fulfillment_lines,
+ update_order_status,
+)
if TYPE_CHECKING:
- from .models import Order, Fulfillment
+ from .models import Order
from ..account.models import User, Address
from ..payment.models import Payment
@@ -37,7 +44,7 @@ def handle_fully_paid_order(order: "Order"):
send_payment_confirmation.delay(order.pk)
if utils.order_needs_automatic_fullfilment(order):
- utils.automatically_fulfill_digital_lines(order)
+ automatically_fulfill_digital_lines(order)
try:
analytics.report_order(order.tracking_client_id, order)
except Exception:
@@ -207,3 +214,40 @@ def clean_mark_order_as_paid(order: "Order"):
"Orders with payments can not be manually marked as paid.",
)
)
+
+
+def fulfill_order_line(order_line, quantity):
+ """Fulfill order line with given quantity."""
+ if order_line.variant and order_line.variant.track_inventory:
+ decrease_stock(order_line.variant, quantity)
+ order_line.quantity_fulfilled += quantity
+ order_line.save(update_fields=["quantity_fulfilled"])
+
+
+def automatically_fulfill_digital_lines(order: "Order"):
+ """Fulfill all digital lines which have enabled automatic fulfillment setting.
+
+ Send confirmation email afterward.
+ """
+ digital_lines = order.lines.filter(
+ is_shipping_required=False, variant__digital_content__isnull=False
+ )
+ digital_lines = digital_lines.prefetch_related("variant__digital_content")
+
+ if not digital_lines:
+ return
+ fulfillment, _ = Fulfillment.objects.get_or_create(order=order)
+ for line in digital_lines:
+ if not order_line_needs_automatic_fulfillment(line):
+ continue
+ digital_content = line.variant.digital_content
+ digital_content.urls.create(line=line)
+ quantity = line.quantity
+ FulfillmentLine.objects.create(
+ fulfillment=fulfillment, order_line=line, quantity=quantity
+ )
+ fulfill_order_line(order_line=line, quantity=quantity)
+ emails.send_fulfillment_confirmation_to_customer(
+ order, fulfillment, user=order.user
+ )
+ update_order_status(order)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 6472807742..4a8c2d3b28 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -13,14 +13,9 @@ from ..core.weight import zero_weight
from ..dashboard.order.utils import get_voucher_discount_for_order
from ..discount.models import NotApplicable
from ..extensions.manager import get_extensions_manager
-from ..order import OrderStatus, emails
-from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
-from ..product.utils import (
- allocate_stock,
- deallocate_stock,
- decrease_stock,
- increase_stock,
-)
+from ..order import OrderStatus
+from ..order.models import Order, OrderLine
+from ..product.utils import allocate_stock, deallocate_stock, increase_stock
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.models import ShippingMethod
from . import events
@@ -46,43 +41,6 @@ def order_needs_automatic_fullfilment(order: Order) -> bool:
return False
-def fulfill_order_line(order_line, quantity):
- """Fulfill order line with given quantity."""
- if order_line.variant and order_line.variant.track_inventory:
- decrease_stock(order_line.variant, quantity)
- order_line.quantity_fulfilled += quantity
- order_line.save(update_fields=["quantity_fulfilled"])
-
-
-def automatically_fulfill_digital_lines(order: Order):
- """Fulfill all digital lines which have enabled automatic fulfillment setting.
-
- Send confirmation email afterward.
- """
- digital_lines = order.lines.filter(
- is_shipping_required=False, variant__digital_content__isnull=False
- )
- digital_lines = digital_lines.prefetch_related("variant__digital_content")
-
- if not digital_lines:
- return
- fulfillment, _ = Fulfillment.objects.get_or_create(order=order)
- for line in digital_lines:
- if not order_line_needs_automatic_fulfillment(line):
- continue
- digital_content = line.variant.digital_content
- digital_content.urls.create(line=line)
- quantity = line.quantity
- FulfillmentLine.objects.create(
- fulfillment=fulfillment, order_line=line, quantity=quantity
- )
- fulfill_order_line(order_line=line, quantity=quantity)
- emails.send_fulfillment_confirmation_to_customer(
- order, fulfillment, user=order.user
- )
- update_order_status(order)
-
-
def check_order_status(func):
"""Check if order meets preconditions of payment process.
diff --git a/tests/api/test_webhook.py b/tests/api/test_webhook.py
index 0de687d350..6a3733a7d9 100644
--- a/tests/api/test_webhook.py
+++ b/tests/api/test_webhook.py
@@ -163,9 +163,10 @@ def test_webhook_create_by_staff_without_permission(staff_api_client, service_ac
WEBHOOK_DELETE_BY_SERVICE_ACCOUNT = """
mutation webhookDelete($id: ID!){
webhookDelete(id: $id){
- errors{
+ webhookErrors{
field
message
+ code
}
}
}
@@ -208,8 +209,8 @@ def test_webhook_delete_by_service_account_wrong_webhook(
response = service_account_api_client.post_graphql(query, variables=variables)
content = get_graphql_content(response)
- errors = content["data"]["webhookDelete"]["errors"]
- assert errors[0]["field"] == "id"
+ errors = content["data"]["webhookDelete"]["webhookErrors"]
+ assert errors[0]["code"] == "GRAPHQL_ERROR"
def test_webhook_delete_by_inactive_service_account(
diff --git a/tests/conftest.py b/tests/conftest.py
index 4c769d7ec6..8851b89e3c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -27,9 +27,10 @@ from saleor.giftcard.models import GiftCard
from saleor.menu.models import Menu, MenuItem
from saleor.menu.utils import update_menu
from saleor.order import OrderStatus
+from saleor.order.actions import fulfill_order_line
from saleor.order.events import OrderEvents
from saleor.order.models import FulfillmentStatus, Order, OrderEvent
-from saleor.order.utils import fulfill_order_line, recalculate_order
+from saleor.order.utils import recalculate_order
from saleor.page.models import Page
from saleor.payment import ChargeStatus, TransactionKind
from saleor.payment.models import Payment
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index 93e0dface5..91506c7406 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -1044,7 +1044,7 @@ def test_view_mark_order_as_paid(admin_client, order_with_lines):
).exists()
-@patch("saleor.order.utils.emails.send_fulfillment_confirmation")
+@patch("saleor.order.actions.emails.send_fulfillment_confirmation")
@pytest.mark.parametrize(
"has_standard,has_digital", ((True, True), (True, False), (False, True))
)
diff --git a/tests/test_order.py b/tests/test_order.py
index 50efc2d378..1e93303f4b 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -12,14 +12,12 @@ from saleor.core.exceptions import InsufficientStock
from saleor.core.weight import zero_weight
from saleor.discount.utils import validate_voucher_in_order
from saleor.order import OrderStatus, events as order_events, models
-from saleor.order.models import Fulfillment, Order
+from saleor.order.models import Order
from saleor.order.templatetags.order_lines import display_translated_order_line_name
from saleor.order.utils import (
add_variant_to_order,
- automatically_fulfill_digital_lines,
change_order_line_quantity,
delete_order_line,
- fulfill_order_line,
recalculate_order,
restock_fulfillment_lines,
restock_order_lines,
@@ -28,8 +26,8 @@ from saleor.order.utils import (
)
from saleor.payment import ChargeStatus
from saleor.payment.models import Payment
-from saleor.product.models import DigitalContent
-from tests.utils import create_image, get_redirect_location
+
+from .utils import get_redirect_location
def test_total_setter():
@@ -610,76 +608,6 @@ def test_get_order_weight_non_existing_product(order_with_lines, product):
assert old_weight == new_weight
-@patch("saleor.order.utils.emails.send_fulfillment_confirmation")
-@patch("saleor.order.utils.get_default_digital_content_settings")
-def test_fulfill_digital_lines(
- mock_digital_settings, mock_email_fulfillment, order_with_lines, media_root
-):
- mock_digital_settings.return_value = {"automatic_fulfillment": True}
- line = order_with_lines.lines.all()[0]
-
- image_file, image_name = create_image()
- variant = line.variant
- digital_content = DigitalContent.objects.create(
- content_file=image_file, product_variant=variant, use_default_settings=True
- )
-
- line.variant.digital_content = digital_content
- line.is_shipping_required = False
- line.save()
-
- order_with_lines.refresh_from_db()
- automatically_fulfill_digital_lines(order_with_lines)
- line.refresh_from_db()
- fulfillment = Fulfillment.objects.get(order=order_with_lines)
- fulfillment_lines = fulfillment.lines.all()
-
- assert fulfillment_lines.count() == 1
- assert line.digital_content_url
- assert mock_email_fulfillment.delay.called
-
-
-def test_fulfill_order_line(order_with_lines):
- order = order_with_lines
- line = order.lines.first()
- quantity_fulfilled_before = line.quantity_fulfilled
- variant = line.variant
- stock_quantity_after = variant.quantity - line.quantity
-
- fulfill_order_line(line, line.quantity)
-
- variant.refresh_from_db()
- assert variant.quantity == stock_quantity_after
- assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity
-
-
-def test_fulfill_order_line_with_variant_deleted(order_with_lines):
- line = order_with_lines.lines.first()
- line.variant.delete()
-
- line.refresh_from_db()
-
- fulfill_order_line(line, line.quantity)
-
-
-def test_fulfill_order_line_without_inventory_tracking(order_with_lines):
- order = order_with_lines
- line = order.lines.first()
- quantity_fulfilled_before = line.quantity_fulfilled
- variant = line.variant
- variant.track_inventory = False
- variant.save()
-
- # stock should not change
- stock_quantity_after = variant.quantity
-
- fulfill_order_line(line, line.quantity)
-
- variant.refresh_from_db()
- assert variant.quantity == stock_quantity_after
- assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity
-
-
@patch("saleor.discount.utils.validate_voucher")
def test_get_voucher_discount_for_order_voucher_validation(
mock_validate_voucher, voucher, order_with_lines
diff --git a/tests/test_order_actions.py b/tests/test_order_actions.py
index fbce78b30f..38a8ab9e7a 100644
--- a/tests/test_order_actions.py
+++ b/tests/test_order_actions.py
@@ -6,13 +6,19 @@ from prices import Money, TaxedMoney
from saleor.order import FulfillmentStatus, OrderEvents, OrderEventsEmails, OrderStatus
from saleor.order.actions import (
+ automatically_fulfill_digital_lines,
cancel_fulfillment,
cancel_order,
clean_mark_order_as_paid,
+ fulfill_order_line,
handle_fully_paid_order,
mark_order_as_paid,
)
+from saleor.order.models import Fulfillment
from saleor.payment import ChargeStatus, PaymentError
+from saleor.product.models import DigitalContent
+
+from .utils import create_image
@pytest.fixture
@@ -141,3 +147,73 @@ def test_cancel_order(fulfilled_order):
]
)
assert fulfilled_order.status == OrderStatus.CANCELED
+
+
+def test_fulfill_order_line(order_with_lines):
+ order = order_with_lines
+ line = order.lines.first()
+ quantity_fulfilled_before = line.quantity_fulfilled
+ variant = line.variant
+ stock_quantity_after = variant.quantity - line.quantity
+
+ fulfill_order_line(line, line.quantity)
+
+ variant.refresh_from_db()
+ assert variant.quantity == stock_quantity_after
+ assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity
+
+
+def test_fulfill_order_line_with_variant_deleted(order_with_lines):
+ line = order_with_lines.lines.first()
+ line.variant.delete()
+
+ line.refresh_from_db()
+
+ fulfill_order_line(line, line.quantity)
+
+
+def test_fulfill_order_line_without_inventory_tracking(order_with_lines):
+ order = order_with_lines
+ line = order.lines.first()
+ quantity_fulfilled_before = line.quantity_fulfilled
+ variant = line.variant
+ variant.track_inventory = False
+ variant.save()
+
+ # stock should not change
+ stock_quantity_after = variant.quantity
+
+ fulfill_order_line(line, line.quantity)
+
+ variant.refresh_from_db()
+ assert variant.quantity == stock_quantity_after
+ assert line.quantity_fulfilled == quantity_fulfilled_before + line.quantity
+
+
+@patch("saleor.order.actions.emails.send_fulfillment_confirmation")
+@patch("saleor.order.utils.get_default_digital_content_settings")
+def test_fulfill_digital_lines(
+ mock_digital_settings, mock_email_fulfillment, order_with_lines, media_root
+):
+ mock_digital_settings.return_value = {"automatic_fulfillment": True}
+ line = order_with_lines.lines.all()[0]
+
+ image_file, image_name = create_image()
+ variant = line.variant
+ digital_content = DigitalContent.objects.create(
+ content_file=image_file, product_variant=variant, use_default_settings=True
+ )
+
+ line.variant.digital_content = digital_content
+ line.is_shipping_required = False
+ line.save()
+
+ order_with_lines.refresh_from_db()
+ automatically_fulfill_digital_lines(order_with_lines)
+ line.refresh_from_db()
+ fulfillment = Fulfillment.objects.get(order=order_with_lines)
+ fulfillment_lines = fulfillment.lines.all()
+
+ assert fulfillment_lines.count() == 1
+ assert line.digital_content_url
+ assert mock_email_fulfillment.delay.called