Skip to content

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

Update draft order validation (#7253)

Iga Karbowiake626a1bda7ef
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 298fd6b0d6..bcd3b9a13e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -117,6 +117,9 @@ All notable, unreleased changes to this project will be documented in this file.
- Add file format validation for uploaded images - #7447 by @IKarbowiak
- Add boolean attributes - #7454 by @piotrgrundas
- Fix attaching params for address form errors - #7485 by @IKarbowiak
+- Update draft order validation - #7253 by @IKarbowiak
+ - Extend Order type with errors: [OrderError!]! field
+ - Create tasks for deleting order lines by deleting products or variants
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 5434b84c8d..8e0ef149b9 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -75,7 +75,7 @@ class SetPassword(CreateToken):
try:
cls._set_password_for_user(email, password, token)
except ValidationError as e:
- errors = validation_error_to_error_type(e)
+ errors = validation_error_to_error_type(e, AccountError)
return cls.handle_typed_errors(errors)
return super().mutate(root, info, **data)
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index f3a34e0c49..80d02378a0 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -20,7 +20,7 @@ from ...core.exceptions import PermissionDenied
from ...core.permissions import AccountPermissions
from ..decorators import staff_member_or_app_required
from ..utils import get_nodes, resolve_global_ids_to_primary_keys
-from .types import Error, File, Upload
+from .types import File, Upload
from .types.common import UploadError
from .utils import from_global_id_or_error, snake_to_camel_case
from .utils.error_codes import get_error_code_from_error
@@ -48,34 +48,46 @@ def get_error_fields(error_type_class, error_type_field, deprecation_reason=None
return {error_type_field: error_field}
-def validation_error_to_error_type(validation_error: ValidationError) -> list:
+def validation_error_to_error_type(
+ validation_error: ValidationError, error_type_class
+) -> list:
"""Convert a ValidationError into a list of Error types."""
err_list = []
+ error_class_fields = set(error_type_class._meta.fields.keys())
if hasattr(validation_error, "error_dict"):
# convert field errors
for field, field_errors in validation_error.error_dict.items():
field = None if field == NON_FIELD_ERRORS else snake_to_camel_case(field)
for err in field_errors:
- err_list.append(
- (
- Error(field=field, message=err.messages[0]),
- get_error_code_from_error(err),
- err.params,
- )
+ error = error_type_class(
+ field=field,
+ message=err.messages[0],
+ code=get_error_code_from_error(err),
)
+ attach_error_params(error, err.params, error_class_fields)
+ err_list.append(error)
else:
# convert non-field errors
for err in validation_error.error_list:
- err_list.append(
- (
- Error(message=err.messages[0]),
- get_error_code_from_error(err),
- err.params,
- )
+ error = error_type_class(
+ message=err.messages[0],
+ code=get_error_code_from_error(err),
)
+ attach_error_params(error, err.params, error_class_fields)
+ err_list.append(error)
return err_list
+def attach_error_params(error, params: dict, error_class_fields: set):
+ if not params:
+ return {}
+ # If some of the params key overlap with error class fields
+ # attach param value to the error
+ error_fields_in_params = set(params.keys()) & error_class_fields
+ for error_field in error_fields_in_params:
+ setattr(error, error_field, params[error_field])
+
+
class ModelMutationOptions(MutationOptions):
exclude = None
model = None
@@ -338,30 +350,15 @@ class BaseMutation(graphene.Mutation):
@classmethod
def handle_errors(cls, error: ValidationError, **extra):
- errors = validation_error_to_error_type(error)
- return cls.handle_typed_errors(errors, **extra)
+ error_list = validation_error_to_error_type(error, cls._meta.error_type_class)
+ return cls.handle_typed_errors(error_list, **extra)
@classmethod
def handle_typed_errors(cls, errors: list, **extra):
"""Return class instance with errors."""
-
- typed_errors = []
- error_class_fields = set(cls._meta.error_type_class._meta.fields.keys())
- for e, code, params in errors:
- error_instance = cls._meta.error_type_class(
- field=e.field, message=e.message, code=code
- )
- if params:
- # If some of the params key overlap with error class fields
- # attach param value to the error
- error_fields_in_params = set(params.keys()) & error_class_fields
- for error_field in error_fields_in_params:
- setattr(error_instance, error_field, params[error_field])
- typed_errors.append(error_instance)
-
if cls._meta.error_type_field is not None:
- extra.update({cls._meta.error_type_field: typed_errors})
- return cls(errors=typed_errors, **extra)
+ extra.update({cls._meta.error_type_field: errors})
+ return cls(errors=errors, **extra)
class ModelMutation(BaseMutation):
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 8d39bfa0bc..98c08c09cb 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -176,8 +176,9 @@ class OrderError(Error):
description="Warehouse ID which causes the error.",
required=False,
)
- order_line = graphene.ID(
- description="Order line ID which causes the error.",
+ order_lines = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of order line IDs that cause the error.",
required=False,
)
variants = graphene.List(
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 8e004311e5..2dcaa6c2c6 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -116,7 +116,7 @@ class OrderFulfill(BaseMutation):
"order_line_id": ValidationError(
msg,
code=OrderErrorCode.FULFILL_ORDER_LINE,
- params={"order_line": order_line_global_id},
+ params={"order_lines": [order_line_global_id]},
)
}
)
@@ -145,7 +145,7 @@ class OrderFulfill(BaseMutation):
"orderLineId": ValidationError(
"Duplicated order line ID.",
code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
- params={"order_line": duplicates.pop()},
+ params={"order_lines": [duplicates.pop()]},
)
}
)
diff --git a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
index 3cde2cb17e..ad9d08878b 100644
--- a/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
+++ b/saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py
@@ -42,7 +42,7 @@ def test_fulfillment_refund_products_order_lines(
code
message
warehouse
- orderLine
+ orderLines
}
}
}
@@ -121,7 +121,7 @@ def test_fulfillment_return_products_order_lines(
code
message
warehouse
- orderLine
+ orderLines
}
}
}
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index a1a904183d..148285a71a 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -24,7 +24,7 @@ mutation fulfillOrder(
code
message
warehouse
- orderLine
+ orderLines
}
}
}
@@ -324,7 +324,7 @@ def test_order_fulfill_zero_quantity(
error = data["errors"][0]
assert error["field"] == "lines"
assert error["code"] == OrderErrorCode.ZERO_QUANTITY.name
- assert not error["orderLine"]
+ assert not error["orderLines"]
assert not error["warehouse"]
mock_create_fulfillments.assert_not_called()
@@ -400,7 +400,7 @@ def test_order_fulfill_fulfilled_order(
error = data["errors"][0]
assert error["field"] == "orderLineId"
assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name
- assert error["orderLine"] == order_line_id
+ assert error["orderLines"] == [order_line_id]
assert not error["warehouse"]
mock_create_fulfillments.assert_not_called()
@@ -453,7 +453,7 @@ def test_order_fulfill_warehouse_with_insufficient_stock_exception(
error = data["errors"][0]
assert error["field"] == "stocks"
assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name
- assert error["orderLine"] == order_line_id
+ assert error["orderLines"] == [order_line_id]
assert error["warehouse"] == warehouse_id
@@ -494,7 +494,7 @@ def test_order_fulfill_warehouse_duplicated_warehouse_id(
error = data["errors"][0]
assert error["field"] == "warehouse"
assert error["code"] == OrderErrorCode.DUPLICATED_INPUT_ITEM.name
- assert not error["orderLine"]
+ assert not error["orderLines"]
assert error["warehouse"] == warehouse_id
mock_create_fulfillments.assert_not_called()
@@ -537,7 +537,7 @@ def test_order_fulfill_warehouse_duplicated_order_line_id(
error = data["errors"][0]
assert error["field"] == "orderLineId"
assert error["code"] == OrderErrorCode.DUPLICATED_INPUT_ITEM.name
- assert error["orderLine"] == order_line_id
+ assert error["orderLines"] == [order_line_id]
assert not error["warehouse"]
mock_create_fulfillments.assert_not_called()
diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
index b95be216ea..6fd56db3a3 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -35,7 +35,7 @@ mutation OrderFulfillmentRefundProducts(
code
message
warehouse
- orderLine
+ orderLines
}
}
}
diff --git a/saleor/graphql/order/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
index 68c4e759a2..a249080b25 100644
--- a/saleor/graphql/order/tests/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -57,7 +57,7 @@ mutation OrderFulfillmentReturnProducts(
code
message
warehouse
- orderLine
+ orderLines
}
}
}
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 31b1f38427..7cae8419a2 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -2444,6 +2444,14 @@ ORDER_CAN_FINALIZE_QUERY = """
query OrderQuery($id: ID!){
order(id: $id){
canFinalize
+ errors {
+ code
+ field
+ message
+ warehouse
+ orderLines
+ variants
+ }
}
}
"""
@@ -2456,6 +2464,7 @@ def test_can_finalize_order(staff_api_client, permission_manage_orders, draft_or
response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)
content = get_graphql_content(response)
assert content["data"]["order"]["canFinalize"] is True
+ assert not content["data"]["order"]["errors"]
def test_can_finalize_order_invalid_shipping_method_set(
@@ -2468,6 +2477,13 @@ def test_can_finalize_order_invalid_shipping_method_set(
response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)
content = get_graphql_content(response)
assert content["data"]["order"]["canFinalize"] is False
+ errors = content["data"]["order"]["errors"]
+ assert len(errors) == 3
+ assert {error["code"] for error in errors} == {
+ OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name,
+ OrderErrorCode.INSUFFICIENT_STOCK.name,
+ }
+ assert {error["field"] for error in errors} == {"shipping", "lines"}
def test_can_finalize_order_no_order_lines(
@@ -2481,6 +2497,10 @@ def test_can_finalize_order_no_order_lines(
response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)
content = get_graphql_content(response)
assert content["data"]["order"]["canFinalize"] is False
+ errors = content["data"]["order"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "lines"
def test_can_finalize_order_product_unavailable_for_purchase(
@@ -2492,7 +2512,8 @@ def test_can_finalize_order_product_unavailable_for_purchase(
order.status = OrderStatus.DRAFT
order.save(update_fields=["status"])
- product = order.lines.first().variant.product
+ line = order.lines.first()
+ product = line.variant.product
product.channel_listings.update(available_for_purchase=None)
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -2505,6 +2526,11 @@ def test_can_finalize_order_product_unavailable_for_purchase(
# then
content = get_graphql_content(response)
assert content["data"]["order"]["canFinalize"] is False
+ errors = content["data"]["order"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["orderLines"] == [graphene.Node.to_global_id("OrderLine", line.pk)]
def test_can_finalize_order_product_available_for_purchase_from_tomorrow(
@@ -2516,7 +2542,8 @@ def test_can_finalize_order_product_available_for_purchase_from_tomorrow(
order.status = OrderStatus.DRAFT
order.save(update_fields=["status"])
- product = order.lines.first().variant.product
+ line = order.lines.first()
+ product = line.variant.product
product.channel_listings.update(
available_for_purchase=date.today() + timedelta(days=1)
)
@@ -2531,6 +2558,11 @@ def test_can_finalize_order_product_available_for_purchase_from_tomorrow(
# then
content = get_graphql_content(response)
assert content["data"]["order"]["canFinalize"] is False
+ errors = content["data"]["order"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["orderLines"] == [graphene.Node.to_global_id("OrderLine", line.pk)]
def test_validate_draft_order(draft_order):
@@ -2587,7 +2619,7 @@ def test_validate_draft_order_with_unpublished_product(draft_order):
error = e.value.error_dict["lines"][0]
assert error.message == msg
- assert error.code == OrderErrorCode.PRODUCT_NOT_PUBLISHED
+ assert error.code == OrderErrorCode.PRODUCT_NOT_PUBLISHED.value
def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order):
@@ -2603,7 +2635,7 @@ def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order)
error = e.value.error_dict["lines"][0]
assert error.message == msg
- assert error.code == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE
+ assert error.code == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.value
def test_validate_draft_order_with_product_available_for_purchase_in_future(
@@ -2623,7 +2655,7 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(
error = e.value.error_dict["lines"][0]
assert error.message == msg
- assert error.code == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE
+ assert error.code == OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.value
def test_validate_draft_order_out_of_stock_variant(draft_order):
@@ -2649,7 +2681,7 @@ def test_validate_draft_order_no_shipping_address(draft_order):
validate_draft_order(order, "US")
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no shipping address."
- assert error.code.value == OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value
+ assert error.code == OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value
def test_validate_draft_order_no_billing_address(draft_order):
@@ -2660,7 +2692,7 @@ def test_validate_draft_order_no_billing_address(draft_order):
validate_draft_order(order, "US")
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no billing address."
- assert error.code.value == OrderErrorCode.BILLING_ADDRESS_NOT_SET.value
+ assert error.code == OrderErrorCode.BILLING_ADDRESS_NOT_SET.value
def test_validate_draft_order_no_shipping_method(draft_order):
@@ -2671,7 +2703,7 @@ def test_validate_draft_order_no_shipping_method(draft_order):
validate_draft_order(order, "US")
error = e.value.error_dict["shipping"][0]
assert error.message == "Shipping method is required."
- assert error.code.value == OrderErrorCode.SHIPPING_METHOD_REQUIRED.value
+ assert error.code == OrderErrorCode.SHIPPING_METHOD_REQUIRED.value
def test_validate_draft_order_no_shipping_method_shipping_not_required(draft_order):
@@ -2870,11 +2902,13 @@ def test_draft_order_complete_channel_without_shipping_zones(
)
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
- assert len(data["errors"]) == 1
- assert (
- data["errors"][0]["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
- )
- assert data["errors"][0]["field"] == "shipping"
+
+ assert len(data["errors"]) == 3
+ assert {error["code"] for error in data["errors"]} == {
+ OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name,
+ OrderErrorCode.INSUFFICIENT_STOCK.name,
+ }
+ assert {error["field"] for error in data["errors"]} == {"shipping", "lines"}
def test_draft_order_complete_product_without_inventory_tracking(
@@ -2954,11 +2988,13 @@ def test_draft_order_complete_not_available_shipping_method(
data = content["data"]["draftOrderComplete"]["order"]
content = get_graphql_content(response)
data = content["data"]["draftOrderComplete"]
- assert len(data["errors"]) == 1
- assert (
- data["errors"][0]["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
- )
- assert data["errors"][0]["field"] == "shipping"
+
+ assert len(data["errors"]) == 3
+ assert {error["code"] for error in data["errors"]} == {
+ OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name,
+ OrderErrorCode.INSUFFICIENT_STOCK.name,
+ }
+ assert {error["field"] for error in data["errors"]} == {"shipping", "lines"}
def test_draft_order_complete_out_of_stock_variant(
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 76857d59a3..f8a6660f70 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -37,8 +37,9 @@ from ..channel import ChannelContext
from ..channel.dataloaders import ChannelByIdLoader, ChannelByOrderLineIdLoader
from ..core.connection import CountableDjangoObjectType
from ..core.enums import LanguageCodeEnum
+from ..core.mutations import validation_error_to_error_type
from ..core.scalars import PositiveDecimal
-from ..core.types.common import Image
+from ..core.types.common import Image, OrderError
from ..core.types.money import Money, TaxedMoney
from ..core.utils import str_to_enum
from ..decorators import one_of_permissions_required, permission_required
@@ -683,6 +684,12 @@ class Order(CountableDjangoObjectType):
description="List of all discounts assigned to the order.",
required=False,
)
+ errors = graphene.List(
+ graphene.NonNull(OrderError),
+ description="List of errors that occurred during order validation.",
+ default_value=[],
+ required=True,
+ )
class Meta:
description = "Represents an order in the shop."
@@ -1104,3 +1111,13 @@ class Order(CountableDjangoObjectType):
if not root.original_id:
return None
return graphene.Node.to_global_id("Order", root.original_id)
+
+ @traced_resolver
+ def resolve_errors(root, _info, **_kwargs):
+ if root.status == OrderStatus.DRAFT:
+ country = get_order_country(root)
+ try:
+ validate_draft_order(root, country)
+ except ValidationError as e:
+ return validation_error_to_error_type(e, OrderError)
+ return []
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index a4ca5ee2b7..06d6a626c4 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,3 +1,6 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, Dict, Iterable, List
+
import graphene
from django.core.exceptions import ValidationError
@@ -7,127 +10,121 @@ from ...product.models import Product, ProductVariant
from ...warehouse.availability import check_stock_quantity
from ..core.validators import validate_variants_available_in_channel
+if TYPE_CHECKING:
+ from ...channel.models import Channel
+ from ...order.models import Order
+
+T_ERRORS = Dict[str, List[ValidationError]]
-def validate_total_quantity(order):
+
+def validate_total_quantity(order: "Order", errors: T_ERRORS):
if order.get_total_quantity() == 0:
- raise ValidationError(
- {
- "lines": ValidationError(
- "Could not create order without any products.",
- code=OrderErrorCode.REQUIRED,
- )
- }
+ errors["lines"].append(
+ ValidationError(
+ "Could not create order without any products.",
+ code=OrderErrorCode.REQUIRED.value,
+ )
)
-def validate_shipping_method(order):
+def validate_shipping_method(order: "Order", errors: T_ERRORS):
+ error = None
if not order.shipping_method:
- raise ValidationError(
- {
- "shipping": ValidationError(
- "Shipping method is required.",
- code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
- )
- }
+ error = ValidationError(
+ "Shipping method is required.",
+ code=OrderErrorCode.SHIPPING_METHOD_REQUIRED.value,
)
- if (
- order.shipping_address.country.code
+ elif (
+ order.shipping_address
+ and order.shipping_address.country.code
not in order.shipping_method.shipping_zone.countries
):
- raise ValidationError(
- {
- "shipping": ValidationError(
- "Shipping method is not valid for chosen shipping address",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE,
- )
- }
+ error = ValidationError(
+ "Shipping method is not valid for chosen shipping address",
+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
- if not order.shipping_method.shipping_zone.channels.filter(id=order.channel_id):
- raise ValidationError(
- {
- "shipping": ValidationError(
- "Shipping method not available in given channel.",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE,
- )
- }
+ elif not order.shipping_method.shipping_zone.channels.filter(id=order.channel_id):
+ error = ValidationError(
+ "Shipping method not available in given channel.",
+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
+ if error:
+ errors["shipping"].append(error)
-def validate_billing_address(order):
+def validate_billing_address(order: "Order", errors: T_ERRORS):
if not order.billing_address:
- raise ValidationError(
- {
- "order": ValidationError(
- "Can't finalize draft with no billing address.",
- code=OrderErrorCode.BILLING_ADDRESS_NOT_SET,
- )
- }
+ errors["order"].append(
+ ValidationError(
+ "Can't finalize draft with no billing address.",
+ code=OrderErrorCode.BILLING_ADDRESS_NOT_SET.value,
+ )
)
-def validate_shipping_address(order):
+def validate_shipping_address(order: "Order", errors: T_ERRORS):
if not order.shipping_address:
- raise ValidationError(
- {
- "order": ValidationError(
- "Can't finalize draft with no shipping address.",
- code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS,
- )
- }
+ errors["order"].append(
+ ValidationError(
+ "Can't finalize draft with no shipping address.",
+ code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value,
+ )
)
-def validate_order_lines(order, country):
+def validate_order_lines(order: "Order", country: str, errors: T_ERRORS):
for line in order.lines.all():
if line.variant is None:
- raise ValidationError(
- {
- "lines": ValidationError(
- "Could not create orders with non-existing products.",
- code=OrderErrorCode.NOT_FOUND,
- )
- }
+ errors["lines"].append(
+ ValidationError(
+ "Could not create orders with non-existing products.",
+ code=OrderErrorCode.NOT_FOUND.value,
+ )
)
- if line.variant.track_inventory:
+ elif line.variant.track_inventory:
try:
check_stock_quantity(
line.variant, country, order.channel.slug, line.quantity
)
except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"lines": errors})
+ errors["lines"].extend(
+ prepare_insufficient_stock_order_validation_errors(exc)
+ )
-def validate_variants_is_available(order):
+def validate_variants_is_available(order: "Order", errors: T_ERRORS):
variants_ids = {line.variant_id for line in order.lines.all()}
- validate_variants_available_in_channel(
- variants_ids, order.channel_id, OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL
- )
+ try:
+ validate_variants_available_in_channel(
+ variants_ids, order.channel_id, OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL
+ )
+ except ValidationError as e:
+ errors["lines"].extend(e.error_dict["lines"])
-def validate_product_is_published(order):
+def validate_product_is_published(order: "Order", errors: T_ERRORS):
variant_ids = [line.variant_id for line in order.lines.all()]
unpublished_product = Product.objects.filter(
variants__id__in=variant_ids
).not_published(order.channel.slug)
if unpublished_product.exists():
- raise ValidationError(
- {
- "lines": ValidationError(
- "Can't finalize draft with unpublished product.",
- code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,
- )
- }
+ errors["lines"].append(
+ ValidationError(
+ "Can't finalize draft with unpublished product.",
+ code=OrderErrorCode.PRODUCT_NOT_PUBLISHED.value,
+ )
)
-def validate_product_is_published_in_channel(variants, channel):
+def validate_product_is_published_in_channel(
+ variants: Iterable[ProductVariant], channel: "Channel"
+):
if not channel:
raise ValidationError(
{
"channel": ValidationError(
"Can't add product variant for draft order without channel",
- code=OrderErrorCode.REQUIRED,
+ code=OrderErrorCode.REQUIRED.value,
)
}
)
@@ -148,20 +145,22 @@ def validate_product_is_published_in_channel(variants, channel):
"lines": ValidationError(
"Can't add product variant that are not published in "
"the channel associated with this draft order.",
- code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,
+ code=OrderErrorCode.PRODUCT_NOT_PUBLISHED.value,
params={"variants": unpublished_variants_global_ids},
)
}
)
-def validate_variant_channel_listings(variants, channel):
+def validate_variant_channel_listings(
+ variants: Iterable[ProductVariant], channel: "Channel"
+):
if not channel:
raise ValidationError(
{
"channel": ValidationError(
"Can't add product variant for draft order without channel",
- code=OrderErrorCode.REQUIRED,
+ code=OrderErrorCode.REQUIRED.value,
)
}
)
@@ -172,8 +171,11 @@ def validate_variant_channel_listings(variants, channel):
)
-def validate_product_is_available_for_purchase(order):
+def validate_product_is_available_for_purchase(order: "Order", errors: T_ERRORS):
+ invalid_lines = []
for line in order.lines.all():
+ if not line.variant:
+ continue
product_channel_listing = line.variant.product.channel_listings.filter(
channel_id=order.channel_id
).first()
@@ -181,29 +183,28 @@ def validate_product_is_available_for_purchase(order):
product_channel_listing
and product_channel_listing.is_available_for_purchase()
):
- raise ValidationError(
- {
- "lines": ValidationError(
- "Can't finalize draft with product unavailable for purchase.",
- code=OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE,
- )
- }
+ invalid_lines.append(graphene.Node.to_global_id("OrderLine", line.pk))
+ if invalid_lines:
+ errors["lines"].append(
+ ValidationError(
+ "Can't finalize draft with product unavailable for purchase.",
+ code=OrderErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.value,
+ params={"order_lines": invalid_lines},
)
+ )
-def validate_channel_is_active(channel):
+def validate_channel_is_active(channel: "Channel", errors: T_ERRORS):
if not channel.is_active:
- raise ValidationError(
- {
- "channel": ValidationError(
- "Cannot complete draft order with inactive channel.",
- code=OrderErrorCode.CHANNEL_INACTIVE.value,
- )
- }
+ errors["channel"].append(
+ ValidationError(
+ "Cannot complete draft order with inactive channel.",
+ code=OrderErrorCode.CHANNEL_INACTIVE.value,
+ )
)
-def validate_draft_order(order, country):
+def validate_draft_order(order: "Order", country: str):
"""Check if the given order contains the proper data.
- Has proper customer data,
@@ -214,16 +215,19 @@ def validate_draft_order(order, country):
Returns a list of errors if any were found.
"""
- validate_billing_address(order)
+ errors: T_ERRORS = defaultdict(list)
+ validate_billing_address(order, errors)
if order.is_shipping_required():
- validate_shipping_address(order)
- validate_shipping_method(order)
- validate_total_quantity(order)
- validate_order_lines(order, country)
- validate_channel_is_active(order.channel)
- validate_product_is_published(order)
- validate_product_is_available_for_purchase(order)
- validate_variants_is_available(order)
+ validate_shipping_address(order, errors)
+ validate_shipping_method(order, errors)
+ validate_total_quantity(order, errors)
+ validate_order_lines(order, country, errors)
+ validate_channel_is_active(order.channel, errors)
+ validate_product_is_published(order, errors)
+ validate_product_is_available_for_purchase(order, errors)
+ validate_variants_is_available(order, errors)
+ if errors:
+ raise ValidationError(errors)
def prepare_insufficient_stock_order_validation_errors(exc):
@@ -244,7 +248,9 @@ def prepare_insufficient_stock_order_validation_errors(exc):
f"Insufficient product stock: {item.variant}",
code=OrderErrorCode.INSUFFICIENT_STOCK,
params={
- "order_line": order_line_global_id,
+ "order_lines": [order_line_global_id]
+ if order_line_global_id
+ else [],
"warehouse": warehouse_global_id,
},
)
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index a341819389..b4fd1927eb 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -10,7 +10,7 @@ from ....attribute import AttributeInputType
from ....attribute import models as attribute_models
from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....core.tracing import traced_atomic_transaction
-from ....order import OrderStatus
+from ....order import events as order_events
from ....order import models as order_models
from ....order.tasks import recalculate_orders_task
from ....product import models
@@ -32,6 +32,7 @@ from ...core.types.common import (
)
from ...core.utils import get_duplicated_values
from ...core.validators import validate_price_precision
+from ...utils import get_user_or_app_from_context
from ...warehouse.types import Warehouse
from ..mutations.channels import ProductVariantChannelListingAddInput
from ..mutations.products import (
@@ -41,7 +42,11 @@ from ..mutations.products import (
StockInput,
)
from ..types import Product, ProductType, ProductVariant
-from ..utils import create_stocks, get_used_variants_attribute_values
+from ..utils import (
+ create_stocks,
+ get_draft_order_lines_data_for_variants,
+ get_used_variants_attribute_values,
+)
class CategoryBulkDelete(ModelBulkDeleteMutation):
@@ -115,13 +120,11 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
)
variants_ids = [variant_id for _, variant_id in product_to_variant]
- # get draft order lines for products
- lines_id_and_orders_id = order_models.OrderLine.objects.filter(
- variant__id__in=variants_ids, order__status=OrderStatus.DRAFT
- ).values("pk", "order_id")
- line_pks = {line["pk"] for line in lines_id_and_orders_id}
- orders_id = {line["order_id"] for line in lines_id_and_orders_id}
cls.delete_assigned_attribute_values(pks)
+
+ requester = get_user_or_app_from_context(info.context)
+ draft_order_lines_data = get_draft_order_lines_data_for_variants(variants_ids)
+
response = super().perform_mutation(
_root,
info,
@@ -131,9 +134,18 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
)
# delete order lines for deleted variants
- order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
- if orders_id:
- recalculate_orders_task.delay(list(orders_id))
+ order_models.OrderLine.objects.filter(
+ pk__in=draft_order_lines_data.line_pks
+ ).delete()
+
+ # run order event for deleted lines
+ for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
+ lines_data = [(line.quantity, line) for line in order_lines]
+ order_events.order_line_product_removed_event(order, requester, lines_data)
+
+ order_pks = draft_order_lines_data.order_pks
+ if order_pks:
+ recalculate_orders_task.delay(list(order_pks))
return response
@@ -529,12 +541,10 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
pks = cls.get_global_ids_or_error(ids, ProductVariant)
except ValidationError as error:
return 0, error
- # get draft order lines for variants
- lines_id_and_orders_id = order_models.OrderLine.objects.filter(
- variant__pk__in=pks, order__status=OrderStatus.DRAFT
- ).values("pk", "order_id")
- line_pks = {line["pk"] for line in lines_id_and_orders_id}
- orders_id = {line["order_id"] for line in lines_id_and_orders_id}
+
+ requester = get_user_or_app_from_context(info.context)
+ draft_order_lines_data = get_draft_order_lines_data_for_variants(pks)
+
product_pks = list(
models.Product.objects.filter(variants__in=pks)
.distinct()
@@ -561,9 +571,18 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
)
# delete order lines for deleted variants
- order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
- if orders_id:
- recalculate_orders_task.delay(list(orders_id))
+ order_models.OrderLine.objects.filter(
+ pk__in=draft_order_lines_data.line_pks
+ ).delete()
+
+ # run order event for deleted lines
+ for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
+ lines_data = [(line.quantity, line) for line in order_lines]
+ order_events.order_line_variant_removed_event(order, requester, lines_data)
+
+ order_pks = draft_order_lines_data.order_pks
+ if order_pks:
+ recalculate_orders_task.delay(list(order_pks))
# set new product default variant if any has been removed
products = models.Product.objects.filter(
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 7bf1bbcae9..d0af2ee527 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -16,6 +16,7 @@ from ....core.tracing import traced_atomic_transaction
from ....core.utils.editorjs import clean_editor_js
from ....core.utils.validators import get_oembed_data
from ....order import OrderStatus
+from ....order import events as order_events
from ....order import models as order_models
from ....order.tasks import recalculate_orders_task
from ....product import ProductMediaTypes, models
@@ -48,6 +49,7 @@ from ...core.utils import (
validate_slug_and_generate_if_needed,
)
from ...core.utils.reordering import perform_reordering
+from ...utils import get_user_or_app_from_context
from ...warehouse.types import Warehouse
from ..types import (
Category,
@@ -59,6 +61,7 @@ from ..types import (
)
from ..utils import (
create_stocks,
+ get_draft_order_lines_data_for_variants,
get_used_attribute_values_for_variant,
get_used_variants_attribute_values,
)
@@ -708,19 +711,27 @@ class ProductDelete(ModelDeleteMutation):
instance = cls.get_node_or_error(info, node_id, only_type=Product)
variants_id = list(instance.variants.all().values_list("id", flat=True))
- # get draft order lines for variant
- lines_id_and_orders_id = order_models.OrderLine.objects.filter(
- variant__id__in=variants_id, order__status=OrderStatus.DRAFT
- ).values("pk", "order_id")
- line_pks = {line["pk"] for line in lines_id_and_orders_id}
- orders_id = {line["order_id"] for line in lines_id_and_orders_id}
cls.delete_assigned_attribute_values(instance)
+
+ requester = get_user_or_app_from_context(info.context)
+ draft_order_lines_data = get_draft_order_lines_data_for_variants(variants_id)
+
response = super().perform_mutation(_root, info, **data)
+
# delete order lines for deleted variant
- order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
- if orders_id:
- recalculate_orders_task.delay(list(orders_id))
+ order_models.OrderLine.objects.filter(
+ pk__in=draft_order_lines_data.line_pks
+ ).delete()
+
+ # run order event for deleted lines
+ for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
+ lines_data = [(line.quantity, line) for line in order_lines]
+ order_events.order_line_product_removed_event(order, requester, lines_data)
+
+ order_pks = draft_order_lines_data.order_pks
+ if order_pks:
+ recalculate_orders_task.delay(list(order_pks))
info.context.plugins.product_deleted(instance, variants_id)
return response
@@ -1025,12 +1036,8 @@ class ProductVariantDelete(ModelDeleteMutation):
node_id = data.get("id")
instance = cls.get_node_or_error(info, node_id, only_type=ProductVariant)
- # get draft order lines for variant
- lines_id_and_orders_id = order_models.OrderLine.objects.filter(
- variant__pk=instance.pk, order__status=OrderStatus.DRAFT
- ).values("pk", "order_id")
- line_pks = {line["pk"] for line in lines_id_and_orders_id}
- orders_id = {line["order_id"] for line in lines_id_and_orders_id}
+ requester = get_user_or_app_from_context(info.context)
+ draft_order_lines_data = get_draft_order_lines_data_for_variants([instance.pk])
# Get cached variant with related fields to fully populate webhook payload.
variant = (
@@ -1043,9 +1050,18 @@ class ProductVariantDelete(ModelDeleteMutation):
response = super().perform_mutation(_root, info, **data)
# delete order lines for deleted variant
- order_models.OrderLine.objects.filter(pk__in=line_pks).delete()
- if orders_id:
- recalculate_orders_task.delay(list(orders_id))
+ order_models.OrderLine.objects.filter(
+ pk__in=draft_order_lines_data.line_pks
+ ).delete()
+
+ # run order event for deleted lines
+ for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
+ lines_data = [(line.quantity, line) for line in order_lines]
+ order_events.order_line_variant_removed_event(order, requester, lines_data)
+
+ order_pks = draft_order_lines_data.order_pks
+ if order_pks:
+ recalculate_orders_task.delay(list(order_pks))
transaction.on_commit(
lambda: info.context.plugins.product_variant_deleted(variant)
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 4a58d52dd0..a559cdf984 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -8,8 +8,8 @@ from prices import Money, TaxedMoney
from ....attribute.utils import associate_attribute_values_to_instance
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
-from ....order import OrderStatus
-from ....order.models import OrderLine
+from ....order import OrderEvents, OrderStatus
+from ....order.models import OrderEvent, OrderLine
from ....plugins.manager import get_plugins_manager
from ....product.error_codes import ProductErrorCode
from ....product.models import (
@@ -614,6 +614,23 @@ def test_delete_products_variants_in_draft_order(
assert not ProductChannelListing.objects.filter(product_id__in=products_id).exists()
mocked_recalculate_orders_task.assert_called_once_with([draft_order.id])
+ event = OrderEvent.objects.filter(
+ type=OrderEvents.ORDER_LINE_PRODUCT_DELETED
+ ).last()
+ assert event
+ assert event.order == draft_order
+ assert event.user == staff_api_client.user
+ expected_params = [
+ {
+ "item": str(line),
+ "line_pk": line.pk,
+ "quantity": line.quantity,
+ }
+ for line in draft_order.lines.all()
+ ]
+ for param in expected_params:
+ assert param in event.parameters
+
def test_delete_product_media(
staff_api_client, product_with_images, permission_manage_products
@@ -1070,6 +1087,23 @@ def test_delete_product_variants_in_draft_orders(
assert OrderLine.objects.filter(pk=order_line_not_in_draft_pk).exists()
mocked_recalculate_orders_task.assert_called_once_with([draft_order.id])
+ event = OrderEvent.objects.filter(
+ type=OrderEvents.ORDER_LINE_VARIANT_DELETED
+ ).last()
+ assert event
+ assert event.order == draft_order
+ assert event.user == staff_api_client.user
+ expected_params = [
+ {
+ "item": str(line),
+ "line_pk": line.pk,
+ "quantity": line.quantity,
+ }
+ for line in draft_order.lines.all()
+ ]
+ for param in expected_params:
+ assert param in event.parameters
+
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_product_variants_delete_default_variant(
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 5241f9c76e..19c7189562 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -20,8 +20,8 @@ from ....attribute.models import Attribute, AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
from ....core.taxes import TaxType
from ....core.units import WeightUnits
-from ....order import OrderStatus
-from ....order.models import OrderLine
+from ....order import OrderEvents, OrderStatus
+from ....order.models import OrderEvent, OrderLine
from ....plugins.manager import PluginsManager
from ....product import ProductMediaTypes
from ....product.error_codes import ProductErrorCode
@@ -6634,6 +6634,23 @@ def test_delete_product_variant_in_draft_order(
assert OrderLine.objects.filter(pk__in=not_draft_order_lines_pks).exists()
mocked_recalculate_orders_task.assert_called_once_with([draft_order.id])
+ event = OrderEvent.objects.filter(
+ type=OrderEvents.ORDER_LINE_PRODUCT_DELETED
+ ).last()
+ assert event
+ assert event.order == draft_order
+ assert event.user == staff_api_client.user
+ expected_params = [
+ {
+ "item": str(line),
+ "line_pk": line.pk,
+ "quantity": line.quantity,
+ }
+ for line in draft_order.lines.all()
+ ]
+ for param in expected_params:
+ assert param in event.parameters
+
def test_product_type(user_api_client, product_type, channel_USD):
query = """
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index ac0cd5a0a1..b3d22960dd 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -12,8 +12,8 @@ from ....attribute import AttributeInputType
from ....attribute.models import AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
from ....core.units import WeightUnits
-from ....order import OrderStatus
-from ....order.models import OrderLine
+from ....order import OrderEvents, OrderStatus
+from ....order.models import OrderEvent, OrderLine
from ....product.error_codes import ProductErrorCode
from ....product.models import Product, ProductChannelListing, ProductVariant
from ....tests.utils import dummy_editorjs, flush_post_commit_hooks
@@ -2532,6 +2532,31 @@ def test_delete_variant_in_draft_order(
assert result_call_args == expected_call_args
+ events = OrderEvent.objects.filter(type=OrderEvents.ORDER_LINE_VARIANT_DELETED)
+ assert events
+ assert {event.order for event in events} == {draft_order, second_draft_order}
+ assert {event.user for event in events} == {staff_api_client.user}
+ expected_params = [
+ {
+ "item": str(line),
+ "line_pk": line.pk,
+ "quantity": line.quantity,
+ }
+ for line in draft_order.lines.all()
+ ]
+ for param in expected_params:
+ assert param in events.get(order=draft_order).parameters
+ expected_params = [
+ {
+ "item": str(line),
+ "line_pk": line.pk,
+ "quantity": line.quantity,
+ }
+ for line in second_draft_order.lines.all()
+ ]
+ for param in expected_params:
+ assert param in events.get(order=second_draft_order).parameters
+
@patch("saleor.order.tasks.recalculate_orders_task.delay")
def test_delete_default_variant(
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index d383b873c4..d1a979b4c5 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -1,11 +1,13 @@
-from collections import defaultdict
-from typing import TYPE_CHECKING, Dict, List
+from collections import defaultdict, namedtuple
+from typing import TYPE_CHECKING, Dict, Iterable, List
import graphene
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from ...core.tracing import traced_atomic_transaction
+from ...order import OrderStatus
+from ...order import models as order_models
from ...warehouse.models import Stock
if TYPE_CHECKING:
@@ -78,3 +80,27 @@ def create_stocks(
except IntegrityError:
msg = "Stock for one of warehouses already exists for this product variant."
raise ValidationError(msg)
+
+
+DraftOrderLinesData = namedtuple(
+ "DraftOrderLinesData", ["order_to_lines_mapping", "line_pks", "order_pks"]
+)
+
+
+def get_draft_order_lines_data_for_variants(
+ variant_ids: Iterable[int],
+):
+ lines = order_models.OrderLine.objects.filter(
+ variant__id__in=variant_ids, order__status=OrderStatus.DRAFT
+ ).select_related("order")
+ order_to_lines_mapping: Dict[
+ order_models.Order, List[order_models.OrderLine]
+ ] = defaultdict(list)
+ line_pks = set()
+ order_pks = set()
+ for line in lines:
+ order_to_lines_mapping[line.order].append(line)
+ line_pks.add(line.pk)
+ order_pks.add(line.order_id)
+
+ return DraftOrderLinesData(order_to_lines_mapping, line_pks, order_pks)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5b03249b23..7af7436549 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3032,6 +3032,7 @@ type Order implements Node & ObjectWithMetadata {
discountName: String @deprecated(reason: "Use discounts field. This field will be removed in Saleor 4.0.")
translatedDiscountName: String @deprecated(reason: "Use discounts field. This field will be removed in Saleor 4.0.")
discounts: [OrderDiscount!]
+ errors: [OrderError!]!
}
enum OrderAction {
@@ -3145,7 +3146,7 @@ type OrderError {
message: String
code: OrderErrorCode!
warehouse: ID
- orderLine: ID
+ orderLines: [ID!]
variants: [ID!]
addressType: AddressTypeEnum
}
@@ -3265,6 +3266,8 @@ enum OrderEventsEnum {
ORDER_DISCOUNT_DELETED
ORDER_LINE_DISCOUNT_UPDATED
ORDER_LINE_DISCOUNT_REMOVED
+ ORDER_LINE_PRODUCT_DELETED
+ ORDER_LINE_VARIANT_DELETED
UPDATED_ADDRESS
EMAIL_SENT
CONFIRMED
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index f000a17990..f94b0820cc 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -94,6 +94,9 @@ class OrderEvents:
ORDER_LINE_DISCOUNT_UPDATED = "order_line_discount_updated"
ORDER_LINE_DISCOUNT_REMOVED = "order_line_discount_removed"
+ ORDER_LINE_PRODUCT_DELETED = "order_line_product_deleted"
+ ORDER_LINE_VARIANT_DELETED = "order_line_variant_deleted"
+
UPDATED_ADDRESS = "updated_address"
EMAIL_SENT = "email_sent"
@@ -143,6 +146,8 @@ class OrderEvents:
(ORDER_DISCOUNT_DELETED, "Order discount was deleted for this order."),
(ORDER_LINE_DISCOUNT_UPDATED, "Order line was discounted."),
(ORDER_LINE_DISCOUNT_REMOVED, "The discount for order line was removed."),
+ (ORDER_LINE_PRODUCT_DELETED, "The order line product was removed."),
+ (ORDER_LINE_VARIANT_DELETED, "The order line product variant was removed."),
(UPDATED_ADDRESS, "The address from the placed order was updated"),
(EMAIL_SENT, "The email was sent"),
(CONFIRMED, "Order was confirmed"),
diff --git a/saleor/order/events.py b/saleor/order/events.py
index 2b7fc95bdd..1fec6e9755 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -705,3 +705,29 @@ def order_line_discount_removed_event(
line=line,
user=user,
)
+
+
+def order_line_product_removed_event(
+ order: Order,
+ user: UserType,
+ order_lines: List[Tuple[int, OrderLine]],
+):
+ return OrderEvent.objects.create(
+ type=OrderEvents.ORDER_LINE_PRODUCT_DELETED,
+ order=order,
+ user=user,
+ parameters={"lines": _lines_per_quantity_to_line_object_list(order_lines)},
+ )
+
+
+def order_line_variant_removed_event(
+ order: Order,
+ user: UserType,
+ order_lines: List[Tuple[int, OrderLine]],
+):
+ return OrderEvent.objects.create(
+ type=OrderEvents.ORDER_LINE_VARIANT_DELETED,
+ order=order,
+ user=user,
+ parameters={"lines": _lines_per_quantity_to_line_object_list(order_lines)},
+ )
diff --git a/saleor/order/migrations/0112_auto_20210616_0548.py b/saleor/order/migrations/0112_auto_20210616_0548.py
new file mode 100644
index 0000000000..1b6d4062f2
--- /dev/null
+++ b/saleor/order/migrations/0112_auto_20210616_0548.py
@@ -0,0 +1,64 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0111_auto_20210518_1357"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="orderevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("DRAFT_CREATED", "draft_created"),
+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),
+ ("ADDED_PRODUCTS", "added_products"),
+ ("REMOVED_PRODUCTS", "removed_products"),
+ ("PLACED", "placed"),
+ ("PLACED_FROM_DRAFT", "placed_from_draft"),
+ ("OVERSOLD_ITEMS", "oversold_items"),
+ ("CANCELED", "canceled"),
+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),
+ ("ORDER_FULLY_PAID", "order_fully_paid"),
+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),
+ ("ORDER_DISCOUNT_ADDED", "order_discount_added"),
+ (
+ "ORDER_DISCOUNT_AUTOMATICALLY_UPDATED",
+ "order_discount_automatically_updated",
+ ),
+ ("ORDER_DISCOUNT_UPDATED", "order_discount_updated"),
+ ("ORDER_DISCOUNT_DELETED", "order_discount_deleted"),
+ ("ORDER_LINE_DISCOUNT_UPDATED", "order_line_discount_updated"),
+ ("ORDER_LINE_DISCOUNT_REMOVED", "order_line_discount_removed"),
+ ("ORDER_LINE_PRODUCT_DELETED", "order_line_product_deleted"),
+ ("ORDER_LINE_VARIANT_DELETED", "order_line_variant_deleted"),
+ ("UPDATED_ADDRESS", "updated_address"),
+ ("EMAIL_SENT", "email_sent"),
+ ("CONFIRMED", "confirmed"),
+ ("PAYMENT_AUTHORIZED", "payment_authorized"),
+ ("PAYMENT_CAPTURED", "payment_captured"),
+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),
+ ("PAYMENT_REFUNDED", "payment_refunded"),
+ ("PAYMENT_VOIDED", "payment_voided"),
+ ("PAYMENT_FAILED", "payment_failed"),
+ ("INVOICE_REQUESTED", "invoice_requested"),
+ ("INVOICE_GENERATED", "invoice_generated"),
+ ("INVOICE_UPDATED", "invoice_updated"),
+ ("INVOICE_SENT", "invoice_sent"),
+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),
+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),
+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),
+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),
+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),
+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),
+ ("TRACKING_UPDATED", "tracking_updated"),
+ ("NOTE_ADDED", "note_added"),
+ ("OTHER", "other"),
+ ],
+ max_length=255,
+ ),
+ ),
+ ]