Skip to content

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

Split order mutations files into file per mutation (#9747)

Maciej Korycinski60b1c18f600a
diff --git a/saleor/graphql/order/bulk_mutations/orders.py b/saleor/graphql/order/bulk_mutations/orders.py
index b14b0050a2..0e2a3e2377 100644
--- a/saleor/graphql/order/bulk_mutations/orders.py
+++ b/saleor/graphql/order/bulk_mutations/orders.py
@@ -5,7 +5,7 @@ from ....order import models
from ....order.actions import cancel_order
from ...core.mutations import BaseBulkMutation
from ...core.types import NonNullList, OrderError
-from ..mutations.orders import clean_order_cancel
+from ..mutations.order_cancel import clean_order_cancel
from ..types import Order
diff --git a/saleor/graphql/order/mutations/discount_order.py b/saleor/graphql/order/mutations/discount_order.py
deleted file mode 100644
index 89d9a66f1c..0000000000
--- a/saleor/graphql/order/mutations/discount_order.py
+++ /dev/null
@@ -1,381 +0,0 @@
-import copy
-
-import graphene
-from django.core.exceptions import ValidationError
-from prices import Money
-
-from ....core.permissions import OrderPermissions
-from ....core.tracing import traced_atomic_transaction
-from ....order import events, models
-from ....order.error_codes import OrderErrorCode
-from ....order.search import update_order_search_document
-from ....order.utils import (
- create_order_discount_for_order,
- get_order_discounts,
- recalculate_order,
- recalculate_order_discounts,
- recalculate_order_prices,
- remove_discount_from_order_line,
- remove_order_discount_from_order,
- update_discount_for_order_line,
-)
-from ...core.mutations import BaseMutation
-from ...core.scalars import PositiveDecimal
-from ...core.types import OrderError
-from ...discount.enums import DiscountValueTypeEnum
-from ..types import Order, OrderLine
-
-
-class OrderDiscountCommonInput(graphene.InputObjectType):
- value_type = graphene.Field(
- DiscountValueTypeEnum,
- required=True,
- description="Type of the discount: fixed or percent",
- )
- value = PositiveDecimal(
- required=True,
- description="Value of the discount. Can store fixed value or percent value",
- )
- reason = graphene.String(
- required=False, description="Explanation for the applied discount."
- )
-
-
-class OrderDiscountCommon(BaseMutation):
- class Meta:
- abstract = True
-
- @classmethod
- def validate_order(cls, info, order):
- if not (order.is_draft() or order.is_unconfirmed()):
- error_msg = "Only draft and unconfirmed order can be modified."
- raise ValidationError(
- {
- "orderId": ValidationError(
- error_msg, code=OrderErrorCode.CANNOT_DISCOUNT.value
- )
- }
- )
-
- @classmethod
- def _validation_error_for_input_value(
- cls, error_msg, code=OrderErrorCode.INVALID.value
- ):
- return ValidationError({"value": ValidationError(error_msg, code=code)})
-
- @classmethod
- def validate_order_discount_input(cls, _info, max_total: Money, input: dict):
- value_type = input["value_type"]
- value = input["value"]
- if value_type == DiscountValueTypeEnum.FIXED:
- if value > max_total.amount:
- error_msg = (
- f"The value ({value}) cannot be higher than {max_total.amount} "
- f"{max_total.currency}"
- )
- raise cls._validation_error_for_input_value(error_msg)
- elif value > 100:
- error_msg = f"The percentage value ({value}) cannot be higher than 100."
- raise cls._validation_error_for_input_value(error_msg)
-
- @classmethod
- def recalculate_order(cls, order: models.Order):
- """Recalculate order data and save them."""
- recalculate_order_prices(order)
- recalculate_order_discounts(order)
- order.save(
- update_fields=[
- "total_net_amount",
- "total_gross_amount",
- "undiscounted_total_net_amount",
- "undiscounted_total_gross_amount",
- "updated_at",
- ]
- )
-
-
-class OrderDiscountAdd(OrderDiscountCommon):
- order = graphene.Field(Order, description="Order which has been discounted.")
-
- class Arguments:
- order_id = graphene.ID(description="ID of an order to discount.", required=True)
- input = OrderDiscountCommonInput(
- required=True,
- description="Fields required to create a discount for the order.",
- )
-
- class Meta:
- description = "Adds discount to the order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def validate_order(cls, info, order):
- super().validate_order(info, order)
- # This condition can be removed when we introduce support for multi discounts.
- order_discounts = get_order_discounts(order)
- if len(order_discounts) >= 1:
- error_msg = "Order already has assigned discount."
- raise ValidationError(
- {
- "orderId": ValidationError(
- error_msg, code=OrderErrorCode.CANNOT_DISCOUNT.value
- )
- }
- )
-
- @classmethod
- def validate(cls, info, order, input):
- cls.validate_order(info, order)
- cls.validate_order_discount_input(info, order.undiscounted_total.gross, input)
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(info, data.get("order_id"), only_type=Order)
- input = data.get("input", {})
- cls.validate(info, order, input)
-
- reason = input.get("reason")
- value_type = input.get("value_type")
- value = input.get("value")
-
- order_discount = create_order_discount_for_order(
- order, reason, value_type, value
- )
-
- events.order_discount_added_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- order_discount=order_discount,
- )
- return OrderDiscountAdd(order=order)
-
-
-class OrderDiscountUpdate(OrderDiscountCommon):
- order = graphene.Field(Order, description="Order which has been discounted.")
-
- class Arguments:
- discount_id = graphene.ID(
- description="ID of a discount to update.", required=True
- )
- input = OrderDiscountCommonInput(
- required=True,
- description="Fields required to update a discount for the order.",
- )
-
- class Meta:
- description = "Update discount for the order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def validate(cls, info, order, order_discount, input):
- cls.validate_order(info, order)
- input["value"] = input.get("value") or order_discount.value
- input["value_type"] = input.get("value_type") or order_discount.value_type
-
- cls.validate_order_discount_input(info, order.undiscounted_total.gross, input)
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order_discount = cls.get_node_or_error(
- info, data.get("discount_id"), only_type="OrderDiscount"
- )
- order = order_discount.order
- input = data.get("input")
- cls.validate(info, order, order_discount, input)
-
- reason = input.get("reason", order_discount.reason)
- value_type = input.get("value_type", order_discount.value_type)
- value = input.get("value", order_discount.value)
-
- order_discount_before_update = copy.deepcopy(order_discount)
-
- order_discount.reason = reason
- order_discount.value = value
- order_discount.value_type = value_type
- order_discount.save()
-
- cls.recalculate_order(order)
-
- if (
- order_discount_before_update.value_type != value_type
- or order_discount_before_update.value != value
- ):
- # call update event only when we changed the type or value of the discount
- order_discount.refresh_from_db()
- events.order_discount_updated_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- order_discount=order_discount,
- old_order_discount=order_discount_before_update,
- )
- return OrderDiscountUpdate(order=order)
-
-
-class OrderDiscountDelete(OrderDiscountCommon):
- order = graphene.Field(Order, description="Order which has removed discount.")
-
- class Arguments:
- discount_id = graphene.ID(
- description="ID of a discount to remove.", required=True
- )
-
- class Meta:
- description = "Remove discount from the order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order_discount = cls.get_node_or_error(
- info, data.get("discount_id"), only_type="OrderDiscount"
- )
- order = order_discount.order
- cls.validate_order(info, order)
-
- remove_order_discount_from_order(order, order_discount)
- events.order_discount_deleted_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- order_discount=order_discount,
- )
-
- order.refresh_from_db()
-
- cls.recalculate_order(order)
- update_order_search_document(order)
-
- return OrderDiscountDelete(order=order)
-
-
-class OrderLineDiscountUpdate(OrderDiscountCommon):
- order_line = graphene.Field(
- OrderLine, description="Order line which has been discounted."
- )
- order = graphene.Field(
- Order, description="Order which is related to the discounted line."
- )
-
- class Arguments:
- order_line_id = graphene.ID(
- description="ID of a order line to update price", required=True
- )
- input = OrderDiscountCommonInput(
- required=True,
- description="Fields required to update price for the order line.",
- )
-
- class Meta:
- description = "Update discount for the order line."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def validate(cls, info, order, order_line, input):
- cls.validate_order(info, order)
- input["value"] = input.get("value") or order_line.unit_discount_value
- input["value_type"] = input.get("value_type") or order_line.unit_discount_type
-
- cls.validate_order_discount_input(
- info, order_line.undiscounted_unit_price.gross, input
- )
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
-
- order_line = cls.get_node_or_error(
- info, data.get("order_line_id"), only_type=OrderLine
- )
- input = data.get("input")
- order = order_line.order
- cls.validate(info, order, order_line, input)
- reason = input.get("reason")
- value_type = input.get("value_type")
- value = input.get("value")
-
- order_line_before_update = copy.deepcopy(order_line)
- tax_included = info.context.site.settings.include_taxes_in_prices
-
- update_discount_for_order_line(
- order_line,
- order=order,
- reason=reason,
- value_type=value_type,
- value=value,
- manager=info.context.plugins,
- tax_included=tax_included,
- )
- if (
- order_line_before_update.unit_discount_value != value
- or order_line_before_update.unit_discount_type != value_type
- ):
- # Create event only when we change type or value of the discount
- events.order_line_discount_updated_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- line=order_line,
- line_before_update=order_line_before_update,
- )
- recalculate_order(order)
- return OrderLineDiscountUpdate(order_line=order_line, order=order)
-
-
-class OrderLineDiscountRemove(OrderDiscountCommon):
- order_line = graphene.Field(
- OrderLine, description="Order line which has removed discount."
- )
- order = graphene.Field(
- Order, description="Order which is related to line which has removed discount."
- )
-
- class Arguments:
- order_line_id = graphene.ID(
- description="ID of a order line to remove its discount", required=True
- )
-
- class Meta:
- description = "Remove discount applied to the order line."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def validate(cls, info, order):
- cls.validate_order(info, order)
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- tax_included = info.context.site.settings.include_taxes_in_prices
- order_line = cls.get_node_or_error(
- info, data.get("order_line_id"), only_type=OrderLine
- )
- order = order_line.order
- cls.validate(info, order)
-
- remove_discount_from_order_line(
- order_line, order, manager=info.context.plugins, tax_included=tax_included
- )
-
- events.order_line_discount_removed_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- line=order_line,
- )
-
- recalculate_order(order)
- return OrderLineDiscountRemove(order_line=order_line, order=order)
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
new file mode 100644
index 0000000000..da9482f320
--- /dev/null
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -0,0 +1,134 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....account.models import User
+from ....core.exceptions import InsufficientStock
+from ....core.permissions import OrderPermissions
+from ....core.taxes import zero_taxed_money
+from ....core.tracing import traced_atomic_transaction
+from ....order import OrderStatus, models
+from ....order.actions import order_created
+from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderInfo, OrderLineInfo
+from ....order.search import prepare_order_search_document_value
+from ....order.utils import get_order_country
+from ....warehouse.management import allocate_preorders, allocate_stocks
+from ....warehouse.reservations import is_reservation_enabled
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Order
+from ..utils import (
+ prepare_insufficient_stock_order_validation_errors,
+ validate_draft_order,
+)
+
+
+class DraftOrderComplete(BaseMutation):
+ order = graphene.Field(Order, description="Completed order.")
+
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of the order that will be completed."
+ )
+
+ class Meta:
+ description = "Completes creating an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def update_user_fields(cls, order):
+ if order.user:
+ order.user_email = order.user.email
+ elif order.user_email:
+ try:
+ order.user = User.objects.get(email=order.user_email)
+ except User.DoesNotExist:
+ order.user = None
+
+ @classmethod
+ def validate_order(cls, order):
+ if not order.is_draft():
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "The order is not draft.", code=OrderErrorCode.INVALID.value
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id):
+ manager = info.context.plugins
+ order = cls.get_node_or_error(
+ info,
+ id,
+ only_type=Order,
+ qs=models.Order.objects.prefetch_related("lines__variant"),
+ )
+ cls.validate_order(order)
+
+ country = get_order_country(order)
+ validate_draft_order(order, country, info.context.plugins)
+ cls.update_user_fields(order)
+ order.status = OrderStatus.UNFULFILLED
+
+ if not order.is_shipping_required():
+ order.shipping_method_name = None
+ order.shipping_price = zero_taxed_money(order.currency)
+ if order.shipping_address:
+ order.shipping_address.delete()
+ order.shipping_address = None
+
+ order.search_document = prepare_order_search_document_value(order)
+ order.save()
+
+ channel = order.channel
+ channel_slug = channel.slug
+ order_lines_info = []
+ for line in order.lines.all():
+ if line.variant.track_inventory or line.variant.is_preorder_active():
+ line_data = OrderLineInfo(
+ line=line, quantity=line.quantity, variant=line.variant
+ )
+ order_lines_info.append(line_data)
+ try:
+ with traced_atomic_transaction():
+ allocate_stocks(
+ [line_data],
+ country,
+ channel_slug,
+ manager,
+ check_reservations=is_reservation_enabled(
+ info.context.site.settings
+ ),
+ )
+ allocate_preorders(
+ [line_data],
+ channel_slug,
+ check_reservations=is_reservation_enabled(
+ info.context.site.settings
+ ),
+ )
+ except InsufficientStock as exc:
+ errors = prepare_insufficient_stock_order_validation_errors(exc)
+ raise ValidationError({"lines": errors})
+
+ order_info = OrderInfo(
+ order=order,
+ customer_email=order.get_customer_email(),
+ channel=channel,
+ payment=order.get_last_payment(),
+ lines_data=order_lines_info,
+ )
+
+ order_created(
+ order_info=order_info,
+ user=info.context.user,
+ app=info.context.app,
+ manager=info.context.plugins,
+ from_draft=True,
+ )
+
+ return DraftOrderComplete(order=order)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_order_create.py
similarity index 63%
rename from saleor/graphql/order/mutations/draft_orders.py
rename to saleor/graphql/order/mutations/draft_order_create.py
index 20b16045ef..92c7f0173d 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -5,41 +5,25 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from graphene.types import InputObjectType
-from ....account.models import User
from ....checkout import AddressType
-from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
-from ....core.taxes import TaxError, zero_taxed_money
+from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
from ....order import OrderOrigin, OrderStatus, events, models
-from ....order.actions import order_created
from ....order.error_codes import OrderErrorCode
-from ....order.fetch import OrderInfo, OrderLineInfo
-from ....order.search import (
- prepare_order_search_document_value,
- update_order_search_document,
-)
-from ....order.utils import (
- add_variant_to_order,
- get_order_country,
- recalculate_order,
- update_order_prices,
-)
-from ....warehouse.management import allocate_preorders, allocate_stocks
-from ....warehouse.reservations import is_reservation_enabled
+from ....order.search import update_order_search_document
+from ....order.utils import add_variant_to_order, recalculate_order, update_order_prices
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...channel.types import Channel
-from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ...core.mutations import ModelMutation
from ...core.scalars import PositiveDecimal
from ...core.types import NonNullList, OrderError
from ...product.types import ProductVariant
from ...shipping.utils import get_shipping_model_by_object_id
from ..types import Order, OrderLine
from ..utils import (
- prepare_insufficient_stock_order_validation_errors,
- validate_draft_order,
validate_product_is_published_in_channel,
validate_variant_channel_listings,
)
@@ -346,184 +330,3 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
# Post-process the results
recalculate_order(instance)
update_order_search_document(instance)
-
-
-class DraftOrderUpdate(DraftOrderCreate):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a draft order to update.")
- input = DraftOrderInput(
- required=True, description="Fields required to update an order."
- )
-
- class Meta:
- description = "Updates a draft order."
- model = models.Order
- object_type = Order
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def get_instance(cls, info, **data):
- instance = super().get_instance(
- info, qs=models.Order.objects.prefetch_related("lines"), **data
- )
- if instance.status != OrderStatus.DRAFT:
- raise ValidationError(
- {
- "id": ValidationError(
- "Provided order id belongs to non-draft order. "
- "Use `orderUpdate` mutation instead.",
- code=OrderErrorCode.INVALID,
- )
- }
- )
- return instance
-
- @classmethod
- def save(cls, info, instance, cleaned_input):
- return cls._save_draft_order(info, instance, cleaned_input, new_instance=False)
-
-
-class DraftOrderDelete(ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a draft order to delete.")
-
- class Meta:
- description = "Deletes a draft order."
- model = models.Order
- object_type = Order
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_instance(cls, info, instance):
- if instance.status != OrderStatus.DRAFT:
- raise ValidationError(
- {
- "id": ValidationError(
- "Provided order id belongs to non-draft order.",
- code=OrderErrorCode.INVALID,
- )
- }
- )
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_instance(info, **data)
- response = super().perform_mutation(_root, info, **data)
- transaction.on_commit(lambda: info.context.plugins.draft_order_deleted(order))
- return response
-
-
-class DraftOrderComplete(BaseMutation):
- order = graphene.Field(Order, description="Completed order.")
-
- class Arguments:
- id = graphene.ID(
- required=True, description="ID of the order that will be completed."
- )
-
- class Meta:
- description = "Completes creating an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def update_user_fields(cls, order):
- if order.user:
- order.user_email = order.user.email
- elif order.user_email:
- try:
- order.user = User.objects.get(email=order.user_email)
- except User.DoesNotExist:
- order.user = None
-
- @classmethod
- def validate_order(cls, order):
- if not order.is_draft():
- raise ValidationError(
- {
- "id": ValidationError(
- "The order is not draft.", code=OrderErrorCode.INVALID.value
- )
- }
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, id):
- manager = info.context.plugins
- order = cls.get_node_or_error(
- info,
- id,
- only_type=Order,
- qs=models.Order.objects.prefetch_related("lines__variant"),
- )
- cls.validate_order(order)
-
- country = get_order_country(order)
- validate_draft_order(order, country, info.context.plugins)
- cls.update_user_fields(order)
- order.status = OrderStatus.UNFULFILLED
-
- if not order.is_shipping_required():
- order.shipping_method_name = None
- order.shipping_price = zero_taxed_money(order.currency)
- if order.shipping_address:
- order.shipping_address.delete()
- order.shipping_address = None
-
- order.search_document = prepare_order_search_document_value(order)
- order.save()
-
- channel = order.channel
- channel_slug = channel.slug
- order_lines_info = []
- for line in order.lines.all():
- if line.variant.track_inventory or line.variant.is_preorder_active():
- line_data = OrderLineInfo(
- line=line, quantity=line.quantity, variant=line.variant
- )
- order_lines_info.append(line_data)
- try:
- with traced_atomic_transaction():
- allocate_stocks(
- [line_data],
- country,
- channel_slug,
- manager,
- check_reservations=is_reservation_enabled(
- info.context.site.settings
- ),
- )
- allocate_preorders(
- [line_data],
- channel_slug,
- check_reservations=is_reservation_enabled(
- info.context.site.settings
- ),
- )
- except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"lines": errors})
-
- order_info = OrderInfo(
- order=order,
- customer_email=order.get_customer_email(),
- channel=channel,
- payment=order.get_last_payment(),
- lines_data=order_lines_info,
- )
-
- order_created(
- order_info=order_info,
- user=info.context.user,
- app=info.context.app,
- manager=info.context.plugins,
- from_draft=True,
- )
-
- return DraftOrderComplete(order=order)
diff --git a/saleor/graphql/order/mutations/draft_order_delete.py b/saleor/graphql/order/mutations/draft_order_delete.py
new file mode 100644
index 0000000000..d3a3f7ce4e
--- /dev/null
+++ b/saleor/graphql/order/mutations/draft_order_delete.py
@@ -0,0 +1,44 @@
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import OrderStatus, models
+from ....order.error_codes import OrderErrorCode
+from ...core.mutations import ModelDeleteMutation
+from ...core.types import OrderError
+from ..types import Order
+
+
+class DraftOrderDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a draft order to delete.")
+
+ class Meta:
+ description = "Deletes a draft order."
+ model = models.Order
+ object_type = Order
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ if instance.status != OrderStatus.DRAFT:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Provided order id belongs to non-draft order.",
+ code=OrderErrorCode.INVALID,
+ )
+ }
+ )
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_instance(info, **data)
+ response = super().perform_mutation(_root, info, **data)
+ transaction.on_commit(lambda: info.context.plugins.draft_order_deleted(order))
+ return response
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
new file mode 100644
index 0000000000..561842abd5
--- /dev/null
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -0,0 +1,46 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....order import OrderStatus, models
+from ....order.error_codes import OrderErrorCode
+from ...core.types import OrderError
+from ..types import Order
+from .draft_order_create import DraftOrderCreate, DraftOrderInput
+
+
+class DraftOrderUpdate(DraftOrderCreate):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a draft order to update.")
+ input = DraftOrderInput(
+ required=True, description="Fields required to update an order."
+ )
+
+ class Meta:
+ description = "Updates a draft order."
+ model = models.Order
+ object_type = Order
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def get_instance(cls, info, **data):
+ instance = super().get_instance(
+ info, qs=models.Order.objects.prefetch_related("lines"), **data
+ )
+ if instance.status != OrderStatus.DRAFT:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Provided order id belongs to non-draft order. "
+ "Use `orderUpdate` mutation instead.",
+ code=OrderErrorCode.INVALID,
+ )
+ }
+ )
+ return instance
+
+ @classmethod
+ def save(cls, info, instance, cleaned_input):
+ return cls._save_draft_order(info, instance, cleaned_input, new_instance=False)
diff --git a/saleor/graphql/order/mutations/fulfillment_approve.py b/saleor/graphql/order/mutations/fulfillment_approve.py
new file mode 100644
index 0000000000..77c1ba937f
--- /dev/null
+++ b/saleor/graphql/order/mutations/fulfillment_approve.py
@@ -0,0 +1,78 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.exceptions import InsufficientStock
+from ....core.permissions import OrderPermissions
+from ....order import FulfillmentStatus
+from ....order.actions import approve_fulfillment
+from ....order.error_codes import OrderErrorCode
+from ...core.descriptions import ADDED_IN_31
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Fulfillment, Order
+from ..utils import prepare_insufficient_stock_order_validation_errors
+from .order_fulfill import OrderFulfill
+
+
+class FulfillmentApprove(BaseMutation):
+ fulfillment = graphene.Field(Fulfillment, description="An approved fulfillment.")
+ order = graphene.Field(Order, description="Order which fulfillment was approved.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a fulfillment to approve.")
+ notify_customer = graphene.Boolean(
+ required=True, description="True if confirmation email should be send."
+ )
+ allow_stock_to_be_exceeded = graphene.Boolean(
+ default_value=False, description="True if stock could be exceeded."
+ )
+
+ class Meta:
+ description = "Approve existing fulfillment." + ADDED_IN_31
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, info, fulfillment):
+ if fulfillment.status != FulfillmentStatus.WAITING_FOR_APPROVAL:
+ raise ValidationError(
+ "Invalid fulfillment status, only WAITING_FOR_APPROVAL "
+ "fulfillments can be accepted.",
+ code=OrderErrorCode.INVALID.value,
+ )
+
+ OrderFulfill.check_lines_for_preorder([line.order_line for line in fulfillment])
+
+ if (
+ not info.context.site.settings.fulfillment_allow_unpaid
+ and not fulfillment.order.is_fully_paid()
+ ):
+ raise ValidationError(
+ "Cannot fulfill unpaid order.",
+ code=OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER,
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ fulfillment = cls.get_node_or_error(info, data["id"], only_type="Fulfillment")
+ cls.clean_input(info, fulfillment)
+
+ order = fulfillment.order
+
+ try:
+ fulfillment = approve_fulfillment(
+ fulfillment,
+ info.context.user,
+ info.context.app,
+ info.context.plugins,
+ info.context.site.settings,
+ notify_customer=data["notify_customer"],
+ allow_stock_to_be_exceeded=data.get("allow_stock_to_be_exceeded"),
+ )
+ except InsufficientStock as exc:
+ errors = prepare_insufficient_stock_order_validation_errors(exc)
+ raise ValidationError({"stocks": errors})
+
+ order.refresh_from_db(fields=["status"])
+ return FulfillmentApprove(fulfillment=fulfillment, order=order)
diff --git a/saleor/graphql/order/mutations/fulfillment_cancel.py b/saleor/graphql/order/mutations/fulfillment_cancel.py
new file mode 100644
index 0000000000..0bbf79ea83
--- /dev/null
+++ b/saleor/graphql/order/mutations/fulfillment_cancel.py
@@ -0,0 +1,108 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....giftcard.utils import order_has_gift_card_lines
+from ....order import FulfillmentStatus
+from ....order.actions import cancel_fulfillment, cancel_waiting_fulfillment
+from ....order.error_codes import OrderErrorCode
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Fulfillment, Order
+
+
+class FulfillmentCancelInput(graphene.InputObjectType):
+ warehouse_id = graphene.ID(
+ description="ID of a warehouse where items will be restocked. Optional "
+ "when fulfillment is in WAITING_FOR_APPROVAL state.",
+ required=False,
+ )
+
+
+class FulfillmentCancel(BaseMutation):
+ fulfillment = graphene.Field(Fulfillment, description="A canceled fulfillment.")
+ order = graphene.Field(Order, description="Order which fulfillment was cancelled.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a fulfillment to cancel.")
+ input = FulfillmentCancelInput(
+ required=False, description="Fields required to cancel a fulfillment."
+ )
+
+ class Meta:
+ description = "Cancels existing fulfillment and optionally restocks items."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def validate_fulfillment(cls, fulfillment, warehouse):
+ if not fulfillment.can_edit():
+ raise ValidationError(
+ {
+ "fulfillment": ValidationError(
+ "This fulfillment can't be canceled",
+ code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT,
+ )
+ }
+ )
+ if (
+ fulfillment.status != FulfillmentStatus.WAITING_FOR_APPROVAL
+ and not warehouse
+ ):
+ raise ValidationError(
+ {
+ "warehouseId": ValidationError(
+ "This parameter is required for fulfillments which are not in "
+ "WAITING_FOR_APPROVAL state.",
+ code=OrderErrorCode.REQUIRED,
+ )
+ }
+ )
+
+ @classmethod
+ def validate_order(cls, order):
+ if order_has_gift_card_lines(order):
+ raise ValidationError(
+ {
+ "fulfillment": ValidationError(
+ "Cannot cancel fulfillment with gift card lines.",
+ code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.value,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
+ order = fulfillment.order
+
+ cls.validate_order(order)
+
+ warehouse = None
+ if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
+ warehouse = None
+ elif warehouse_id := data.get("input", {}).get("warehouse_id"):
+ warehouse = cls.get_node_or_error(
+ info, warehouse_id, only_type="Warehouse", field="warehouse_id"
+ )
+
+ cls.validate_fulfillment(fulfillment, warehouse)
+
+ if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
+ fulfillment = cancel_waiting_fulfillment(
+ fulfillment,
+ info.context.user,
+ info.context.app,
+ info.context.plugins,
+ )
+ else:
+ fulfillment = cancel_fulfillment(
+ fulfillment,
+ info.context.user,
+ info.context.app,
+ warehouse,
+ info.context.plugins,
+ )
+ order.refresh_from_db(fields=["status"])
+ return FulfillmentCancel(fulfillment=fulfillment, order=order)
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py b/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
new file mode 100644
index 0000000000..09197eda77
--- /dev/null
+++ b/saleor/graphql/order/mutations/fulfillment_refund_and_return_product_base.py
@@ -0,0 +1,204 @@
+from typing import Optional
+
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....giftcard.utils import order_has_gift_card_lines
+from ....order import FulfillmentLineData
+from ....order import models as order_models
+from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderLineInfo
+from ....payment.models import TransactionItem
+from ...core.mutations import BaseMutation
+from ..types import FulfillmentLine, OrderLine
+
+
+class FulfillmentRefundAndReturnProductBase(BaseMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def clean_order_payment(cls, payment, cleaned_input):
+ if not payment or not payment.can_refund():
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "Order cannot be refunded.",
+ code=OrderErrorCode.CANNOT_REFUND.value,
+ )
+ }
+ )
+ cleaned_input["payment"] = payment
+
+ @classmethod
+ def clean_amount_to_refund(
+ cls, order, amount_to_refund, captured_value, cleaned_input
+ ):
+ if amount_to_refund is not None:
+ if order_has_gift_card_lines(order):
+ raise ValidationError(
+ {
+ "amount_to_refund": ValidationError(
+ (
+ "Cannot specified amount to refund when order has "
+ "gift card lines."
+ ),
+ code=OrderErrorCode.CANNOT_REFUND.value,
+ )
+ }
+ )
+
+ if amount_to_refund > captured_value:
+ raise ValidationError(
+ {
+ "amount_to_refund": ValidationError(
+ (
+ "The amountToRefund is greater than the maximal "
+ "possible amount to refund."
+ ),
+ code=OrderErrorCode.CANNOT_REFUND.value,
+ ),
+ }
+ )
+ cleaned_input["amount_to_refund"] = amount_to_refund
+
+ @classmethod
+ def _raise_error_for_line(cls, msg, type, line_id, field_name, code=None):
+ line_global_id = graphene.Node.to_global_id(type, line_id)
+ if not code:
+ code = OrderErrorCode.INVALID_QUANTITY.value
+ raise ValidationError(
+ {
+ field_name: ValidationError(
+ msg,
+ code=code,
+ params={field_name: line_global_id},
+ )
+ }
+ )
+
+ @classmethod
+ def raise_error_for_payment_error(cls, transactions: Optional[TransactionItem]):
+ if transactions:
+ code = OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
+ msg = "No app or plugin is configured to handle payment action requests."
+ else:
+ msg = "The refund operation is not available yet."
+ code = OrderErrorCode.CANNOT_REFUND.value
+ raise ValidationError(
+ msg,
+ code=code,
+ )
+
+ @classmethod
+ def clean_fulfillment_lines(
+ cls, fulfillment_lines_data, cleaned_input, whitelisted_statuses
+ ):
+ fulfillment_lines = cls.get_nodes_or_error(
+ [line["fulfillment_line_id"] for line in fulfillment_lines_data],
+ field="fulfillment_lines",
+ only_type=FulfillmentLine,
+ qs=order_models.FulfillmentLine.objects.prefetch_related(
+ "fulfillment", "order_line"
+ ),
+ )
+ fulfillment_lines = list(fulfillment_lines)
+ cleaned_fulfillment_lines = []
+ for line, line_data in zip(fulfillment_lines, fulfillment_lines_data):
+ quantity = line_data["quantity"]
+ if line.order_line.is_gift_card:
+ cls._raise_error_for_line(
+ "Cannot refund or return gift card line.",
+ "FulfillmentLine",
+ line.pk,
+ "fulfillment_line_id",
+ OrderErrorCode.GIFT_CARD_LINE.value,
+ )
+ if line.quantity < quantity:
+ cls._raise_error_for_line(
+ "Provided quantity is bigger than quantity from "
+ "fulfillment line",
+ "FulfillmentLine",
+ line.pk,
+ "fulfillment_line_id",
+ )
+ if line.fulfillment.status not in whitelisted_statuses:
+ allowed_statuses_str = ", ".join(whitelisted_statuses)
+ cls._raise_error_for_line(
+ f"Unable to process action for fulfillmentLine with different "
+ f"status than {allowed_statuses_str}.",
+ "FulfillmentLine",
+ line.pk,
+ "fulfillment_line_id",
+ code=OrderErrorCode.INVALID.value,
+ )
+ replace = line_data.get("replace", False)
+ if replace and not line.order_line.variant_id:
+ cls._raise_error_for_line(
+ "Unable to replace line as the assigned product doesn't exist.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ )
+ cleaned_fulfillment_lines.append(
+ FulfillmentLineData(
+ line=line,
+ quantity=quantity,
+ replace=replace,
+ )
+ )
+ cleaned_input["fulfillment_lines"] = cleaned_fulfillment_lines
+
+ @classmethod
+ def clean_lines(cls, lines_data, cleaned_input):
+ order_lines = cls.get_nodes_or_error(
+ [line["order_line_id"] for line in lines_data],
+ field="order_lines",
+ only_type=OrderLine,
+ qs=order_models.OrderLine.objects.prefetch_related(
+ "fulfillment_lines__fulfillment", "variant", "allocations"
+ ),
+ )
+ order_lines = list(order_lines)
+ cleaned_order_lines = []
+ for line, line_data in zip(order_lines, lines_data):
+ quantity = line_data["quantity"]
+ if line.is_gift_card:
+ cls._raise_error_for_line(
+ "Cannot refund or return gift card line.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ OrderErrorCode.GIFT_CARD_LINE.value,
+ )
+ if line.quantity < quantity:
+ cls._raise_error_for_line(
+ "Provided quantity is bigger than quantity from order line.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ )
+ quantity_ready_to_move = line.quantity_unfulfilled
+ if quantity_ready_to_move < quantity:
+ cls._raise_error_for_line(
+ "Provided quantity is bigger than unfulfilled quantity.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ )
+ variant = line.variant
+ replace = line_data.get("replace", False)
+ if replace and not line.variant_id:
+ cls._raise_error_for_line(
+ "Unable to replace line as the assigned product doesn't exist.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ )
+
+ cleaned_order_lines.append(
+ OrderLineInfo(
+ line=line, quantity=quantity, variant=variant, replace=replace
+ )
+ )
+ cleaned_input["order_lines"] = cleaned_order_lines
diff --git a/saleor/graphql/order/mutations/fulfillment_refund_products.py b/saleor/graphql/order/mutations/fulfillment_refund_products.py
new file mode 100644
index 0000000000..1c00ac0ca5
--- /dev/null
+++ b/saleor/graphql/order/mutations/fulfillment_refund_products.py
@@ -0,0 +1,150 @@
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....order import FulfillmentStatus
+from ....order import models as order_models
+from ....order.actions import create_refund_fulfillment
+from ....payment import PaymentError
+from ...core.scalars import PositiveDecimal
+from ...core.types import NonNullList, OrderError
+from ..types import Fulfillment, Order
+from .fulfillment_refund_and_return_product_base import (
+ FulfillmentRefundAndReturnProductBase,
+)
+
+
+class OrderRefundLineInput(graphene.InputObjectType):
+ order_line_id = graphene.ID(
+ description="The ID of the order line to refund.",
+ name="orderLineId",
+ required=True,
+ )
+ quantity = graphene.Int(
+ description="The number of items to be refunded.",
+ required=True,
+ )
+
+
+class OrderRefundFulfillmentLineInput(graphene.InputObjectType):
+ fulfillment_line_id = graphene.ID(
+ description="The ID of the fulfillment line to refund.",
+ name="fulfillmentLineId",
+ required=True,
+ )
+ quantity = graphene.Int(
+ description="The number of items to be refunded.",
+ required=True,
+ )
+
+
+class OrderRefundProductsInput(graphene.InputObjectType):
+ order_lines = NonNullList(
+ OrderRefundLineInput,
+ description="List of unfulfilled lines to refund.",
+ )
+ fulfillment_lines = NonNullList(
+ OrderRefundFulfillmentLineInput,
+ description="List of fulfilled lines to refund.",
+ )
+ amount_to_refund = PositiveDecimal(
+ required=False,
+ description="The total amount of refund when the value is provided manually.",
+ )
+ include_shipping_costs = graphene.Boolean(
+ description=(
+ "If true, Saleor will refund shipping costs. If amountToRefund is provided"
+ "includeShippingCosts will be ignored."
+ ),
+ default_value=False,
+ )
+
+
+class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
+ fulfillment = graphene.Field(Fulfillment, description="A refunded fulfillment.")
+ order = graphene.Field(Order, description="Order which fulfillment was refunded.")
+
+ class Arguments:
+ order = graphene.ID(
+ description="ID of the order to be refunded.", required=True
+ )
+ input = OrderRefundProductsInput(
+ required=True,
+ description="Fields required to create an refund fulfillment.",
+ )
+
+ class Meta:
+ description = "Refund products."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, info, order_id, input):
+ cleaned_input = {}
+ amount_to_refund = input.get("amount_to_refund")
+ include_shipping_costs = input["include_shipping_costs"]
+
+ qs = order_models.Order.objects.prefetch_related("payments")
+ order = cls.get_node_or_error(
+ info, order_id, field="order", only_type=Order, qs=qs
+ )
+ payment = order.get_last_payment()
+ transactions = list(order.payment_transactions.all())
+ if transactions:
+ # For know we handle refunds only for last transaction. We need to add an
+ # interface to process a refund requests on multiple transactions
+ captured_value = transactions[-1].captured_value
+ else:
+ cls.clean_order_payment(payment, cleaned_input)
+ captured_value = payment.captured_amount
+ cls.clean_amount_to_refund(
+ order, amount_to_refund, captured_value, cleaned_input
+ )
+
+ cleaned_input.update(
+ {
+ "include_shipping_costs": include_shipping_costs,
+ "order": order,
+ "transactions": transactions,
+ "payment": payment,
+ }
+ )
+
+ order_lines_data = input.get("order_lines", [])
+ fulfillment_lines_data = input.get("fulfillment_lines", [])
+
+ if order_lines_data:
+ cls.clean_lines(order_lines_data, cleaned_input)
+ if fulfillment_lines_data:
+ cls.clean_fulfillment_lines(
+ fulfillment_lines_data,
+ cleaned_input,
+ whitelisted_statuses=[
+ FulfillmentStatus.FULFILLED,
+ FulfillmentStatus.RETURNED,
+ FulfillmentStatus.WAITING_FOR_APPROVAL,
+ ],
+ )
+ return cleaned_input
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
+ order = cleaned_input["order"]
+
+ try:
+ refund_fulfillment = create_refund_fulfillment(
+ info.context.user,
+ info.context.app,
+ order,
+ cleaned_input["payment"],
+ cleaned_input["transactions"],
+ cleaned_input.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
+ info.context.plugins,
+ cleaned_input["amount_to_refund"],
+ cleaned_input["include_shipping_costs"],
+ )
+ except PaymentError:
+ cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
+ return cls(order=order, fulfillment=refund_fulfillment)
diff --git a/saleor/graphql/order/mutations/fulfillment_return_products.py b/saleor/graphql/order/mutations/fulfillment_return_products.py
new file mode 100644
index 0000000000..7177a387cb
--- /dev/null
+++ b/saleor/graphql/order/mutations/fulfillment_return_products.py
@@ -0,0 +1,180 @@
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....order import FulfillmentStatus
+from ....order import models as order_models
+from ....order.actions import create_fulfillments_for_returned_products
+from ....payment import PaymentError
+from ...core.scalars import PositiveDecimal
+from ...core.types import NonNullList, OrderError
+from ..types import Fulfillment, Order
+from .fulfillment_refund_and_return_product_base import (
+ FulfillmentRefundAndReturnProductBase,
+)
+
+
+class OrderReturnLineInput(graphene.InputObjectType):
+ order_line_id = graphene.ID(
+ description="The ID of the order line to return.",
+ name="orderLineId",
+ required=True,
+ )
+ quantity = graphene.Int(
+ description="The number of items to be returned.",
+ required=True,
+ )
+ replace = graphene.Boolean(
+ description="Determines, if the line should be added to replace order.",
+ default_value=False,
+ )
+
+
+class OrderReturnFulfillmentLineInput(graphene.InputObjectType):
+ fulfillment_line_id = graphene.ID(
+ description="The ID of the fulfillment line to return.",
+ name="fulfillmentLineId",
+ required=True,
+ )
+ quantity = graphene.Int(
+ description="The number of items to be returned.",
+ required=True,
+ )
+ replace = graphene.Boolean(
+ description="Determines, if the line should be added to replace order.",
+ default_value=False,
+ )
+
+
+class OrderReturnProductsInput(graphene.InputObjectType):
+ order_lines = NonNullList(
+ OrderReturnLineInput,
+ description="List of unfulfilled lines to return.",
+ )
+ fulfillment_lines = NonNullList(
+ OrderReturnFulfillmentLineInput,
+ description="List of fulfilled lines to return.",
+ )
+ amount_to_refund = PositiveDecimal(
+ required=False,
+ description="The total amount of refund when the value is provided manually.",
+ )
+ include_shipping_costs = graphene.Boolean(
+ description=(
+ "If true, Saleor will refund shipping costs. If amountToRefund is provided"
+ "includeShippingCosts will be ignored."
+ ),
+ default_value=False,
+ )
+ refund = graphene.Boolean(
+ description="If true, Saleor will call refund action for all lines.",
+ default_value=False,
+ )
+
+
+class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
+ return_fulfillment = graphene.Field(
+ Fulfillment, description="A return fulfillment."
+ )
+ replace_fulfillment = graphene.Field(
+ Fulfillment, description="A replace fulfillment."
+ )
+ order = graphene.Field(Order, description="Order which fulfillment was returned.")
+ replace_order = graphene.Field(
+ Order,
+ description="A draft order which was created for products with replace flag.",
+ )
+
+ class Meta:
+ description = "Return products."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ class Arguments:
+ order = graphene.ID(
+ description="ID of the order to be returned.", required=True
+ )
+ input = OrderReturnProductsInput(
+ required=True,
+ description="Fields required to return products.",
+ )
+
+ @classmethod
+ def clean_input(cls, info, order_id, input):
+ cleaned_input = {}
+ amount_to_refund = input.get("amount_to_refund")
+ include_shipping_costs = input["include_shipping_costs"]
+ refund = input["refund"]
+
+ qs = order_models.Order.objects.prefetch_related("payments")
+ order = cls.get_node_or_error(
+ info, order_id, field="order", only_type=Order, qs=qs
+ )
+ if refund:
+ payment = order.get_last_payment()
+ transactions = list(order.payment_transactions.all())
+ if transactions:
+ # For know we handle refunds only for last transaction. We need to add
+ # an interface to process a refund requests on multiple transactions
+ captured_value = transactions[-1].captured_value
+ else:
+ cls.clean_order_payment(payment, cleaned_input)
+ captured_value = payment.captured_amount
+ cls.clean_amount_to_refund(
+ order, amount_to_refund, captured_value, cleaned_input
+ )
+ cleaned_input["transactions"] = transactions
+
+ cleaned_input.update(
+ {
+ "include_shipping_costs": include_shipping_costs,
+ "order": order,
+ "refund": refund,
+ }
+ )
+
+ order_lines_data = input.get("order_lines")
+ fulfillment_lines_data = input.get("fulfillment_lines")
+
+ if order_lines_data:
+ cls.clean_lines(order_lines_data, cleaned_input)
+ if fulfillment_lines_data:
+ cls.clean_fulfillment_lines(
+ fulfillment_lines_data,
+ cleaned_input,
+ whitelisted_statuses=[
+ FulfillmentStatus.FULFILLED,
+ FulfillmentStatus.REFUNDED,
+ FulfillmentStatus.WAITING_FOR_APPROVAL,
+ ],
+ )
+ return cleaned_input
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
+ order = cleaned_input["order"]
+ try:
+ response = create_fulfillments_for_returned_products(
+ info.context.user,
+ info.context.app,
+ order,
+ cleaned_input.get("payment"),
+ cleaned_input.get("transactions"),
+ cleaned_input.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
+ info.context.plugins,
+ cleaned_input["refund"],
+ cleaned_input.get("amount_to_refund"),
+ cleaned_input["include_shipping_costs"],
+ )
+ except PaymentError:
+ cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
+
+ return_fulfillment, replace_fulfillment, replace_order = response
+ return cls(
+ order=order,
+ return_fulfillment=return_fulfillment,
+ replace_fulfillment=replace_fulfillment,
+ replace_order=replace_order,
+ )
diff --git a/saleor/graphql/order/mutations/fulfillment_update_tracking.py b/saleor/graphql/order/mutations/fulfillment_update_tracking.py
new file mode 100644
index 0000000000..1680af3c03
--- /dev/null
+++ b/saleor/graphql/order/mutations/fulfillment_update_tracking.py
@@ -0,0 +1,50 @@
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....order.actions import fulfillment_tracking_updated
+from ....order.notifications import send_fulfillment_update
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Fulfillment, Order
+from .order_fulfill import FulfillmentUpdateTrackingInput
+
+
+class FulfillmentUpdateTracking(BaseMutation):
+ fulfillment = graphene.Field(
+ Fulfillment, description="A fulfillment with updated tracking."
+ )
+ order = graphene.Field(
+ Order, description="Order for which fulfillment was updated."
+ )
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a fulfillment to update.")
+ input = FulfillmentUpdateTrackingInput(
+ required=True, description="Fields required to update a fulfillment."
+ )
+
+ class Meta:
+ description = "Updates a fulfillment for an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
+ tracking_number = data.get("input").get("tracking_number") or ""
+ fulfillment.tracking_number = tracking_number
+ fulfillment.save()
+ order = fulfillment.order
+ fulfillment_tracking_updated(
+ fulfillment,
+ info.context.user,
+ info.context.app,
+ tracking_number,
+ info.context.plugins,
+ )
+ input_data = data.get("input", {})
+ notify_customer = input_data.get("notify_customer")
+ if notify_customer:
+ send_fulfillment_update(order, fulfillment, info.context.plugins)
+ return FulfillmentUpdateTracking(fulfillment=fulfillment, order=order)
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
deleted file mode 100644
index 8b3be179d5..0000000000
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ /dev/null
@@ -1,983 +0,0 @@
-from collections import defaultdict
-from typing import Optional
-
-import graphene
-from django.core.exceptions import ValidationError
-from django.template.defaultfilters import pluralize
-
-from ....core.exceptions import InsufficientStock
-from ....core.permissions import OrderPermissions
-from ....core.tracing import traced_atomic_transaction
-from ....giftcard.utils import order_has_gift_card_lines
-from ....order import FulfillmentLineData, FulfillmentStatus
-from ....order import models as order_models
-from ....order.actions import (
- approve_fulfillment,
- cancel_fulfillment,
- cancel_waiting_fulfillment,
- create_fulfillments,
- create_fulfillments_for_returned_products,
- create_refund_fulfillment,
- fulfillment_tracking_updated,
-)
-from ....order.error_codes import OrderErrorCode
-from ....order.fetch import OrderLineInfo
-from ....order.notifications import send_fulfillment_update
-from ....payment import PaymentError
-from ....payment.models import TransactionItem
-from ...core.descriptions import ADDED_IN_31
-from ...core.mutations import BaseMutation
-from ...core.scalars import PositiveDecimal
-from ...core.types import NonNullList, OrderError
-from ...core.utils import get_duplicated_values
-from ...warehouse.types import Warehouse
-from ..types import Fulfillment, FulfillmentLine, Order, OrderLine
-from ..utils import prepare_insufficient_stock_order_validation_errors
-
-
-class OrderFulfillStockInput(graphene.InputObjectType):
- quantity = graphene.Int(
- description="The number of line items to be fulfilled from given warehouse.",
- required=True,
- )
- warehouse = graphene.ID(
- description="ID of the warehouse from which the item will be fulfilled.",
- required=True,
- )
-
-
-class OrderFulfillLineInput(graphene.InputObjectType):
- order_line_id = graphene.ID(
- description="The ID of the order line.", name="orderLineId"
- )
- stocks = NonNullList(
- OrderFulfillStockInput,
- required=True,
- description="List of stock items to create.",
- )
-
-
-class OrderFulfillInput(graphene.InputObjectType):
- lines = NonNullList(
- OrderFulfillLineInput,
- required=True,
- description="List of items informing how to fulfill the order.",
- )
- notify_customer = graphene.Boolean(
- description="If true, send an email notification to the customer."
- )
-
- allow_stock_to_be_exceeded = graphene.Boolean(
- description="If true, then allow proceed fulfillment when stock is exceeded.",
- default_value=False,
- )
-
-
-class FulfillmentUpdateTrackingInput(graphene.InputObjectType):
- tracking_number = graphene.String(description="Fulfillment tracking number.")
- notify_customer = graphene.Boolean(
- default_value=False,
- description="If true, send an email notification to the customer.",
- )
-
-
-class OrderFulfill(BaseMutation):
- fulfillments = NonNullList(Fulfillment, description="List of created fulfillments.")
- order = graphene.Field(Order, description="Fulfilled order.")
-
- class Arguments:
- order = graphene.ID(
- description="ID of the order to be fulfilled.", name="order"
- )
- input = OrderFulfillInput(
- required=True, description="Fields required to create a fulfillment."
- )
-
- class Meta:
- description = "Creates new fulfillments for an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_lines(cls, order_lines, quantities_for_lines):
- for order_line, line_quantities in zip(order_lines, quantities_for_lines):
- line_total_quantity = sum(line_quantities)
- line_quantity_unfulfilled = order_line.quantity_unfulfilled
-
- if line_total_quantity > line_quantity_unfulfilled:
- msg = (
- "Only %(quantity)d item%(item_pluralize)s remaining "
- "to fulfill: %(order_line)s."
- ) % {
- "quantity": line_quantity_unfulfilled,
- "item_pluralize": pluralize(line_quantity_unfulfilled),
- "order_line": order_line,
- }
- order_line_global_id = graphene.Node.to_global_id(
- "OrderLine", order_line.pk
- )
- raise ValidationError(
- {
- "order_line_id": ValidationError(
- msg,
- code=OrderErrorCode.FULFILL_ORDER_LINE,
- params={"order_lines": [order_line_global_id]},
- )
- }
- )
-
- @classmethod
- def check_warehouses_for_duplicates(cls, warehouse_ids):
- for warehouse_ids_for_line in warehouse_ids:
- duplicates = get_duplicated_values(warehouse_ids_for_line)
- if duplicates:
- raise ValidationError(
- {
- "warehouse": ValidationError(
- "Duplicated warehouse ID.",
- code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
- params={"warehouse": duplicates.pop()},
- )
- }
- )
-
- @classmethod
- def check_lines_for_duplicates(cls, lines_ids):
- duplicates = get_duplicated_values(lines_ids)
- if duplicates:
- raise ValidationError(
- {
- "orderLineId": ValidationError(
- "Duplicated order line ID.",
- code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
- params={"order_lines": [duplicates.pop()]},
- )
- }
- )
-
- @classmethod
- def check_lines_for_preorder(cls, order_lines):
- for order_line in order_lines:
- if order_line.variant_id and order_line.variant.is_preorder_active():
- order_line_global_id = graphene.Node.to_global_id(
- "OrderLine", order_line.pk
- )
- raise ValidationError(
- {
- "order_line_id": ValidationError(
- "Can not fulfill preorder variant.",
- code=OrderErrorCode.FULFILL_ORDER_LINE,
- params={"order_lines": [order_line_global_id]},
- )
- }
- )
-
- @classmethod
- def check_total_quantity_of_items(cls, quantities_for_lines):
- flat_quantities = sum(quantities_for_lines, [])
- if sum(flat_quantities) <= 0:
- raise ValidationError(
- {
- "lines": ValidationError(
- "Total quantity must be larger than 0.",
- code=OrderErrorCode.ZERO_QUANTITY,
- )
- }
- )
-
- @classmethod
- def clean_input(cls, info, order, data):
- site_settings = info.context.site.settings
- if not order.is_fully_paid() and (
- site_settings.fulfillment_auto_approve
- and not site_settings.fulfillment_allow_unpaid
- ):
- raise ValidationError(
- {
- "order": ValidationError(
- "Cannot fulfill unpaid order.",
- code=OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.value,
- )
- }
- )
-
- lines = data["lines"]
-
- warehouse_ids_for_lines = [
- [stock["warehouse"] for stock in line["stocks"]] for line in lines
- ]
- cls.check_warehouses_for_duplicates(warehouse_ids_for_lines)
-
- quantities_for_lines = [
- [stock["quantity"] for stock in line["stocks"]] for line in lines
- ]
-
- lines_ids = [line["order_line_id"] for line in lines]
- cls.check_lines_for_duplicates(lines_ids)
- order_lines = cls.get_nodes_or_error(
- lines_ids, field="lines", only_type=OrderLine
- )
-
- cls.clean_lines(order_lines, quantities_for_lines)
-
- if site_settings.fulfillment_auto_approve:
- cls.check_lines_for_preorder(order_lines)
-
- cls.check_total_quantity_of_items(quantities_for_lines)
-
- lines_for_warehouses = defaultdict(list)
- for line, order_line in zip(lines, order_lines):
- for stock in line["stocks"]:
- if stock["quantity"] > 0:
- warehouse_pk = cls.get_global_id_or_error(
- stock["warehouse"], only_type=Warehouse, field="warehouse"
- )
- lines_for_warehouses[warehouse_pk].append(
- {"order_line": order_line, "quantity": stock["quantity"]}
- )
-
- data["order_lines"] = order_lines
- data["lines_for_warehouses"] = lines_for_warehouses
- return data
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, order, **data):
- order = cls.get_node_or_error(
- info,
- order,
- field="order",
- only_type=Order,
- qs=order_models.Order.objects.prefetch_related("lines__variant"),
- )
- data = data.get("input")
-
- cleaned_input = cls.clean_input(info, order, data)
-
- context = info.context
- user = context.user if not context.user.is_anonymous else None
- app = context.app
- manager = context.plugins
- lines_for_warehouses = cleaned_input["lines_for_warehouses"]
- notify_customer = cleaned_input.get("notify_customer", True)
- allow_stock_to_be_exceeded = cleaned_input.get(
- "allow_stock_to_be_exceeded", False
- )
-
- approved = info.context.site.settings.fulfillment_auto_approve
-
- try:
- fulfillments = create_fulfillments(
- user,
- app,
- order,
- dict(lines_for_warehouses),
- manager,
- context.site.settings,
- notify_customer,
- allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,
- approved=approved,
- )
- except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"stocks": errors})
-
- return OrderFulfill(fulfillments=fulfillments, order=order)
-
-
-class FulfillmentUpdateTracking(BaseMutation):
- fulfillment = graphene.Field(
- Fulfillment, description="A fulfillment with updated tracking."
- )
- order = graphene.Field(
- Order, description="Order for which fulfillment was updated."
- )
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a fulfillment to update.")
- input = FulfillmentUpdateTrackingInput(
- required=True, description="Fields required to update a fulfillment."
- )
-
- class Meta:
- description = "Updates a fulfillment for an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
- tracking_number = data.get("input").get("tracking_number") or ""
- fulfillment.tracking_number = tracking_number
- fulfillment.save()
- order = fulfillment.order
- fulfillment_tracking_updated(
- fulfillment,
- info.context.user,
- info.context.app,
- tracking_number,
- info.context.plugins,
- )
- input_data = data.get("input", {})
- notify_customer = input_data.get("notify_customer")
- if notify_customer:
- send_fulfillment_update(order, fulfillment, info.context.plugins)
- return FulfillmentUpdateTracking(fulfillment=fulfillment, order=order)
-
-
-class FulfillmentCancelInput(graphene.InputObjectType):
- warehouse_id = graphene.ID(
- description="ID of a warehouse where items will be restocked. Optional "
- "when fulfillment is in WAITING_FOR_APPROVAL state.",
- required=False,
- )
-
-
-class FulfillmentCancel(BaseMutation):
- fulfillment = graphene.Field(Fulfillment, description="A canceled fulfillment.")
- order = graphene.Field(Order, description="Order which fulfillment was cancelled.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a fulfillment to cancel.")
- input = FulfillmentCancelInput(
- required=False, description="Fields required to cancel a fulfillment."
- )
-
- class Meta:
- description = "Cancels existing fulfillment and optionally restocks items."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def validate_fulfillment(cls, fulfillment, warehouse):
- if not fulfillment.can_edit():
- raise ValidationError(
- {
- "fulfillment": ValidationError(
- "This fulfillment can't be canceled",
- code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT,
- )
- }
- )
- if (
- fulfillment.status != FulfillmentStatus.WAITING_FOR_APPROVAL
- and not warehouse
- ):
- raise ValidationError(
- {
- "warehouseId": ValidationError(
- "This parameter is required for fulfillments which are not in "
- "WAITING_FOR_APPROVAL state.",
- code=OrderErrorCode.REQUIRED,
- )
- }
- )
-
- @classmethod
- def validate_order(cls, order):
- if order_has_gift_card_lines(order):
- raise ValidationError(
- {
- "fulfillment": ValidationError(
- "Cannot cancel fulfillment with gift card lines.",
- code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.value,
- )
- }
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
- order = fulfillment.order
-
- cls.validate_order(order)
-
- warehouse = None
- if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
- warehouse = None
- elif warehouse_id := data.get("input", {}).get("warehouse_id"):
- warehouse = cls.get_node_or_error(
- info, warehouse_id, only_type="Warehouse", field="warehouse_id"
- )
-
- cls.validate_fulfillment(fulfillment, warehouse)
-
- if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
- fulfillment = cancel_waiting_fulfillment(
- fulfillment,
- info.context.user,
- info.context.app,
- info.context.plugins,
- )
- else:
- fulfillment = cancel_fulfillment(
- fulfillment,
- info.context.user,
- info.context.app,
- warehouse,
- info.context.plugins,
- )
- order.refresh_from_db(fields=["status"])
- return FulfillmentCancel(fulfillment=fulfillment, order=order)
-
-
-class FulfillmentApprove(BaseMutation):
- fulfillment = graphene.Field(Fulfillment, description="An approved fulfillment.")
- order = graphene.Field(Order, description="Order which fulfillment was approved.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a fulfillment to approve.")
- notify_customer = graphene.Boolean(
- required=True, description="True if confirmation email should be send."
- )
- allow_stock_to_be_exceeded = graphene.Boolean(
- default_value=False, description="True if stock could be exceeded."
- )
-
- class Meta:
- description = "Approve existing fulfillment." + ADDED_IN_31
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_input(cls, info, fulfillment):
- if fulfillment.status != FulfillmentStatus.WAITING_FOR_APPROVAL:
- raise ValidationError(
- "Invalid fulfillment status, only WAITING_FOR_APPROVAL "
- "fulfillments can be accepted.",
- code=OrderErrorCode.INVALID.value,
- )
-
- OrderFulfill.check_lines_for_preorder([line.order_line for line in fulfillment])
-
- if (
- not info.context.site.settings.fulfillment_allow_unpaid
- and not fulfillment.order.is_fully_paid()
- ):
- raise ValidationError(
- "Cannot fulfill unpaid order.",
- code=OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER,
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- fulfillment = cls.get_node_or_error(info, data["id"], only_type="Fulfillment")
- cls.clean_input(info, fulfillment)
-
- order = fulfillment.order
-
- try:
- fulfillment = approve_fulfillment(
- fulfillment,
- info.context.user,
- info.context.app,
- info.context.plugins,
- info.context.site.settings,
- notify_customer=data["notify_customer"],
- allow_stock_to_be_exceeded=data.get("allow_stock_to_be_exceeded"),
- )
- except InsufficientStock as exc:
- errors = prepare_insufficient_stock_order_validation_errors(exc)
- raise ValidationError({"stocks": errors})
-
- order.refresh_from_db(fields=["status"])
- return FulfillmentApprove(fulfillment=fulfillment, order=order)
-
-
-class OrderRefundLineInput(graphene.InputObjectType):
- order_line_id = graphene.ID(
- description="The ID of the order line to refund.",
- name="orderLineId",
- required=True,
- )
- quantity = graphene.Int(
- description="The number of items to be refunded.",
- required=True,
- )
-
-
-class OrderRefundFulfillmentLineInput(graphene.InputObjectType):
- fulfillment_line_id = graphene.ID(
- description="The ID of the fulfillment line to refund.",
- name="fulfillmentLineId",
- required=True,
- )
- quantity = graphene.Int(
- description="The number of items to be refunded.",
- required=True,
- )
-
-
-class OrderRefundProductsInput(graphene.InputObjectType):
- order_lines = NonNullList(
- OrderRefundLineInput,
- description="List of unfulfilled lines to refund.",
- )
- fulfillment_lines = NonNullList(
- OrderRefundFulfillmentLineInput,
- description="List of fulfilled lines to refund.",
- )
- amount_to_refund = PositiveDecimal(
- required=False,
- description="The total amount of refund when the value is provided manually.",
- )
- include_shipping_costs = graphene.Boolean(
- description=(
- "If true, Saleor will refund shipping costs. If amountToRefund is provided"
- "includeShippingCosts will be ignored."
- ),
- default_value=False,
- )
-
-
-class FulfillmentRefundAndReturnProductBase(BaseMutation):
- class Meta:
- abstract = True
-
- @classmethod
- def clean_order_payment(cls, payment, cleaned_input):
- if not payment or not payment.can_refund():
- raise ValidationError(
- {
- "order": ValidationError(
- "Order cannot be refunded.",
- code=OrderErrorCode.CANNOT_REFUND.value,
- )
- }
- )
- cleaned_input["payment"] = payment
-
- @classmethod
- def clean_amount_to_refund(
- cls, order, amount_to_refund, captured_value, cleaned_input
- ):
- if amount_to_refund is not None:
- if order_has_gift_card_lines(order):
- raise ValidationError(
- {
- "amount_to_refund": ValidationError(
- (
- "Cannot specified amount to refund when order has "
- "gift card lines."
- ),
- code=OrderErrorCode.CANNOT_REFUND.value,
- )
- }
- )
-
- if amount_to_refund > captured_value:
- raise ValidationError(
- {
- "amount_to_refund": ValidationError(
- (
- "The amountToRefund is greater than the maximal "
- "possible amount to refund."
- ),
- code=OrderErrorCode.CANNOT_REFUND.value,
- ),
- }
- )
- cleaned_input["amount_to_refund"] = amount_to_refund
-
- @classmethod
- def _raise_error_for_line(cls, msg, type, line_id, field_name, code=None):
- line_global_id = graphene.Node.to_global_id(type, line_id)
- if not code:
- code = OrderErrorCode.INVALID_QUANTITY.value
- raise ValidationError(
- {
- field_name: ValidationError(
- msg,
- code=code,
- params={field_name: line_global_id},
- )
- }
- )
-
- @classmethod
- def raise_error_for_payment_error(cls, transactions: Optional[TransactionItem]):
- if transactions:
- code = OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.value
- msg = "No app or plugin is configured to handle payment action requests."
- else:
- msg = "The refund operation is not available yet."
- code = OrderErrorCode.CANNOT_REFUND.value
- raise ValidationError(
- msg,
- code=code,
- )
-
- @classmethod
- def clean_fulfillment_lines(
- cls, fulfillment_lines_data, cleaned_input, whitelisted_statuses
- ):
- fulfillment_lines = cls.get_nodes_or_error(
- [line["fulfillment_line_id"] for line in fulfillment_lines_data],
- field="fulfillment_lines",
- only_type=FulfillmentLine,
- qs=order_models.FulfillmentLine.objects.prefetch_related(
- "fulfillment", "order_line"
- ),
- )
- fulfillment_lines = list(fulfillment_lines)
- cleaned_fulfillment_lines = []
- for line, line_data in zip(fulfillment_lines, fulfillment_lines_data):
- quantity = line_data["quantity"]
- if line.order_line.is_gift_card:
- cls._raise_error_for_line(
- "Cannot refund or return gift card line.",
- "FulfillmentLine",
- line.pk,
- "fulfillment_line_id",
- OrderErrorCode.GIFT_CARD_LINE.value,
- )
- if line.quantity < quantity:
- cls._raise_error_for_line(
- "Provided quantity is bigger than quantity from "
- "fulfillment line",
- "FulfillmentLine",
- line.pk,
- "fulfillment_line_id",
- )
- if line.fulfillment.status not in whitelisted_statuses:
- allowed_statuses_str = ", ".join(whitelisted_statuses)
- cls._raise_error_for_line(
- f"Unable to process action for fulfillmentLine with different "
- f"status than {allowed_statuses_str}.",
- "FulfillmentLine",
- line.pk,
- "fulfillment_line_id",
- code=OrderErrorCode.INVALID.value,
- )
- replace = line_data.get("replace", False)
- if replace and not line.order_line.variant_id:
- cls._raise_error_for_line(
- "Unable to replace line as the assigned product doesn't exist.",
- "OrderLine",
- line.pk,
- "order_line_id",
- )
- cleaned_fulfillment_lines.append(
- FulfillmentLineData(
- line=line,
- quantity=quantity,
- replace=replace,
- )
- )
- cleaned_input["fulfillment_lines"] = cleaned_fulfillment_lines
-
- @classmethod
- def clean_lines(cls, lines_data, cleaned_input):
- order_lines = cls.get_nodes_or_error(
- [line["order_line_id"] for line in lines_data],
- field="order_lines",
- only_type=OrderLine,
- qs=order_models.OrderLine.objects.prefetch_related(
- "fulfillment_lines__fulfillment", "variant", "allocations"
- ),
- )
- order_lines = list(order_lines)
- cleaned_order_lines = []
- for line, line_data in zip(order_lines, lines_data):
- quantity = line_data["quantity"]
- if line.is_gift_card:
- cls._raise_error_for_line(
- "Cannot refund or return gift card line.",
- "OrderLine",
- line.pk,
- "order_line_id",
- OrderErrorCode.GIFT_CARD_LINE.value,
- )
- if line.quantity < quantity:
- cls._raise_error_for_line(
- "Provided quantity is bigger than quantity from order line.",
- "OrderLine",
- line.pk,
- "order_line_id",
- )
- quantity_ready_to_move = line.quantity_unfulfilled
- if quantity_ready_to_move < quantity:
- cls._raise_error_for_line(
- "Provided quantity is bigger than unfulfilled quantity.",
- "OrderLine",
- line.pk,
- "order_line_id",
- )
- variant = line.variant
- replace = line_data.get("replace", False)
- if replace and not line.variant_id:
- cls._raise_error_for_line(
- "Unable to replace line as the assigned product doesn't exist.",
- "OrderLine",
- line.pk,
- "order_line_id",
- )
-
- cleaned_order_lines.append(
- OrderLineInfo(
- line=line, quantity=quantity, variant=variant, replace=replace
- )
- )
- cleaned_input["order_lines"] = cleaned_order_lines
-
-
-class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
- fulfillment = graphene.Field(Fulfillment, description="A refunded fulfillment.")
- order = graphene.Field(Order, description="Order which fulfillment was refunded.")
-
- class Arguments:
- order = graphene.ID(
- description="ID of the order to be refunded.", required=True
- )
- input = OrderRefundProductsInput(
- required=True,
- description="Fields required to create an refund fulfillment.",
- )
-
- class Meta:
- description = "Refund products."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_input(cls, info, order_id, input):
- cleaned_input = {}
- amount_to_refund = input.get("amount_to_refund")
- include_shipping_costs = input["include_shipping_costs"]
-
- qs = order_models.Order.objects.prefetch_related("payments")
- order = cls.get_node_or_error(
- info, order_id, field="order", only_type=Order, qs=qs
- )
- payment = order.get_last_payment()
- transactions = list(order.payment_transactions.all())
- if transactions:
- # For know we handle refunds only for last transaction. We need to add an
- # interface to process a refund requests on multiple transactions
- captured_value = transactions[-1].captured_value
- else:
- cls.clean_order_payment(payment, cleaned_input)
- captured_value = payment.captured_amount
- cls.clean_amount_to_refund(
- order, amount_to_refund, captured_value, cleaned_input
- )
-
- cleaned_input.update(
- {
- "include_shipping_costs": include_shipping_costs,
- "order": order,
- "transactions": transactions,
- "payment": payment,
- }
- )
-
- order_lines_data = input.get("order_lines", [])
- fulfillment_lines_data = input.get("fulfillment_lines", [])
-
- if order_lines_data:
- cls.clean_lines(order_lines_data, cleaned_input)
- if fulfillment_lines_data:
- cls.clean_fulfillment_lines(
- fulfillment_lines_data,
- cleaned_input,
- whitelisted_statuses=[
- FulfillmentStatus.FULFILLED,
- FulfillmentStatus.RETURNED,
- FulfillmentStatus.WAITING_FOR_APPROVAL,
- ],
- )
- return cleaned_input
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
- order = cleaned_input["order"]
-
- try:
- refund_fulfillment = create_refund_fulfillment(
- info.context.user,
- info.context.app,
- order,
- cleaned_input["payment"],
- cleaned_input["transactions"],
- cleaned_input.get("order_lines", []),
- cleaned_input.get("fulfillment_lines", []),
- info.context.plugins,
- cleaned_input["amount_to_refund"],
- cleaned_input["include_shipping_costs"],
- )
- except PaymentError:
- cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
- return cls(order=order, fulfillment=refund_fulfillment)
-
-
-class OrderReturnLineInput(graphene.InputObjectType):
- order_line_id = graphene.ID(
- description="The ID of the order line to return.",
- name="orderLineId",
- required=True,
- )
- quantity = graphene.Int(
- description="The number of items to be returned.",
- required=True,
- )
- replace = graphene.Boolean(
- description="Determines, if the line should be added to replace order.",
- default_value=False,
- )
-
-
-class OrderReturnFulfillmentLineInput(graphene.InputObjectType):
- fulfillment_line_id = graphene.ID(
- description="The ID of the fulfillment line to return.",
- name="fulfillmentLineId",
- required=True,
- )
- quantity = graphene.Int(
- description="The number of items to be returned.",
- required=True,
- )
- replace = graphene.Boolean(
- description="Determines, if the line should be added to replace order.",
- default_value=False,
- )
-
-
-class OrderReturnProductsInput(graphene.InputObjectType):
- order_lines = NonNullList(
- OrderReturnLineInput,
- description="List of unfulfilled lines to return.",
- )
- fulfillment_lines = NonNullList(
- OrderReturnFulfillmentLineInput,
- description="List of fulfilled lines to return.",
- )
- amount_to_refund = PositiveDecimal(
- required=False,
- description="The total amount of refund when the value is provided manually.",
- )
- include_shipping_costs = graphene.Boolean(
- description=(
- "If true, Saleor will refund shipping costs. If amountToRefund is provided"
- "includeShippingCosts will be ignored."
- ),
- default_value=False,
- )
- refund = graphene.Boolean(
- description="If true, Saleor will call refund action for all lines.",
- default_value=False,
- )
-
-
-class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
- return_fulfillment = graphene.Field(
- Fulfillment, description="A return fulfillment."
- )
- replace_fulfillment = graphene.Field(
- Fulfillment, description="A replace fulfillment."
- )
- order = graphene.Field(Order, description="Order which fulfillment was returned.")
- replace_order = graphene.Field(
- Order,
- description="A draft order which was created for products with replace flag.",
- )
-
- class Meta:
- description = "Return products."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- class Arguments:
- order = graphene.ID(
- description="ID of the order to be returned.", required=True
- )
- input = OrderReturnProductsInput(
- required=True,
- description="Fields required to return products.",
- )
-
- @classmethod
- def clean_input(cls, info, order_id, input):
- cleaned_input = {}
- amount_to_refund = input.get("amount_to_refund")
- include_shipping_costs = input["include_shipping_costs"]
- refund = input["refund"]
-
- qs = order_models.Order.objects.prefetch_related("payments")
- order = cls.get_node_or_error(
- info, order_id, field="order", only_type=Order, qs=qs
- )
- if refund:
- payment = order.get_last_payment()
- transactions = list(order.payment_transactions.all())
- if transactions:
- # For know we handle refunds only for last transaction. We need to add
- # an interface to process a refund requests on multiple transactions
- captured_value = transactions[-1].captured_value
- else:
- cls.clean_order_payment(payment, cleaned_input)
- captured_value = payment.captured_amount
- cls.clean_amount_to_refund(
- order, amount_to_refund, captured_value, cleaned_input
- )
- cleaned_input["transactions"] = transactions
-
- cleaned_input.update(
- {
- "include_shipping_costs": include_shipping_costs,
- "order": order,
- "refund": refund,
- }
- )
-
- order_lines_data = input.get("order_lines")
- fulfillment_lines_data = input.get("fulfillment_lines")
-
- if order_lines_data:
- cls.clean_lines(order_lines_data, cleaned_input)
- if fulfillment_lines_data:
- cls.clean_fulfillment_lines(
- fulfillment_lines_data,
- cleaned_input,
- whitelisted_statuses=[
- FulfillmentStatus.FULFILLED,
- FulfillmentStatus.REFUNDED,
- FulfillmentStatus.WAITING_FOR_APPROVAL,
- ],
- )
- return cleaned_input
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
- order = cleaned_input["order"]
- try:
- response = create_fulfillments_for_returned_products(
- info.context.user,
- info.context.app,
- order,
- cleaned_input.get("payment"),
- cleaned_input.get("transactions"),
- cleaned_input.get("order_lines", []),
- cleaned_input.get("fulfillment_lines", []),
- info.context.plugins,
- cleaned_input["refund"],
- cleaned_input.get("amount_to_refund"),
- cleaned_input["include_shipping_costs"],
- )
- except PaymentError:
- cls.raise_error_for_payment_error(cleaned_input.get("transactions"))
-
- return_fulfillment, replace_fulfillment, replace_order = response
- return cls(
- order=order,
- return_fulfillment=return_fulfillment,
- replace_fulfillment=replace_fulfillment,
- replace_order=replace_order,
- )
diff --git a/saleor/graphql/order/mutations/order_add_note.py b/saleor/graphql/order/mutations/order_add_note.py
new file mode 100644
index 0000000000..34a7e1208e
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_add_note.py
@@ -0,0 +1,70 @@
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.error_codes import OrderErrorCode
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ...core.utils import validate_required_string_field
+from ..types import Order, OrderEvent
+from .utils import get_webhook_handler_by_order_status
+
+
+class OrderAddNoteInput(graphene.InputObjectType):
+ message = graphene.String(
+ description="Note message.", name="message", required=True
+ )
+
+
+class OrderAddNote(BaseMutation):
+ order = graphene.Field(Order, description="Order with the note added.")
+ event = graphene.Field(OrderEvent, description="Order note created.")
+
+ class Arguments:
+ id = graphene.ID(
+ required=True,
+ description="ID of the order to add a note for.",
+ name="order",
+ )
+ input = OrderAddNoteInput(
+ required=True, description="Fields required to create a note for the order."
+ )
+
+ class Meta:
+ description = "Adds note to the order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, _info, _instance, data):
+ try:
+ cleaned_input = validate_required_string_field(data["input"], "message")
+ except ValidationError:
+ raise ValidationError(
+ {
+ "message": ValidationError(
+ "Message can't be empty.",
+ code=OrderErrorCode.REQUIRED,
+ )
+ }
+ )
+ return cleaned_input
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ cleaned_input = cls.clean_input(info, order, data)
+ event = events.order_note_added_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ message=cleaned_input["message"],
+ )
+ func = get_webhook_handler_by_order_status(order.status, info)
+ transaction.on_commit(lambda: func(order))
+ return OrderAddNote(order=order, event=event)
diff --git a/saleor/graphql/order/mutations/order_cancel.py b/saleor/graphql/order/mutations/order_cancel.py
new file mode 100644
index 0000000000..97554a33e2
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_cancel.py
@@ -0,0 +1,52 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....giftcard.utils import deactivate_order_gift_cards
+from ....order.actions import cancel_order
+from ....order.error_codes import OrderErrorCode
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Order
+
+
+def clean_order_cancel(order):
+ if order and not order.can_cancel():
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "This order can't be canceled.",
+ code=OrderErrorCode.CANNOT_CANCEL_ORDER,
+ )
+ }
+ )
+
+
+class OrderCancel(BaseMutation):
+ order = graphene.Field(Order, description="Canceled order.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the order to cancel.")
+
+ class Meta:
+ description = "Cancel an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ clean_order_cancel(order)
+ user = info.context.user
+ app = info.context.app
+ cancel_order(
+ order=order,
+ user=user,
+ app=app,
+ manager=info.context.plugins,
+ )
+ deactivate_order_gift_cards(order.id, user, app)
+ return OrderCancel(order=order)
diff --git a/saleor/graphql/order/mutations/order_capture.py b/saleor/graphql/order/mutations/order_capture.py
new file mode 100644
index 0000000000..478149753e
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_capture.py
@@ -0,0 +1,104 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....order.actions import order_captured
+from ....order.error_codes import OrderErrorCode
+from ....order.fetch import fetch_order_info
+from ....payment import PaymentError, TransactionKind, gateway
+from ....payment.gateway import request_capture_action
+from ...core.mutations import BaseMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types import OrderError
+from ..types import Order
+from .utils import clean_payment, try_payment_action
+
+
+def clean_order_capture(payment):
+ clean_payment(payment)
+ if not payment.is_active:
+ raise ValidationError(
+ {
+ "payment": ValidationError(
+ "Only pre-authorized payments can be captured",
+ code=OrderErrorCode.CAPTURE_INACTIVE_PAYMENT,
+ )
+ }
+ )
+
+
+class OrderCapture(BaseMutation):
+ order = graphene.Field(Order, description="Captured order.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the order to capture.")
+ amount = PositiveDecimal(
+ required=True, description="Amount of money to capture."
+ )
+
+ class Meta:
+ description = "Capture an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, amount, **data):
+ if amount <= 0:
+ raise ValidationError(
+ {
+ "amount": ValidationError(
+ "Amount should be a positive number.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ )
+ }
+ )
+
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+
+ if payment_transactions := list(order.payment_transactions.all()):
+ try:
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ payment_transaction = payment_transactions[-1]
+ request_capture_action(
+ transaction=payment_transaction,
+ manager=info.context.plugins,
+ capture_value=amount,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ else:
+ order_info = fetch_order_info(order)
+ payment = order_info.payment
+ clean_order_capture(payment)
+ transaction = try_payment_action(
+ order,
+ info.context.user,
+ info.context.app,
+ payment,
+ gateway.capture,
+ payment,
+ info.context.plugins,
+ amount=amount,
+ channel_slug=order.channel.slug,
+ )
+ order_info.payment.refresh_from_db()
+ # Confirm that we changed the status to capture. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.CAPTURE:
+ order_captured(
+ order_info,
+ info.context.user,
+ info.context.app,
+ amount,
+ payment,
+ info.context.plugins,
+ )
+ return OrderCapture(order=order)
diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.py
new file mode 100644
index 0000000000..d4a471851e
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_confirm.py
@@ -0,0 +1,101 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import OrderStatus, models
+from ....order.actions import order_captured, order_confirmed
+from ....order.error_codes import OrderErrorCode
+from ....order.fetch import fetch_order_info
+from ....payment import PaymentError, gateway
+from ....payment.gateway import request_capture_action
+from ...core.mutations import ModelMutation
+from ...core.types import OrderError
+from ..types import Order
+
+
+class OrderConfirm(ModelMutation):
+ order = graphene.Field(Order, description="Order which has been confirmed.")
+
+ class Arguments:
+ id = graphene.ID(description="ID of an order to confirm.", required=True)
+
+ class Meta:
+ description = "Confirms an unconfirmed order by changing status to unfulfilled."
+ model = models.Order
+ object_type = Order
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def get_instance(cls, info, **data):
+ instance = super().get_instance(info, **data)
+ if not instance.is_unconfirmed():
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Provided order id belongs to an order with status "
+ "different than unconfirmed.",
+ code=OrderErrorCode.INVALID,
+ )
+ }
+ )
+ if not instance.lines.exists():
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Provided order id belongs to an order without products.",
+ code=OrderErrorCode.INVALID,
+ )
+ }
+ )
+ return instance
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, root, info, **data):
+ order = cls.get_instance(info, **data)
+ order.status = OrderStatus.UNFULFILLED
+ order.save(update_fields=["status", "updated_at"])
+ order_info = fetch_order_info(order)
+ payment = order_info.payment
+ manager = info.context.plugins
+ if payment_transactions := list(order.payment_transactions.all()):
+ try:
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ payment_transaction = payment_transactions[-1]
+ request_capture_action(
+ transaction=payment_transaction,
+ manager=info.context.plugins,
+ capture_value=payment_transaction.captured_value,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ elif payment and payment.is_authorized and payment.can_capture():
+ gateway.capture(
+ payment, info.context.plugins, channel_slug=order.channel.slug
+ )
+ order_captured(
+ order_info,
+ info.context.user,
+ info.context.app,
+ payment.total,
+ payment,
+ manager,
+ )
+ order_confirmed(
+ order,
+ info.context.user,
+ info.context.app,
+ manager,
+ send_confirmation_email=True,
+ )
+ return OrderConfirm(order=order)
diff --git a/saleor/graphql/order/mutations/order_discount_add.py b/saleor/graphql/order/mutations/order_discount_add.py
new file mode 100644
index 0000000000..34eb96c84a
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_discount_add.py
@@ -0,0 +1,71 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.error_codes import OrderErrorCode
+from ....order.utils import create_order_discount_for_order, get_order_discounts
+from ...core.types import OrderError
+from ..types import Order
+from .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput
+
+
+class OrderDiscountAdd(OrderDiscountCommon):
+ order = graphene.Field(Order, description="Order which has been discounted.")
+
+ class Arguments:
+ order_id = graphene.ID(description="ID of an order to discount.", required=True)
+ input = OrderDiscountCommonInput(
+ required=True,
+ description="Fields required to create a discount for the order.",
+ )
+
+ class Meta:
+ description = "Adds discount to the order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def validate_order(cls, info, order):
+ super().validate_order(info, order)
+ # This condition can be removed when we introduce support for multi discounts.
+ order_discounts = get_order_discounts(order)
+ if len(order_discounts) >= 1:
+ error_msg = "Order already has assigned discount."
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ error_msg, code=OrderErrorCode.CANNOT_DISCOUNT.value
+ )
+ }
+ )
+
+ @classmethod
+ def validate(cls, info, order, input):
+ cls.validate_order(info, order)
+ cls.validate_order_discount_input(info, order.undiscounted_total.gross, input)
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("order_id"), only_type=Order)
+ input = data.get("input", {})
+ cls.validate(info, order, input)
+
+ reason = input.get("reason")
+ value_type = input.get("value_type")
+ value = input.get("value")
+
+ order_discount = create_order_discount_for_order(
+ order, reason, value_type, value
+ )
+
+ events.order_discount_added_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ order_discount=order_discount,
+ )
+ return OrderDiscountAdd(order=order)
diff --git a/saleor/graphql/order/mutations/order_discount_common.py b/saleor/graphql/order/mutations/order_discount_common.py
new file mode 100644
index 0000000000..4e951a778d
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_discount_common.py
@@ -0,0 +1,78 @@
+import graphene
+from django.core.exceptions import ValidationError
+from prices import Money
+
+from ....order import models
+from ....order.error_codes import OrderErrorCode
+from ....order.utils import recalculate_order_discounts, recalculate_order_prices
+from ...core.mutations import BaseMutation
+from ...core.scalars import PositiveDecimal
+from ...discount.enums import DiscountValueTypeEnum
+
+
+class OrderDiscountCommonInput(graphene.InputObjectType):
+ value_type = graphene.Field(
+ DiscountValueTypeEnum,
+ required=True,
+ description="Type of the discount: fixed or percent",
+ )
+ value = PositiveDecimal(
+ required=True,
+ description="Value of the discount. Can store fixed value or percent value",
+ )
+ reason = graphene.String(
+ required=False, description="Explanation for the applied discount."
+ )
+
+
+class OrderDiscountCommon(BaseMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def validate_order(cls, info, order):
+ if not (order.is_draft() or order.is_unconfirmed()):
+ error_msg = "Only draft and unconfirmed order can be modified."
+ raise ValidationError(
+ {
+ "orderId": ValidationError(
+ error_msg, code=OrderErrorCode.CANNOT_DISCOUNT.value
+ )
+ }
+ )
+
+ @classmethod
+ def _validation_error_for_input_value(
+ cls, error_msg, code=OrderErrorCode.INVALID.value
+ ):
+ return ValidationError({"value": ValidationError(error_msg, code=code)})
+
+ @classmethod
+ def validate_order_discount_input(cls, _info, max_total: Money, input: dict):
+ value_type = input["value_type"]
+ value = input["value"]
+ if value_type == DiscountValueTypeEnum.FIXED:
+ if value > max_total.amount:
+ error_msg = (
+ f"The value ({value}) cannot be higher than {max_total.amount} "
+ f"{max_total.currency}"
+ )
+ raise cls._validation_error_for_input_value(error_msg)
+ elif value > 100:
+ error_msg = f"The percentage value ({value}) cannot be higher than 100."
+ raise cls._validation_error_for_input_value(error_msg)
+
+ @classmethod
+ def recalculate_order(cls, order: models.Order):
+ """Recalculate order data and save them."""
+ recalculate_order_prices(order)
+ recalculate_order_discounts(order)
+ order.save(
+ update_fields=[
+ "total_net_amount",
+ "total_gross_amount",
+ "undiscounted_total_net_amount",
+ "undiscounted_total_gross_amount",
+ "updated_at",
+ ]
+ )
diff --git a/saleor/graphql/order/mutations/order_discount_delete.py b/saleor/graphql/order/mutations/order_discount_delete.py
new file mode 100644
index 0000000000..d96a812d60
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_discount_delete.py
@@ -0,0 +1,49 @@
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.search import update_order_search_document
+from ....order.utils import remove_order_discount_from_order
+from ...core.types import OrderError
+from ..types import Order
+from .order_discount_common import OrderDiscountCommon
+
+
+class OrderDiscountDelete(OrderDiscountCommon):
+ order = graphene.Field(Order, description="Order which has removed discount.")
+
+ class Arguments:
+ discount_id = graphene.ID(
+ description="ID of a discount to remove.", required=True
+ )
+
+ class Meta:
+ description = "Remove discount from the order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order_discount = cls.get_node_or_error(
+ info, data.get("discount_id"), only_type="OrderDiscount"
+ )
+ order = order_discount.order
+ cls.validate_order(info, order)
+
+ remove_order_discount_from_order(order, order_discount)
+ events.order_discount_deleted_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ order_discount=order_discount,
+ )
+
+ order.refresh_from_db()
+
+ cls.recalculate_order(order)
+ update_order_search_document(order)
+
+ return OrderDiscountDelete(order=order)
diff --git a/saleor/graphql/order/mutations/order_discount_update.py b/saleor/graphql/order/mutations/order_discount_update.py
new file mode 100644
index 0000000000..a243e02ff9
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_discount_update.py
@@ -0,0 +1,75 @@
+import copy
+
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ...core.types import OrderError
+from ..types import Order
+from .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput
+
+
+class OrderDiscountUpdate(OrderDiscountCommon):
+ order = graphene.Field(Order, description="Order which has been discounted.")
+
+ class Arguments:
+ discount_id = graphene.ID(
+ description="ID of a discount to update.", required=True
+ )
+ input = OrderDiscountCommonInput(
+ required=True,
+ description="Fields required to update a discount for the order.",
+ )
+
+ class Meta:
+ description = "Update discount for the order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def validate(cls, info, order, order_discount, input):
+ cls.validate_order(info, order)
+ input["value"] = input.get("value") or order_discount.value
+ input["value_type"] = input.get("value_type") or order_discount.value_type
+
+ cls.validate_order_discount_input(info, order.undiscounted_total.gross, input)
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order_discount = cls.get_node_or_error(
+ info, data.get("discount_id"), only_type="OrderDiscount"
+ )
+ order = order_discount.order
+ input = data.get("input")
+ cls.validate(info, order, order_discount, input)
+
+ reason = input.get("reason", order_discount.reason)
+ value_type = input.get("value_type", order_discount.value_type)
+ value = input.get("value", order_discount.value)
+
+ order_discount_before_update = copy.deepcopy(order_discount)
+
+ order_discount.reason = reason
+ order_discount.value = value
+ order_discount.value_type = value_type
+ order_discount.save()
+
+ cls.recalculate_order(order)
+
+ if (
+ order_discount_before_update.value_type != value_type
+ or order_discount_before_update.value != value
+ ):
+ # call update event only when we changed the type or value of the discount
+ order_discount.refresh_from_db()
+ events.order_discount_updated_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ order_discount=order_discount,
+ old_order_discount=order_discount_before_update,
+ )
+ return OrderDiscountUpdate(order=order)
diff --git a/saleor/graphql/order/mutations/order_fulfill.py b/saleor/graphql/order/mutations/order_fulfill.py
new file mode 100644
index 0000000000..dbd4c4e88b
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_fulfill.py
@@ -0,0 +1,269 @@
+from collections import defaultdict
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.template.defaultfilters import pluralize
+
+from ....core.exceptions import InsufficientStock
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import models as order_models
+from ....order.actions import create_fulfillments
+from ....order.error_codes import OrderErrorCode
+from ...core.mutations import BaseMutation
+from ...core.types import NonNullList, OrderError
+from ...core.utils import get_duplicated_values
+from ...warehouse.types import Warehouse
+from ..types import Fulfillment, Order, OrderLine
+from ..utils import prepare_insufficient_stock_order_validation_errors
+
+
+class OrderFulfillStockInput(graphene.InputObjectType):
+ quantity = graphene.Int(
+ description="The number of line items to be fulfilled from given warehouse.",
+ required=True,
+ )
+ warehouse = graphene.ID(
+ description="ID of the warehouse from which the item will be fulfilled.",
+ required=True,
+ )
+
+
+class OrderFulfillLineInput(graphene.InputObjectType):
+ order_line_id = graphene.ID(
+ description="The ID of the order line.", name="orderLineId"
+ )
+ stocks = NonNullList(
+ OrderFulfillStockInput,
+ required=True,
+ description="List of stock items to create.",
+ )
+
+
+class OrderFulfillInput(graphene.InputObjectType):
+ lines = NonNullList(
+ OrderFulfillLineInput,
+ required=True,
+ description="List of items informing how to fulfill the order.",
+ )
+ notify_customer = graphene.Boolean(
+ description="If true, send an email notification to the customer."
+ )
+
+ allow_stock_to_be_exceeded = graphene.Boolean(
+ description="If true, then allow proceed fulfillment when stock is exceeded.",
+ default_value=False,
+ )
+
+
+class FulfillmentUpdateTrackingInput(graphene.InputObjectType):
+ tracking_number = graphene.String(description="Fulfillment tracking number.")
+ notify_customer = graphene.Boolean(
+ default_value=False,
+ description="If true, send an email notification to the customer.",
+ )
+
+
+class OrderFulfill(BaseMutation):
+ fulfillments = NonNullList(Fulfillment, description="List of created fulfillments.")
+ order = graphene.Field(Order, description="Fulfilled order.")
+
+ class Arguments:
+ order = graphene.ID(
+ description="ID of the order to be fulfilled.", name="order"
+ )
+ input = OrderFulfillInput(
+ required=True, description="Fields required to create a fulfillment."
+ )
+
+ class Meta:
+ description = "Creates new fulfillments for an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_lines(cls, order_lines, quantities_for_lines):
+ for order_line, line_quantities in zip(order_lines, quantities_for_lines):
+ line_total_quantity = sum(line_quantities)
+ line_quantity_unfulfilled = order_line.quantity_unfulfilled
+
+ if line_total_quantity > line_quantity_unfulfilled:
+ msg = (
+ "Only %(quantity)d item%(item_pluralize)s remaining "
+ "to fulfill: %(order_line)s."
+ ) % {
+ "quantity": line_quantity_unfulfilled,
+ "item_pluralize": pluralize(line_quantity_unfulfilled),
+ "order_line": order_line,
+ }
+ order_line_global_id = graphene.Node.to_global_id(
+ "OrderLine", order_line.pk
+ )
+ raise ValidationError(
+ {
+ "order_line_id": ValidationError(
+ msg,
+ code=OrderErrorCode.FULFILL_ORDER_LINE,
+ params={"order_lines": [order_line_global_id]},
+ )
+ }
+ )
+
+ @classmethod
+ def check_warehouses_for_duplicates(cls, warehouse_ids):
+ for warehouse_ids_for_line in warehouse_ids:
+ duplicates = get_duplicated_values(warehouse_ids_for_line)
+ if duplicates:
+ raise ValidationError(
+ {
+ "warehouse": ValidationError(
+ "Duplicated warehouse ID.",
+ code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
+ params={"warehouse": duplicates.pop()},
+ )
+ }
+ )
+
+ @classmethod
+ def check_lines_for_duplicates(cls, lines_ids):
+ duplicates = get_duplicated_values(lines_ids)
+ if duplicates:
+ raise ValidationError(
+ {
+ "orderLineId": ValidationError(
+ "Duplicated order line ID.",
+ code=OrderErrorCode.DUPLICATED_INPUT_ITEM,
+ params={"order_lines": [duplicates.pop()]},
+ )
+ }
+ )
+
+ @classmethod
+ def check_lines_for_preorder(cls, order_lines):
+ for order_line in order_lines:
+ if order_line.variant_id and order_line.variant.is_preorder_active():
+ order_line_global_id = graphene.Node.to_global_id(
+ "OrderLine", order_line.pk
+ )
+ raise ValidationError(
+ {
+ "order_line_id": ValidationError(
+ "Can not fulfill preorder variant.",
+ code=OrderErrorCode.FULFILL_ORDER_LINE,
+ params={"order_lines": [order_line_global_id]},
+ )
+ }
+ )
+
+ @classmethod
+ def check_total_quantity_of_items(cls, quantities_for_lines):
+ flat_quantities = sum(quantities_for_lines, [])
+ if sum(flat_quantities) <= 0:
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Total quantity must be larger than 0.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ )
+ }
+ )
+
+ @classmethod
+ def clean_input(cls, info, order, data):
+ site_settings = info.context.site.settings
+ if not order.is_fully_paid() and (
+ site_settings.fulfillment_auto_approve
+ and not site_settings.fulfillment_allow_unpaid
+ ):
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "Cannot fulfill unpaid order.",
+ code=OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.value,
+ )
+ }
+ )
+
+ lines = data["lines"]
+
+ warehouse_ids_for_lines = [
+ [stock["warehouse"] for stock in line["stocks"]] for line in lines
+ ]
+ cls.check_warehouses_for_duplicates(warehouse_ids_for_lines)
+
+ quantities_for_lines = [
+ [stock["quantity"] for stock in line["stocks"]] for line in lines
+ ]
+
+ lines_ids = [line["order_line_id"] for line in lines]
+ cls.check_lines_for_duplicates(lines_ids)
+ order_lines = cls.get_nodes_or_error(
+ lines_ids, field="lines", only_type=OrderLine
+ )
+
+ cls.clean_lines(order_lines, quantities_for_lines)
+
+ if site_settings.fulfillment_auto_approve:
+ cls.check_lines_for_preorder(order_lines)
+
+ cls.check_total_quantity_of_items(quantities_for_lines)
+
+ lines_for_warehouses = defaultdict(list)
+ for line, order_line in zip(lines, order_lines):
+ for stock in line["stocks"]:
+ if stock["quantity"] > 0:
+ warehouse_pk = cls.get_global_id_or_error(
+ stock["warehouse"], only_type=Warehouse, field="warehouse"
+ )
+ lines_for_warehouses[warehouse_pk].append(
+ {"order_line": order_line, "quantity": stock["quantity"]}
+ )
+
+ data["order_lines"] = order_lines
+ data["lines_for_warehouses"] = lines_for_warehouses
+ return data
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, order, **data):
+ order = cls.get_node_or_error(
+ info,
+ order,
+ field="order",
+ only_type=Order,
+ qs=order_models.Order.objects.prefetch_related("lines__variant"),
+ )
+ data = data.get("input")
+
+ cleaned_input = cls.clean_input(info, order, data)
+
+ context = info.context
+ user = context.user if not context.user.is_anonymous else None
+ app = context.app
+ manager = context.plugins
+ lines_for_warehouses = cleaned_input["lines_for_warehouses"]
+ notify_customer = cleaned_input.get("notify_customer", True)
+ allow_stock_to_be_exceeded = cleaned_input.get(
+ "allow_stock_to_be_exceeded", False
+ )
+
+ approved = info.context.site.settings.fulfillment_auto_approve
+
+ try:
+ fulfillments = create_fulfillments(
+ user,
+ app,
+ order,
+ dict(lines_for_warehouses),
+ manager,
+ context.site.settings,
+ notify_customer,
+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,
+ approved=approved,
+ )
+ except InsufficientStock as exc:
+ errors = prepare_insufficient_stock_order_validation_errors(exc)
+ raise ValidationError({"stocks": errors})
+
+ return OrderFulfill(fulfillments=fulfillments, order=order)
diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.py
new file mode 100644
index 0000000000..1fdee87736
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_line_delete.py
@@ -0,0 +1,85 @@
+import graphene
+from django.db import transaction
+
+from ....core.permissions import OrderPermissions
+from ....core.taxes import zero_taxed_money
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.fetch import OrderLineInfo
+from ....order.search import update_order_search_document
+from ....order.utils import delete_order_line, recalculate_order
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Order, OrderLine
+from .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status
+
+
+class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
+ order = graphene.Field(Order, description="A related order.")
+ order_line = graphene.Field(
+ OrderLine, description="An order line that was deleted."
+ )
+
+ class Arguments:
+ id = graphene.ID(description="ID of the order line to delete.", required=True)
+
+ class Meta:
+ description = "Deletes an order line from an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, id):
+ manager = info.context.plugins
+ line = cls.get_node_or_error(
+ info,
+ id,
+ only_type=OrderLine,
+ )
+ order = line.order
+ cls.validate_order(line.order)
+
+ db_id = line.id
+ warehouse_pk = (
+ line.allocations.first().stock.warehouse.pk
+ if order.is_unconfirmed()
+ else None
+ )
+ line_info = OrderLineInfo(
+ line=line,
+ quantity=line.quantity,
+ variant=line.variant,
+ warehouse_pk=warehouse_pk,
+ )
+ delete_order_line(line_info, manager)
+ line.id = db_id
+
+ if not order.is_shipping_required():
+ order.shipping_method = None
+ order.shipping_price = zero_taxed_money(order.currency)
+ order.shipping_method_name = None
+ order.save(
+ update_fields=[
+ "currency",
+ "shipping_method",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_method_name",
+ "updated_at",
+ ]
+ )
+ # Create the removal event
+ events.order_removed_products_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ order_lines=[(line.quantity, line)],
+ )
+
+ recalculate_order(order)
+ update_order_search_document(order)
+ func = get_webhook_handler_by_order_status(order.status, info)
+ transaction.on_commit(lambda: func(order))
+ return OrderLineDelete(order=order, order_line=line)
diff --git a/saleor/graphql/order/mutations/order_line_discount_remove.py b/saleor/graphql/order/mutations/order_line_discount_remove.py
new file mode 100644
index 0000000000..5817c490cf
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_line_discount_remove.py
@@ -0,0 +1,57 @@
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.utils import recalculate_order, remove_discount_from_order_line
+from ...core.types import OrderError
+from ..types import Order, OrderLine
+from .order_discount_common import OrderDiscountCommon
+
+
+class OrderLineDiscountRemove(OrderDiscountCommon):
+ order_line = graphene.Field(
+ OrderLine, description="Order line which has removed discount."
+ )
+ order = graphene.Field(
+ Order, description="Order which is related to line which has removed discount."
+ )
+
+ class Arguments:
+ order_line_id = graphene.ID(
+ description="ID of a order line to remove its discount", required=True
+ )
+
+ class Meta:
+ description = "Remove discount applied to the order line."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def validate(cls, info, order):
+ cls.validate_order(info, order)
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ tax_included = info.context.site.settings.include_taxes_in_prices
+ order_line = cls.get_node_or_error(
+ info, data.get("order_line_id"), only_type=OrderLine
+ )
+ order = order_line.order
+ cls.validate(info, order)
+
+ remove_discount_from_order_line(
+ order_line, order, manager=info.context.plugins, tax_included=tax_included
+ )
+
+ events.order_line_discount_removed_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ line=order_line,
+ )
+
+ recalculate_order(order)
+ return OrderLineDiscountRemove(order_line=order_line, order=order)
diff --git a/saleor/graphql/order/mutations/order_line_discount_update.py b/saleor/graphql/order/mutations/order_line_discount_update.py
new file mode 100644
index 0000000000..d02fd60fdd
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_line_discount_update.py
@@ -0,0 +1,86 @@
+import copy
+
+import graphene
+
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.utils import recalculate_order, update_discount_for_order_line
+from ...core.types import OrderError
+from ..types import Order, OrderLine
+from .order_discount_common import OrderDiscountCommon, OrderDiscountCommonInput
+
+
+class OrderLineDiscountUpdate(OrderDiscountCommon):
+ order_line = graphene.Field(
+ OrderLine, description="Order line which has been discounted."
+ )
+ order = graphene.Field(
+ Order, description="Order which is related to the discounted line."
+ )
+
+ class Arguments:
+ order_line_id = graphene.ID(
+ description="ID of a order line to update price", required=True
+ )
+ input = OrderDiscountCommonInput(
+ required=True,
+ description="Fields required to update price for the order line.",
+ )
+
+ class Meta:
+ description = "Update discount for the order line."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def validate(cls, info, order, order_line, input):
+ cls.validate_order(info, order)
+ input["value"] = input.get("value") or order_line.unit_discount_value
+ input["value_type"] = input.get("value_type") or order_line.unit_discount_type
+
+ cls.validate_order_discount_input(
+ info, order_line.undiscounted_unit_price.gross, input
+ )
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+
+ order_line = cls.get_node_or_error(
+ info, data.get("order_line_id"), only_type=OrderLine
+ )
+ input = data.get("input")
+ order = order_line.order
+ cls.validate(info, order, order_line, input)
+ reason = input.get("reason")
+ value_type = input.get("value_type")
+ value = input.get("value")
+
+ order_line_before_update = copy.deepcopy(order_line)
+ tax_included = info.context.site.settings.include_taxes_in_prices
+
+ update_discount_for_order_line(
+ order_line,
+ order=order,
+ reason=reason,
+ value_type=value_type,
+ value=value,
+ manager=info.context.plugins,
+ tax_included=tax_included,
+ )
+ if (
+ order_line_before_update.unit_discount_value != value
+ or order_line_before_update.unit_discount_type != value_type
+ ):
+ # Create event only when we change type or value of the discount
+ events.order_line_discount_updated_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ line=order_line,
+ line_before_update=order_line_before_update,
+ )
+ recalculate_order(order)
+ return OrderLineDiscountUpdate(order_line=order_line, order=order)
diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.py
new file mode 100644
index 0000000000..de2b1ee867
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_line_update.py
@@ -0,0 +1,93 @@
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.exceptions import InsufficientStock
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import models
+from ....order.error_codes import OrderErrorCode
+from ....order.fetch import OrderLineInfo
+from ....order.utils import change_order_line_quantity, recalculate_order
+from ...core.mutations import ModelMutation
+from ...core.types import OrderError
+from ..types import Order, OrderLine
+from .draft_order_create import OrderLineInput
+from .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status
+
+
+class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
+ order = graphene.Field(Order, description="Related order.")
+
+ class Arguments:
+ id = graphene.ID(description="ID of the order line to update.", required=True)
+ input = OrderLineInput(
+ required=True, description="Fields required to update an order line."
+ )
+
+ class Meta:
+ description = "Updates an order line of an order."
+ model = models.OrderLine
+ object_type = OrderLine
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ instance.old_quantity = instance.quantity
+ cleaned_input = super().clean_input(info, instance, data)
+ cls.validate_order(instance.order)
+
+ quantity = data["quantity"]
+ if quantity <= 0:
+ raise ValidationError(
+ {
+ "quantity": ValidationError(
+ "Ensure this value is greater than 0.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ )
+ }
+ )
+ return cleaned_input
+
+ @classmethod
+ @traced_atomic_transaction()
+ def save(cls, info, instance, cleaned_input):
+ manager = info.context.plugins
+ warehouse_pk = (
+ instance.allocations.first().stock.warehouse.pk
+ if instance.order.is_unconfirmed()
+ else None
+ )
+ line_info = OrderLineInfo(
+ line=instance,
+ quantity=instance.quantity,
+ variant=instance.variant,
+ warehouse_pk=warehouse_pk,
+ )
+ try:
+ change_order_line_quantity(
+ info.context.user,
+ info.context.app,
+ line_info,
+ instance.old_quantity,
+ instance.quantity,
+ instance.order.channel.slug,
+ manager,
+ )
+ except InsufficientStock:
+ raise ValidationError(
+ "Cannot set new quantity because of insufficient stock.",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ )
+ recalculate_order(instance.order)
+
+ func = get_webhook_handler_by_order_status(instance.order.status, info)
+ transaction.on_commit(lambda: func(instance.order))
+
+ @classmethod
+ def success_response(cls, instance):
+ response = super().success_response(instance)
+ response.order = instance.order
+ return response
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
new file mode 100644
index 0000000000..6dbbc39325
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -0,0 +1,144 @@
+from typing import List, Tuple
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.permissions import OrderPermissions
+from ....core.taxes import TaxError
+from ....core.tracing import traced_atomic_transaction
+from ....order import events
+from ....order.error_codes import OrderErrorCode
+from ....order.search import update_order_search_document
+from ....order.utils import add_variant_to_order, recalculate_order
+from ...core.mutations import BaseMutation
+from ...core.types import NonNullList, OrderError
+from ...product.types import ProductVariant
+from ..types import Order, OrderLine
+from ..utils import (
+ validate_product_is_published_in_channel,
+ validate_variant_channel_listings,
+)
+from .draft_order_create import OrderLineCreateInput
+from .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status
+
+
+class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
+ order = graphene.Field(Order, description="Related order.")
+ order_lines = NonNullList(OrderLine, description="List of added order lines.")
+
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of the order to add the lines to."
+ )
+ input = NonNullList(
+ OrderLineCreateInput,
+ required=True,
+ description="Fields required to add order lines.",
+ )
+
+ class Meta:
+ description = "Create order lines for an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+ errors_mapping = {"lines": "input", "channel": "input"}
+
+ @classmethod
+ def validate_lines(cls, info, data):
+ lines_to_add = []
+ invalid_ids = []
+ for input_line in data.get("input"):
+ variant_id = input_line["variant_id"]
+ variant = cls.get_node_or_error(
+ info, variant_id, "variant_id", only_type=ProductVariant
+ )
+ quantity = input_line["quantity"]
+ if quantity > 0:
+ lines_to_add.append((quantity, variant))
+ else:
+ invalid_ids.append(variant_id)
+ if invalid_ids:
+ raise ValidationError(
+ {
+ "quantity": ValidationError(
+ "Variants quantity must be greater than 0.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ params={"variants": invalid_ids},
+ ),
+ }
+ )
+ return lines_to_add
+
+ @classmethod
+ def validate_variants(cls, order, variants):
+ try:
+ channel = order.channel
+ validate_product_is_published_in_channel(variants, channel)
+ validate_variant_channel_listings(variants, channel)
+ except ValidationError as error:
+ cls.remap_error_fields(error, cls._meta.errors_mapping)
+ raise ValidationError(error)
+
+ @staticmethod
+ def add_lines_to_order(
+ order, lines_to_add, user, app, manager, settings, discounts
+ ):
+ added_lines: List[Tuple[int, OrderLine]] = []
+ try:
+ for quantity, variant in lines_to_add:
+ line = add_variant_to_order(
+ order,
+ variant,
+ quantity,
+ user,
+ app,
+ manager,
+ settings,
+ discounts=discounts,
+ allocate_stock=order.is_unconfirmed(),
+ )
+ added_lines.append((quantity, line))
+ except TaxError as tax_error:
+ raise ValidationError(
+ "Unable to calculate taxes - %s" % str(tax_error),
+ code=OrderErrorCode.TAX_ERROR.value,
+ )
+ return added_lines
+
+ @classmethod
+ @traced_atomic_transaction()
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ cls.validate_order(order)
+ lines_to_add = cls.validate_lines(info, data)
+ variants = [line[1] for line in lines_to_add]
+ cls.validate_variants(order, variants)
+
+ added_lines = cls.add_lines_to_order(
+ order,
+ lines_to_add,
+ info.context.user,
+ info.context.app,
+ info.context.plugins,
+ info.context.site.settings,
+ info.context.discounts,
+ )
+
+ # Create the products added event
+ events.order_added_products_event(
+ order=order,
+ user=info.context.user,
+ app=info.context.app,
+ order_lines=added_lines,
+ )
+
+ lines = [line for _, line in added_lines]
+
+ recalculate_order(order)
+ update_order_search_document(order)
+
+ func = get_webhook_handler_by_order_status(order.status, info)
+ transaction.on_commit(lambda: func(order))
+
+ return OrderLinesCreate(order=order, order_lines=lines)
diff --git a/saleor/graphql/order/mutations/order_mark_as_paid.py b/saleor/graphql/order/mutations/order_mark_as_paid.py
new file mode 100644
index 0000000000..a60657fc47
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_mark_as_paid.py
@@ -0,0 +1,52 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....order.actions import clean_mark_order_as_paid, mark_order_as_paid
+from ....order.error_codes import OrderErrorCode
+from ....order.search import update_order_search_document
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Order
+from .utils import try_payment_action
+
+
+class OrderMarkAsPaid(BaseMutation):
+ order = graphene.Field(Order, description="Order marked as paid.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the order to mark paid.")
+ transaction_reference = graphene.String(
+ required=False, description="The external transaction reference."
+ )
+
+ class Meta:
+ description = "Mark order as manually paid."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_billing_address(cls, instance):
+ if not instance.billing_address:
+ raise ValidationError(
+ "Order billing address is required to mark order as paid.",
+ code=OrderErrorCode.BILLING_ADDRESS_NOT_SET,
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ transaction_reference = data.get("transaction_reference")
+ cls.clean_billing_address(order)
+ user = info.context.user
+ app = info.context.app
+ try_payment_action(order, user, app, None, clean_mark_order_as_paid, order)
+
+ mark_order_as_paid(
+ order, user, app, info.context.plugins, transaction_reference
+ )
+
+ update_order_search_document(order)
+
+ return OrderMarkAsPaid(order=order)
diff --git a/saleor/graphql/order/mutations/order_refund.py b/saleor/graphql/order/mutations/order_refund.py
new file mode 100644
index 0000000000..e009fd5cbe
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_refund.py
@@ -0,0 +1,120 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....giftcard.utils import order_has_gift_card_lines
+from ....order import FulfillmentStatus
+from ....order.actions import order_refunded
+from ....order.error_codes import OrderErrorCode
+from ....payment import PaymentError, TransactionKind, gateway
+from ....payment.gateway import request_refund_action
+from ...core.mutations import BaseMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types import OrderError
+from ..types import Order
+from .utils import clean_payment, try_payment_action
+
+
+def clean_refund_payment(payment):
+ clean_payment(payment)
+ if not payment.can_refund():
+ raise ValidationError(
+ {
+ "payment": ValidationError(
+ "Payment cannot be refunded.",
+ code=OrderErrorCode.CANNOT_REFUND,
+ )
+ }
+ )
+
+
+def clean_order_refund(order):
+ if order_has_gift_card_lines(order):
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot refund order with gift card lines.",
+ code=OrderErrorCode.CANNOT_REFUND.value,
+ )
+ }
+ )
+
+
+class OrderRefund(BaseMutation):
+ order = graphene.Field(Order, description="A refunded order.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the order to refund.")
+ amount = PositiveDecimal(
+ required=True, description="Amount of money to refund."
+ )
+
+ class Meta:
+ description = "Refund an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, amount, **data):
+ if amount <= 0:
+ raise ValidationError(
+ {
+ "amount": ValidationError(
+ "Amount should be a positive number.",
+ code=OrderErrorCode.ZERO_QUANTITY,
+ )
+ }
+ )
+
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ clean_order_refund(order)
+
+ if payment_transactions := list(order.payment_transactions.all()):
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ try:
+ request_refund_action(
+ payment_transactions[-1],
+ info.context.plugins,
+ refund_value=amount,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ else:
+ payment = order.get_last_payment()
+ clean_payment(payment)
+ clean_refund_payment(payment)
+ transaction = try_payment_action(
+ order,
+ info.context.user,
+ info.context.app,
+ payment,
+ gateway.refund,
+ payment,
+ info.context.plugins,
+ amount=amount,
+ channel_slug=order.channel.slug,
+ )
+ # Confirm that we changed the status to refund. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.REFUND:
+ order_refunded(
+ order,
+ info.context.user,
+ info.context.app,
+ amount,
+ payment,
+ info.context.plugins,
+ )
+
+ order.fulfillments.create(
+ status=FulfillmentStatus.REFUNDED, total_refund_amount=amount
+ )
+ return OrderRefund(order=order)
diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.py
new file mode 100644
index 0000000000..f634e085e4
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_update.py
@@ -0,0 +1,80 @@
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....account.models import User
+from ....core.permissions import OrderPermissions
+from ....core.tracing import traced_atomic_transaction
+from ....order import OrderStatus, models
+from ....order.error_codes import OrderErrorCode
+from ....order.search import prepare_order_search_document_value
+from ....order.utils import update_order_prices
+from ...account.types import AddressInput
+from ...core.types import OrderError
+from ..types import Order
+from .draft_order_create import DraftOrderCreate
+
+
+class OrderUpdateInput(graphene.InputObjectType):
+ billing_address = AddressInput(description="Billing address of the customer.")
+ user_email = graphene.String(description="Email address of the customer.")
+ shipping_address = AddressInput(description="Shipping address of the customer.")
+
+
+class OrderUpdate(DraftOrderCreate):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of an order to update.")
+ input = OrderUpdateInput(
+ required=True, description="Fields required to update an order."
+ )
+
+ class Meta:
+ description = "Updates an order."
+ model = models.Order
+ object_type = Order
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ draft_order_cleaned_input = super().clean_input(info, instance, data)
+
+ # We must to filter out field added by DraftOrderUpdate
+ editable_fields = ["billing_address", "shipping_address", "user_email"]
+ cleaned_input = {}
+ for key in draft_order_cleaned_input:
+ if key in editable_fields:
+ cleaned_input[key] = draft_order_cleaned_input[key]
+ return cleaned_input
+
+ @classmethod
+ def get_instance(cls, info, **data):
+ instance = super().get_instance(info, **data)
+ if instance.status == OrderStatus.DRAFT:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Provided order id belongs to draft order. "
+ "Use `draftOrderUpdate` mutation instead.",
+ code=OrderErrorCode.INVALID,
+ )
+ }
+ )
+ return instance
+
+ @classmethod
+ @traced_atomic_transaction()
+ def save(cls, info, instance, cleaned_input):
+ cls._save_addresses(info, instance, cleaned_input)
+ if instance.user_email:
+ user = User.objects.filter(email=instance.user_email).first()
+ instance.user = user
+ instance.search_document = prepare_order_search_document_value(instance)
+ instance.save()
+ update_order_prices(
+ instance,
+ info.context.plugins,
+ info.context.site.settings.include_taxes_in_prices,
+ )
+ transaction.on_commit(lambda: info.context.plugins.order_updated(instance))
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
new file mode 100644
index 0000000000..3b06d1c2ad
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -0,0 +1,168 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....core.taxes import zero_taxed_money
+from ....order import models
+from ....order.actions import order_shipping_updated
+from ....order.error_codes import OrderErrorCode
+from ....order.utils import recalculate_order, update_order_prices
+from ....shipping import models as shipping_models
+from ....shipping.utils import convert_to_shipping_method_data
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ...shipping.types import ShippingMethod
+from ..types import Order
+from .utils import EditableOrderValidationMixin, clean_order_update_shipping
+
+
+class OrderUpdateShippingInput(graphene.InputObjectType):
+ shipping_method = graphene.ID(
+ description="ID of the selected shipping method,"
+ " pass null to remove currently assigned shipping method.",
+ name="shippingMethod",
+ )
+
+
+class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
+ order = graphene.Field(Order, description="Order with updated shipping method.")
+
+ class Arguments:
+ id = graphene.ID(
+ required=True,
+ name="order",
+ description="ID of the order to update a shipping method.",
+ )
+ input = OrderUpdateShippingInput(
+ description="Fields required to change shipping method of the order.",
+ required=True,
+ )
+
+ class Meta:
+ description = (
+ "Updates a shipping method of the order."
+ " Requires shipping method ID to update, when null is passed "
+ "then currently assigned shipping method is removed."
+ )
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(
+ info,
+ data.get("id"),
+ only_type=Order,
+ qs=models.Order.objects.prefetch_related(
+ "lines", "channel__shipping_method_listings"
+ ),
+ )
+ cls.validate_order(order)
+
+ data = data.get("input")
+
+ if "shipping_method" not in data:
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "Shipping method must be provided to perform mutation.",
+ code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
+ )
+ }
+ )
+
+ if not data.get("shipping_method"):
+ if not order.is_draft() and order.is_shipping_required():
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "Shipping method is required for this order.",
+ code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
+ )
+ }
+ )
+
+ # Shipping method is detached only when null is passed in input.
+ if data["shipping_method"] == "":
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "Shipping method cannot be empty.",
+ code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
+ )
+ }
+ )
+
+ order.shipping_method = None
+ order.shipping_price = zero_taxed_money(order.currency)
+ order.shipping_method_name = None
+ order.save(
+ update_fields=[
+ "currency",
+ "shipping_method",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_method_name",
+ "updated_at",
+ ]
+ )
+ recalculate_order(order)
+ return OrderUpdateShipping(order=order)
+
+ method = cls.get_node_or_error(
+ info,
+ data["shipping_method"],
+ field="shipping_method",
+ only_type=ShippingMethod,
+ qs=shipping_models.ShippingMethod.objects.prefetch_related(
+ "postal_code_rules"
+ ),
+ )
+ shipping_channel_listing = (
+ shipping_models.ShippingMethodChannelListing.objects.filter(
+ shipping_method=method, channel=order.channel
+ ).first()
+ )
+ if not shipping_channel_listing:
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ "Shipping method not available in the given channel.",
+ code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
+ )
+ }
+ )
+
+ shipping_method_data = convert_to_shipping_method_data(
+ method,
+ shipping_channel_listing,
+ )
+ clean_order_update_shipping(order, shipping_method_data, info.context.plugins)
+
+ order.shipping_method = method
+ shipping_price = info.context.plugins.calculate_order_shipping(order)
+ order.shipping_price = shipping_price
+ order.shipping_tax_rate = info.context.plugins.get_order_shipping_tax_rate(
+ order, shipping_price
+ )
+ order.shipping_method_name = method.name
+ order.save(
+ update_fields=[
+ "currency",
+ "shipping_method",
+ "shipping_method_name",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_tax_rate",
+ "updated_at",
+ ]
+ )
+ update_order_prices(
+ order,
+ info.context.plugins,
+ info.context.site.settings.include_taxes_in_prices,
+ )
+ # Post-process the results
+ order_shipping_updated(order, info.context.plugins)
+ return OrderUpdateShipping(order=order)
diff --git a/saleor/graphql/order/mutations/order_void.py b/saleor/graphql/order/mutations/order_void.py
new file mode 100644
index 0000000000..38a907cb8d
--- /dev/null
+++ b/saleor/graphql/order/mutations/order_void.py
@@ -0,0 +1,84 @@
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....core.permissions import OrderPermissions
+from ....order.actions import order_voided
+from ....order.error_codes import OrderErrorCode
+from ....payment import PaymentError, TransactionKind, gateway
+from ....payment.gateway import request_void_action
+from ...core.mutations import BaseMutation
+from ...core.types import OrderError
+from ..types import Order
+from .utils import clean_payment, try_payment_action
+
+
+def clean_void_payment(payment):
+ """Check for payment errors."""
+ clean_payment(payment)
+ if not payment.is_active:
+ raise ValidationError(
+ {
+ "payment": ValidationError(
+ "Only pre-authorized payments can be voided",
+ code=OrderErrorCode.VOID_INACTIVE_PAYMENT,
+ )
+ }
+ )
+
+
+class OrderVoid(BaseMutation):
+ order = graphene.Field(Order, description="A voided order.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the order to void.")
+
+ class Meta:
+ description = "Void an order."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+
+ if payment_transactions := list(order.payment_transactions.all()):
+ # We use the last transaction as we don't have a possibility to
+ # provide way of handling multiple transaction here
+ try:
+ request_void_action(
+ payment_transactions[-1],
+ info.context.plugins,
+ channel_slug=order.channel.slug,
+ user=info.context.user,
+ app=info.context.app,
+ )
+ except PaymentError as e:
+ raise ValidationError(
+ str(e),
+ code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
+ )
+ else:
+ payment = order.get_last_payment()
+ clean_void_payment(payment)
+ transaction = try_payment_action(
+ order,
+ info.context.user,
+ info.context.app,
+ payment,
+ gateway.void,
+ payment,
+ info.context.plugins,
+ channel_slug=order.channel.slug,
+ )
+ # Confirm that we changed the status to void. Some payment can receive
+ # asynchronous webhook with update status
+ if transaction.kind == TransactionKind.VOID:
+ order_voided(
+ order,
+ info.context.user,
+ info.context.app,
+ payment,
+ info.context.plugins,
+ )
+ return OrderVoid(order=order)
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
deleted file mode 100644
index e605a4eeb7..0000000000
--- a/saleor/graphql/order/mutations/orders.py
+++ /dev/null
@@ -1,1116 +0,0 @@
-from typing import List, Tuple
-
-import graphene
-from django.core.exceptions import ValidationError
-from django.db import transaction
-
-from ....account.models import User
-from ....core.exceptions import InsufficientStock
-from ....core.permissions import OrderPermissions
-from ....core.taxes import TaxError, zero_taxed_money
-from ....core.tracing import traced_atomic_transaction
-from ....giftcard.utils import deactivate_order_gift_cards, order_has_gift_card_lines
-from ....order import FulfillmentStatus, OrderStatus, events, models
-from ....order.actions import (
- cancel_order,
- clean_mark_order_as_paid,
- mark_order_as_paid,
- order_captured,
- order_confirmed,
- order_refunded,
- order_shipping_updated,
- order_voided,
-)
-from ....order.error_codes import OrderErrorCode
-from ....order.fetch import OrderLineInfo, fetch_order_info
-from ....order.search import (
- prepare_order_search_document_value,
- update_order_search_document,
-)
-from ....order.utils import (
- add_variant_to_order,
- change_order_line_quantity,
- delete_order_line,
- recalculate_order,
- update_order_prices,
-)
-from ....payment import PaymentError, TransactionKind, gateway
-from ....payment.gateway import (
- request_capture_action,
- request_refund_action,
- request_void_action,
-)
-from ....plugins.manager import PluginsManager
-from ....shipping import models as shipping_models
-from ....shipping.interface import ShippingMethodData
-from ....shipping.utils import convert_to_shipping_method_data
-from ...account.types import AddressInput
-from ...core.mutations import BaseMutation, ModelMutation
-from ...core.scalars import PositiveDecimal
-from ...core.types import NonNullList, OrderError
-from ...core.utils import validate_required_string_field
-from ...order.mutations.draft_orders import (
- DraftOrderCreate,
- OrderLineCreateInput,
- OrderLineInput,
-)
-from ...product.types import ProductVariant
-from ...shipping.types import ShippingMethod
-from ..types import Order, OrderEvent, OrderLine
-from ..utils import (
- get_shipping_method_availability_error,
- validate_product_is_published_in_channel,
- validate_variant_channel_listings,
-)
-
-ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)
-
-
-def clean_order_update_shipping(
- order, method: ShippingMethodData, manager: "PluginsManager"
-):
- if not order.shipping_address:
- raise ValidationError(
- {
- "order": ValidationError(
- "Cannot choose a shipping method for an order without "
- "the shipping address.",
- code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value,
- )
- }
- )
-
- error = get_shipping_method_availability_error(order, method, manager)
- if error:
- raise ValidationError({"shipping_method": error})
-
-
-def clean_order_cancel(order):
- if order and not order.can_cancel():
- raise ValidationError(
- {
- "order": ValidationError(
- "This order can't be canceled.",
- code=OrderErrorCode.CANNOT_CANCEL_ORDER,
- )
- }
- )
-
-
-def clean_payment(payment):
- if not payment:
- raise ValidationError(
- {
- "payment": ValidationError(
- "There's no payment associated with the order.",
- code=OrderErrorCode.PAYMENT_MISSING,
- )
- }
- )
-
-
-def clean_order_capture(payment):
- clean_payment(payment)
- if not payment.is_active:
- raise ValidationError(
- {
- "payment": ValidationError(
- "Only pre-authorized payments can be captured",
- code=OrderErrorCode.CAPTURE_INACTIVE_PAYMENT,
- )
- }
- )
-
-
-def clean_void_payment(payment):
- """Check for payment errors."""
- clean_payment(payment)
- if not payment.is_active:
- raise ValidationError(
- {
- "payment": ValidationError(
- "Only pre-authorized payments can be voided",
- code=OrderErrorCode.VOID_INACTIVE_PAYMENT,
- )
- }
- )
-
-
-def clean_refund_payment(payment):
- clean_payment(payment)
- if not payment.can_refund():
- raise ValidationError(
- {
- "payment": ValidationError(
- "Payment cannot be refunded.",
- code=OrderErrorCode.CANNOT_REFUND,
- )
- }
- )
-
-
-def try_payment_action(order, user, app, payment, func, *args, **kwargs):
- try:
- result = func(*args, **kwargs)
- # provided order might alter it's total_paid.
- order.refresh_from_db()
- return result
- except (PaymentError, ValueError) as e:
- message = str(e)
- events.payment_failed_event(
- order=order, user=user, app=app, message=message, payment=payment
- )
- raise ValidationError(
- {"payment": ValidationError(message, code=OrderErrorCode.PAYMENT_ERROR)}
- )
-
-
-def clean_order_refund(order):
- if order_has_gift_card_lines(order):
- raise ValidationError(
- {
- "id": ValidationError(
- "Cannot refund order with gift card lines.",
- code=OrderErrorCode.CANNOT_REFUND.value,
- )
- }
- )
-
-
-def get_webhook_handler_by_order_status(status, info):
- if status == OrderStatus.DRAFT:
- return info.context.plugins.draft_order_updated
- else:
- return info.context.plugins.order_updated
-
-
-class OrderUpdateInput(graphene.InputObjectType):
- billing_address = AddressInput(description="Billing address of the customer.")
- user_email = graphene.String(description="Email address of the customer.")
- shipping_address = AddressInput(description="Shipping address of the customer.")
-
-
-class OrderUpdate(DraftOrderCreate):
- class Arguments:
- id = graphene.ID(required=True, description="ID of an order to update.")
- input = OrderUpdateInput(
- required=True, description="Fields required to update an order."
- )
-
- class Meta:
- description = "Updates an order."
- model = models.Order
- object_type = Order
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- draft_order_cleaned_input = super().clean_input(info, instance, data)
-
- # We must to filter out field added by DraftOrderUpdate
- editable_fields = ["billing_address", "shipping_address", "user_email"]
- cleaned_input = {}
- for key in draft_order_cleaned_input:
- if key in editable_fields:
- cleaned_input[key] = draft_order_cleaned_input[key]
- return cleaned_input
-
- @classmethod
- def get_instance(cls, info, **data):
- instance = super().get_instance(info, **data)
- if instance.status == OrderStatus.DRAFT:
- raise ValidationError(
- {
- "id": ValidationError(
- "Provided order id belongs to draft order. "
- "Use `draftOrderUpdate` mutation instead.",
- code=OrderErrorCode.INVALID,
- )
- }
- )
- return instance
-
- @classmethod
- @traced_atomic_transaction()
- def save(cls, info, instance, cleaned_input):
- cls._save_addresses(info, instance, cleaned_input)
- if instance.user_email:
- user = User.objects.filter(email=instance.user_email).first()
- instance.user = user
- instance.search_document = prepare_order_search_document_value(instance)
- instance.save()
- update_order_prices(
- instance,
- info.context.plugins,
- info.context.site.settings.include_taxes_in_prices,
- )
- transaction.on_commit(lambda: info.context.plugins.order_updated(instance))
-
-
-class OrderUpdateShippingInput(graphene.InputObjectType):
- shipping_method = graphene.ID(
- description="ID of the selected shipping method,"
- " pass null to remove currently assigned shipping method.",
- name="shippingMethod",
- )
-
-
-class EditableOrderValidationMixin:
- class Meta:
- abstract = True
-
- @classmethod
- def validate_order(cls, order):
- if order.status not in ORDER_EDITABLE_STATUS:
- raise ValidationError(
- {
- "id": ValidationError(
- "Only draft and unconfirmed orders can be edited.",
- code=OrderErrorCode.NOT_EDITABLE,
- )
- }
- )
-
-
-class OrderUpdateShipping(EditableOrderValidationMixin, BaseMutation):
- order = graphene.Field(Order, description="Order with updated shipping method.")
-
- class Arguments:
- id = graphene.ID(
- required=True,
- name="order",
- description="ID of the order to update a shipping method.",
- )
- input = OrderUpdateShippingInput(
- description="Fields required to change shipping method of the order.",
- required=True,
- )
-
- class Meta:
- description = (
- "Updates a shipping method of the order."
- " Requires shipping method ID to update, when null is passed "
- "then currently assigned shipping method is removed."
- )
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(
- info,
- data.get("id"),
- only_type=Order,
- qs=models.Order.objects.prefetch_related(
- "lines", "channel__shipping_method_listings"
- ),
- )
- cls.validate_order(order)
-
- data = data.get("input")
-
- if "shipping_method" not in data:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method must be provided to perform mutation.",
- code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
- )
- }
- )
-
- if not data.get("shipping_method"):
- if not order.is_draft() and order.is_shipping_required():
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method is required for this order.",
- code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
- )
- }
- )
-
- # Shipping method is detached only when null is passed in input.
- if data["shipping_method"] == "":
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method cannot be empty.",
- code=OrderErrorCode.SHIPPING_METHOD_REQUIRED,
- )
- }
- )
-
- order.shipping_method = None
- order.shipping_price = zero_taxed_money(order.currency)
- order.shipping_method_name = None
- order.save(
- update_fields=[
- "currency",
- "shipping_method",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_method_name",
- "updated_at",
- ]
- )
- recalculate_order(order)
- return OrderUpdateShipping(order=order)
-
- method = cls.get_node_or_error(
- info,
- data["shipping_method"],
- field="shipping_method",
- only_type=ShippingMethod,
- qs=shipping_models.ShippingMethod.objects.prefetch_related(
- "postal_code_rules"
- ),
- )
- shipping_channel_listing = (
- shipping_models.ShippingMethodChannelListing.objects.filter(
- shipping_method=method, channel=order.channel
- ).first()
- )
- if not shipping_channel_listing:
- raise ValidationError(
- {
- "shipping_method": ValidationError(
- "Shipping method not available in the given channel.",
- code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
- )
- }
- )
-
- shipping_method_data = convert_to_shipping_method_data(
- method,
- shipping_channel_listing,
- )
- clean_order_update_shipping(order, shipping_method_data, info.context.plugins)
-
- order.shipping_method = method
- shipping_price = info.context.plugins.calculate_order_shipping(order)
- order.shipping_price = shipping_price
- order.shipping_tax_rate = info.context.plugins.get_order_shipping_tax_rate(
- order, shipping_price
- )
- order.shipping_method_name = method.name
- order.save(
- update_fields=[
- "currency",
- "shipping_method",
- "shipping_method_name",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_tax_rate",
- "updated_at",
- ]
- )
- update_order_prices(
- order,
- info.context.plugins,
- info.context.site.settings.include_taxes_in_prices,
- )
- # Post-process the results
- order_shipping_updated(order, info.context.plugins)
- return OrderUpdateShipping(order=order)
-
-
-class OrderAddNoteInput(graphene.InputObjectType):
- message = graphene.String(
- description="Note message.", name="message", required=True
- )
-
-
-class OrderAddNote(BaseMutation):
- order = graphene.Field(Order, description="Order with the note added.")
- event = graphene.Field(OrderEvent, description="Order note created.")
-
- class Arguments:
- id = graphene.ID(
- required=True,
- description="ID of the order to add a note for.",
- name="order",
- )
- input = OrderAddNoteInput(
- required=True, description="Fields required to create a note for the order."
- )
-
- class Meta:
- description = "Adds note to the order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_input(cls, _info, _instance, data):
- try:
- cleaned_input = validate_required_string_field(data["input"], "message")
- except ValidationError:
- raise ValidationError(
- {
- "message": ValidationError(
- "Message can't be empty.",
- code=OrderErrorCode.REQUIRED,
- )
- }
- )
- return cleaned_input
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- cleaned_input = cls.clean_input(info, order, data)
- event = events.order_note_added_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- message=cleaned_input["message"],
- )
- func = get_webhook_handler_by_order_status(order.status, info)
- transaction.on_commit(lambda: func(order))
- return OrderAddNote(order=order, event=event)
-
-
-class OrderCancel(BaseMutation):
- order = graphene.Field(Order, description="Canceled order.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of the order to cancel.")
-
- class Meta:
- description = "Cancel an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- clean_order_cancel(order)
- user = info.context.user
- app = info.context.app
- cancel_order(
- order=order,
- user=user,
- app=app,
- manager=info.context.plugins,
- )
- deactivate_order_gift_cards(order.id, user, app)
- return OrderCancel(order=order)
-
-
-class OrderMarkAsPaid(BaseMutation):
- order = graphene.Field(Order, description="Order marked as paid.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of the order to mark paid.")
- transaction_reference = graphene.String(
- required=False, description="The external transaction reference."
- )
-
- class Meta:
- description = "Mark order as manually paid."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_billing_address(cls, instance):
- if not instance.billing_address:
- raise ValidationError(
- "Order billing address is required to mark order as paid.",
- code=OrderErrorCode.BILLING_ADDRESS_NOT_SET,
- )
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- transaction_reference = data.get("transaction_reference")
- cls.clean_billing_address(order)
- user = info.context.user
- app = info.context.app
- try_payment_action(order, user, app, None, clean_mark_order_as_paid, order)
-
- mark_order_as_paid(
- order, user, app, info.context.plugins, transaction_reference
- )
-
- update_order_search_document(order)
-
- return OrderMarkAsPaid(order=order)
-
-
-class OrderCapture(BaseMutation):
- order = graphene.Field(Order, description="Captured order.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of the order to capture.")
- amount = PositiveDecimal(
- required=True, description="Amount of money to capture."
- )
-
- class Meta:
- description = "Capture an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, amount, **data):
- if amount <= 0:
- raise ValidationError(
- {
- "amount": ValidationError(
- "Amount should be a positive number.",
- code=OrderErrorCode.ZERO_QUANTITY,
- )
- }
- )
-
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
-
- if payment_transactions := list(order.payment_transactions.all()):
- try:
- # We use the last transaction as we don't have a possibility to
- # provide way of handling multiple transaction here
- payment_transaction = payment_transactions[-1]
- request_capture_action(
- transaction=payment_transaction,
- manager=info.context.plugins,
- capture_value=amount,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=info.context.app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
- )
- else:
- order_info = fetch_order_info(order)
- payment = order_info.payment
- clean_order_capture(payment)
- transaction = try_payment_action(
- order,
- info.context.user,
- info.context.app,
- payment,
- gateway.capture,
- payment,
- info.context.plugins,
- amount=amount,
- channel_slug=order.channel.slug,
- )
- order_info.payment.refresh_from_db()
- # Confirm that we changed the status to capture. Some payment can receive
- # asynchronous webhook with update status
- if transaction.kind == TransactionKind.CAPTURE:
- order_captured(
- order_info,
- info.context.user,
- info.context.app,
- amount,
- payment,
- info.context.plugins,
- )
- return OrderCapture(order=order)
-
-
-class OrderVoid(BaseMutation):
- order = graphene.Field(Order, description="A voided order.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of the order to void.")
-
- class Meta:
- description = "Void an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
-
- if payment_transactions := list(order.payment_transactions.all()):
- # We use the last transaction as we don't have a possibility to
- # provide way of handling multiple transaction here
- try:
- request_void_action(
- payment_transactions[-1],
- info.context.plugins,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=info.context.app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
- )
- else:
- payment = order.get_last_payment()
- clean_void_payment(payment)
- transaction = try_payment_action(
- order,
- info.context.user,
- info.context.app,
- payment,
- gateway.void,
- payment,
- info.context.plugins,
- channel_slug=order.channel.slug,
- )
- # Confirm that we changed the status to void. Some payment can receive
- # asynchronous webhook with update status
- if transaction.kind == TransactionKind.VOID:
- order_voided(
- order,
- info.context.user,
- info.context.app,
- payment,
- info.context.plugins,
- )
- return OrderVoid(order=order)
-
-
-class OrderRefund(BaseMutation):
- order = graphene.Field(Order, description="A refunded order.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of the order to refund.")
- amount = PositiveDecimal(
- required=True, description="Amount of money to refund."
- )
-
- class Meta:
- description = "Refund an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, amount, **data):
- if amount <= 0:
- raise ValidationError(
- {
- "amount": ValidationError(
- "Amount should be a positive number.",
- code=OrderErrorCode.ZERO_QUANTITY,
- )
- }
- )
-
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- clean_order_refund(order)
-
- if payment_transactions := list(order.payment_transactions.all()):
- # We use the last transaction as we don't have a possibility to
- # provide way of handling multiple transaction here
- try:
- request_refund_action(
- payment_transactions[-1],
- info.context.plugins,
- refund_value=amount,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=info.context.app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
- )
- else:
- payment = order.get_last_payment()
- clean_payment(payment)
- clean_refund_payment(payment)
- transaction = try_payment_action(
- order,
- info.context.user,
- info.context.app,
- payment,
- gateway.refund,
- payment,
- info.context.plugins,
- amount=amount,
- channel_slug=order.channel.slug,
- )
- # Confirm that we changed the status to refund. Some payment can receive
- # asynchronous webhook with update status
- if transaction.kind == TransactionKind.REFUND:
- order_refunded(
- order,
- info.context.user,
- info.context.app,
- amount,
- payment,
- info.context.plugins,
- )
-
- order.fulfillments.create(
- status=FulfillmentStatus.REFUNDED, total_refund_amount=amount
- )
- return OrderRefund(order=order)
-
-
-class OrderConfirm(ModelMutation):
- order = graphene.Field(Order, description="Order which has been confirmed.")
-
- class Arguments:
- id = graphene.ID(description="ID of an order to confirm.", required=True)
-
- class Meta:
- description = "Confirms an unconfirmed order by changing status to unfulfilled."
- model = models.Order
- object_type = Order
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def get_instance(cls, info, **data):
- instance = super().get_instance(info, **data)
- if not instance.is_unconfirmed():
- raise ValidationError(
- {
- "id": ValidationError(
- "Provided order id belongs to an order with status "
- "different than unconfirmed.",
- code=OrderErrorCode.INVALID,
- )
- }
- )
- if not instance.lines.exists():
- raise ValidationError(
- {
- "id": ValidationError(
- "Provided order id belongs to an order without products.",
- code=OrderErrorCode.INVALID,
- )
- }
- )
- return instance
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, root, info, **data):
- order = cls.get_instance(info, **data)
- order.status = OrderStatus.UNFULFILLED
- order.save(update_fields=["status", "updated_at"])
- order_info = fetch_order_info(order)
- payment = order_info.payment
- manager = info.context.plugins
- if payment_transactions := list(order.payment_transactions.all()):
- try:
- # We use the last transaction as we don't have a possibility to
- # provide way of handling multiple transaction here
- payment_transaction = payment_transactions[-1]
- request_capture_action(
- transaction=payment_transaction,
- manager=info.context.plugins,
- capture_value=payment_transaction.captured_value,
- channel_slug=order.channel.slug,
- user=info.context.user,
- app=info.context.app,
- )
- except PaymentError as e:
- raise ValidationError(
- str(e),
- code=OrderErrorCode.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK,
- )
- elif payment and payment.is_authorized and payment.can_capture():
- gateway.capture(
- payment, info.context.plugins, channel_slug=order.channel.slug
- )
- order_captured(
- order_info,
- info.context.user,
- info.context.app,
- payment.total,
- payment,
- manager,
- )
- order_confirmed(
- order,
- info.context.user,
- info.context.app,
- manager,
- send_confirmation_email=True,
- )
- return OrderConfirm(order=order)
-
-
-class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
- order = graphene.Field(Order, description="Related order.")
- order_lines = NonNullList(OrderLine, description="List of added order lines.")
-
- class Arguments:
- id = graphene.ID(
- required=True, description="ID of the order to add the lines to."
- )
- input = NonNullList(
- OrderLineCreateInput,
- required=True,
- description="Fields required to add order lines.",
- )
-
- class Meta:
- description = "Create order lines for an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
- errors_mapping = {"lines": "input", "channel": "input"}
-
- @classmethod
- def validate_lines(cls, info, data):
- lines_to_add = []
- invalid_ids = []
- for input_line in data.get("input"):
- variant_id = input_line["variant_id"]
- variant = cls.get_node_or_error(
- info, variant_id, "variant_id", only_type=ProductVariant
- )
- quantity = input_line["quantity"]
- if quantity > 0:
- lines_to_add.append((quantity, variant))
- else:
- invalid_ids.append(variant_id)
- if invalid_ids:
- raise ValidationError(
- {
- "quantity": ValidationError(
- "Variants quantity must be greater than 0.",
- code=OrderErrorCode.ZERO_QUANTITY,
- params={"variants": invalid_ids},
- ),
- }
- )
- return lines_to_add
-
- @classmethod
- def validate_variants(cls, order, variants):
- try:
- channel = order.channel
- validate_product_is_published_in_channel(variants, channel)
- validate_variant_channel_listings(variants, channel)
- except ValidationError as error:
- cls.remap_error_fields(error, cls._meta.errors_mapping)
- raise ValidationError(error)
-
- @staticmethod
- def add_lines_to_order(
- order, lines_to_add, user, app, manager, settings, discounts
- ):
- added_lines: List[Tuple[int, OrderLine]] = []
- try:
- for quantity, variant in lines_to_add:
- line = add_variant_to_order(
- order,
- variant,
- quantity,
- user,
- app,
- manager,
- settings,
- discounts=discounts,
- allocate_stock=order.is_unconfirmed(),
- )
- added_lines.append((quantity, line))
- except TaxError as tax_error:
- raise ValidationError(
- "Unable to calculate taxes - %s" % str(tax_error),
- code=OrderErrorCode.TAX_ERROR.value,
- )
- return added_lines
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, **data):
- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
- cls.validate_order(order)
- lines_to_add = cls.validate_lines(info, data)
- variants = [line[1] for line in lines_to_add]
- cls.validate_variants(order, variants)
-
- added_lines = cls.add_lines_to_order(
- order,
- lines_to_add,
- info.context.user,
- info.context.app,
- info.context.plugins,
- info.context.site.settings,
- info.context.discounts,
- )
-
- # Create the products added event
- events.order_added_products_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- order_lines=added_lines,
- )
-
- lines = [line for _, line in added_lines]
-
- recalculate_order(order)
- update_order_search_document(order)
-
- func = get_webhook_handler_by_order_status(order.status, info)
- transaction.on_commit(lambda: func(order))
-
- return OrderLinesCreate(order=order, order_lines=lines)
-
-
-class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
- order = graphene.Field(Order, description="A related order.")
- order_line = graphene.Field(
- OrderLine, description="An order line that was deleted."
- )
-
- class Arguments:
- id = graphene.ID(description="ID of the order line to delete.", required=True)
-
- class Meta:
- description = "Deletes an order line from an order."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- @traced_atomic_transaction()
- def perform_mutation(cls, _root, info, id):
- manager = info.context.plugins
- line = cls.get_node_or_error(
- info,
- id,
- only_type=OrderLine,
- )
- order = line.order
- cls.validate_order(line.order)
-
- db_id = line.id
- warehouse_pk = (
- line.allocations.first().stock.warehouse.pk
- if order.is_unconfirmed()
- else None
- )
- line_info = OrderLineInfo(
- line=line,
- quantity=line.quantity,
- variant=line.variant,
- warehouse_pk=warehouse_pk,
- )
- delete_order_line(line_info, manager)
- line.id = db_id
-
- if not order.is_shipping_required():
- order.shipping_method = None
- order.shipping_price = zero_taxed_money(order.currency)
- order.shipping_method_name = None
- order.save(
- update_fields=[
- "currency",
- "shipping_method",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_method_name",
- "updated_at",
- ]
- )
- # Create the removal event
- events.order_removed_products_event(
- order=order,
- user=info.context.user,
- app=info.context.app,
- order_lines=[(line.quantity, line)],
- )
-
- recalculate_order(order)
- update_order_search_document(order)
- func = get_webhook_handler_by_order_status(order.status, info)
- transaction.on_commit(lambda: func(order))
- return OrderLineDelete(order=order, order_line=line)
-
-
-class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):
- order = graphene.Field(Order, description="Related order.")
-
- class Arguments:
- id = graphene.ID(description="ID of the order line to update.", required=True)
- input = OrderLineInput(
- required=True, description="Fields required to update an order line."
- )
-
- class Meta:
- description = "Updates an order line of an order."
- model = models.OrderLine
- object_type = OrderLine
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- instance.old_quantity = instance.quantity
- cleaned_input = super().clean_input(info, instance, data)
- cls.validate_order(instance.order)
-
- quantity = data["quantity"]
- if quantity <= 0:
- raise ValidationError(
- {
- "quantity": ValidationError(
- "Ensure this value is greater than 0.",
- code=OrderErrorCode.ZERO_QUANTITY,
- )
- }
- )
- return cleaned_input
-
- @classmethod
- @traced_atomic_transaction()
- def save(cls, info, instance, cleaned_input):
- manager = info.context.plugins
- warehouse_pk = (
- instance.allocations.first().stock.warehouse.pk
- if instance.order.is_unconfirmed()
- else None
- )
- line_info = OrderLineInfo(
- line=instance,
- quantity=instance.quantity,
- variant=instance.variant,
- warehouse_pk=warehouse_pk,
- )
- try:
- change_order_line_quantity(
- info.context.user,
- info.context.app,
- line_info,
- instance.old_quantity,
- instance.quantity,
- instance.order.channel.slug,
- manager,
- )
- except InsufficientStock:
- raise ValidationError(
- "Cannot set new quantity because of insufficient stock.",
- code=OrderErrorCode.INSUFFICIENT_STOCK,
- )
- recalculate_order(instance.order)
-
- func = get_webhook_handler_by_order_status(instance.order.status, info)
- transaction.on_commit(lambda: func(instance.order))
-
- @classmethod
- def success_response(cls, instance):
- response = super().success_response(instance)
- response.order = instance.order
- return response
diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.py
new file mode 100644
index 0000000000..d4e6d40fe7
--- /dev/null
+++ b/saleor/graphql/order/mutations/utils.py
@@ -0,0 +1,81 @@
+from django.core.exceptions import ValidationError
+
+from ....order import OrderStatus, events
+from ....order.error_codes import OrderErrorCode
+from ....payment import PaymentError
+from ....plugins.manager import PluginsManager
+from ....shipping.interface import ShippingMethodData
+from ..utils import get_shipping_method_availability_error
+
+ORDER_EDITABLE_STATUS = (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED)
+
+
+class EditableOrderValidationMixin:
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def validate_order(cls, order):
+ if order.status not in ORDER_EDITABLE_STATUS:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Only draft and unconfirmed orders can be edited.",
+ code=OrderErrorCode.NOT_EDITABLE,
+ )
+ }
+ )
+
+
+def clean_order_update_shipping(
+ order, method: ShippingMethodData, manager: "PluginsManager"
+):
+ if not order.shipping_address:
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "Cannot choose a shipping method for an order without "
+ "the shipping address.",
+ code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value,
+ )
+ }
+ )
+
+ error = get_shipping_method_availability_error(order, method, manager)
+ if error:
+ raise ValidationError({"shipping_method": error})
+
+
+def get_webhook_handler_by_order_status(status, info):
+ if status == OrderStatus.DRAFT:
+ return info.context.plugins.draft_order_updated
+ else:
+ return info.context.plugins.order_updated
+
+
+def try_payment_action(order, user, app, payment, func, *args, **kwargs):
+ try:
+ result = func(*args, **kwargs)
+ # provided order might alter it's total_paid.
+ order.refresh_from_db()
+ return result
+ except (PaymentError, ValueError) as e:
+ message = str(e)
+ events.payment_failed_event(
+ order=order, user=user, app=app, message=message, payment=payment
+ )
+ raise ValidationError(
+ {"payment": ValidationError(message, code=OrderErrorCode.PAYMENT_ERROR)}
+ )
+
+
+def clean_payment(payment):
+ if not payment:
+ raise ValidationError(
+ {
+ "payment": ValidationError(
+ "There's no payment associated with the order.",
+ code=OrderErrorCode.PAYMENT_MISSING,
+ )
+ }
+ )
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 01d22e1da4..173d9dbc4e 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -11,41 +11,33 @@ from ..core.utils import from_global_id_or_error
from .bulk_mutations.draft_orders import DraftOrderBulkDelete, DraftOrderLinesBulkDelete
from .bulk_mutations.orders import OrderBulkCancel
from .filters import DraftOrderFilter, OrderFilter
-from .mutations.discount_order import (
- OrderDiscountAdd,
- OrderDiscountDelete,
- OrderDiscountUpdate,
- OrderLineDiscountRemove,
- OrderLineDiscountUpdate,
-)
-from .mutations.draft_orders import (
- DraftOrderComplete,
- DraftOrderCreate,
- DraftOrderDelete,
- DraftOrderUpdate,
-)
-from .mutations.fulfillments import (
- FulfillmentApprove,
- FulfillmentCancel,
- FulfillmentRefundProducts,
- FulfillmentReturnProducts,
- FulfillmentUpdateTracking,
- OrderFulfill,
-)
-from .mutations.orders import (
- OrderAddNote,
- OrderCancel,
- OrderCapture,
- OrderConfirm,
- OrderLineDelete,
- OrderLinesCreate,
- OrderLineUpdate,
- OrderMarkAsPaid,
- OrderRefund,
- OrderUpdate,
- OrderUpdateShipping,
- OrderVoid,
-)
+from .mutations.draft_order_complete import DraftOrderComplete
+from .mutations.draft_order_create import DraftOrderCreate
+from .mutations.draft_order_delete import DraftOrderDelete
+from .mutations.draft_order_update import DraftOrderUpdate
+from .mutations.fulfillment_approve import FulfillmentApprove
+from .mutations.fulfillment_cancel import FulfillmentCancel
+from .mutations.fulfillment_refund_products import FulfillmentRefundProducts
+from .mutations.fulfillment_return_products import FulfillmentReturnProducts
+from .mutations.fulfillment_update_tracking import FulfillmentUpdateTracking
+from .mutations.order_add_note import OrderAddNote
+from .mutations.order_cancel import OrderCancel
+from .mutations.order_capture import OrderCapture
+from .mutations.order_confirm import OrderConfirm
+from .mutations.order_discount_add import OrderDiscountAdd
+from .mutations.order_discount_delete import OrderDiscountDelete
+from .mutations.order_discount_update import OrderDiscountUpdate
+from .mutations.order_fulfill import OrderFulfill
+from .mutations.order_line_delete import OrderLineDelete
+from .mutations.order_line_discount_remove import OrderLineDiscountRemove
+from .mutations.order_line_discount_update import OrderLineDiscountUpdate
+from .mutations.order_line_update import OrderLineUpdate
+from .mutations.order_lines_create import OrderLinesCreate
+from .mutations.order_mark_as_paid import OrderMarkAsPaid
+from .mutations.order_refund import OrderRefund
+from .mutations.order_update import OrderUpdate
+from .mutations.order_update_shipping import OrderUpdateShipping
+from .mutations.order_void import OrderVoid
from .resolvers import (
resolve_draft_orders,
resolve_homepage_events,
diff --git a/saleor/graphql/order/tests/benchmark/test_order_fulfill.py b/saleor/graphql/order/tests/benchmark/test_order_fulfill.py
index fd26a1e6b3..b122228eaa 100644
--- a/saleor/graphql/order/tests/benchmark/test_order_fulfill.py
+++ b/saleor/graphql/order/tests/benchmark/test_order_fulfill.py
@@ -26,7 +26,7 @@ ORDER_FULFILL_QUERY = """
@pytest.mark.count_queries(autouse=False)
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill(
mock_create_fulfillments,
staff_api_client,
@@ -68,7 +68,7 @@ def test_order_fulfill(
@pytest.mark.count_queries(autouse=False)
@patch("saleor.giftcard.utils.send_gift_card_notification")
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_with_gift_cards(
mock_create_fulfillments,
mock_send_notification,
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
index be1f373de6..9d16697e49 100644
--- a/saleor/graphql/order/tests/deprecated/test_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -224,7 +224,7 @@ ORDER_FULFILL_QUERY = """
@pytest.mark.parametrize("fulfillment_auto_approve", [True, False])
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_old_line_id(
mock_create_fulfillments,
fulfillment_auto_approve,
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 52646a8b99..d4aebd9f68 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -74,7 +74,7 @@ def test_order_fulfill_with_out_of_stock_webhook(
@pytest.mark.parametrize("fulfillment_auto_approve", [True, False])
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill(
mock_create_fulfillments,
fulfillment_auto_approve,
@@ -354,7 +354,7 @@ def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_disabled_deleted_var
assert order_lines[1].quantity_unfulfilled == 2
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_above_available_quantity(
mock_create_fulfillments,
staff_api_client,
@@ -407,7 +407,7 @@ def test_order_fulfill_above_available_quantity(
mock_create_fulfillments.assert_not_called()
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_as_app(
mock_create_fulfillments,
app_api_client,
@@ -465,7 +465,7 @@ def test_order_fulfill_as_app(
)
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_many_warehouses(
mock_create_fulfillments,
staff_api_client,
@@ -772,7 +772,7 @@ def test_order_fulfill_with_gift_cards_multiple_warehouses(
mock_send_notification.assert_not_called
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_without_notification(
mock_create_fulfillments,
staff_api_client,
@@ -823,7 +823,7 @@ def test_order_fulfill_without_notification(
)
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_lines_with_empty_quantity(
mock_create_fulfillments,
staff_api_client,
@@ -891,7 +891,7 @@ def test_order_fulfill_lines_with_empty_quantity(
@pytest.mark.parametrize("fulfillment_auto_approve", [True, False])
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_without_sku(
mock_create_fulfillments,
fulfillment_auto_approve,
@@ -955,7 +955,7 @@ def test_order_fulfill_without_sku(
)
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_zero_quantity(
mock_create_fulfillments,
staff_api_client,
@@ -1031,7 +1031,7 @@ def test_order_fulfill_channel_without_shipping_zones(
assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_fulfilled_order(
mock_create_fulfillments,
staff_api_client,
@@ -1071,7 +1071,7 @@ def test_order_fulfill_fulfilled_order(
mock_create_fulfillments.assert_not_called()
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_unpaid_order_and_disallow_unpaid(
mock_create_fulfillments,
staff_api_client,
@@ -1111,7 +1111,9 @@ def test_order_fulfill_unpaid_order_and_disallow_unpaid(
mock_create_fulfillments.assert_not_called()
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
+@patch(
+ "saleor.graphql.order.mutations.order_fulfill.create_fulfillments", autospec=True
+)
def test_order_fulfill_warehouse_with_insufficient_stock_exception(
mock_create_fulfillments,
staff_api_client,
@@ -1162,7 +1164,9 @@ def test_order_fulfill_warehouse_with_insufficient_stock_exception(
assert error["warehouse"] == warehouse_id
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
+@patch(
+ "saleor.graphql.order.mutations.order_fulfill.create_fulfillments", autospec=True
+)
def test_order_fulfill_warehouse_duplicated_warehouse_id(
mock_create_fulfillments,
staff_api_client,
@@ -1204,7 +1208,9 @@ def test_order_fulfill_warehouse_duplicated_warehouse_id(
mock_create_fulfillments.assert_not_called()
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True)
+@patch(
+ "saleor.graphql.order.mutations.order_fulfill.create_fulfillments", autospec=True
+)
def test_order_fulfill_warehouse_duplicated_order_line_id(
mock_create_fulfillments,
staff_api_client,
@@ -1247,7 +1253,7 @@ def test_order_fulfill_warehouse_duplicated_order_line_id(
mock_create_fulfillments.assert_not_called()
-@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")
+@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")
def test_order_fulfill_preorder(
mock_create_fulfillments,
staff_api_client,
@@ -1381,7 +1387,9 @@ FULFILLMENT_UPDATE_TRACKING_WITH_SEND_NOTIFICATION_QUERY = """
"""
-@patch("saleor.graphql.order.mutations.fulfillments.send_fulfillment_update")
+@patch(
+ "saleor.graphql.order.mutations.fulfillment_update_tracking.send_fulfillment_update"
+)
def test_fulfillment_update_tracking_send_notification_true(
send_fulfillment_update_mock,
staff_api_client,
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 7d40c9a115..e80a81081f 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -45,12 +45,6 @@ from ....shipping.models import ShippingMethod, ShippingMethodChannelListing
from ....warehouse.models import Allocation, PreorderAllocation, Stock, Warehouse
from ....warehouse.tests.utils import get_available_quantity_for_stock
from ...core.utils import to_global_id_or_none
-from ...order.mutations.orders import (
- clean_order_cancel,
- clean_order_capture,
- clean_refund_payment,
- try_payment_action,
-)
from ...payment.enums import TransactionStatusEnum
from ...payment.types import PaymentChargeStatusEnum
from ...tests.utils import (
@@ -58,6 +52,10 @@ from ...tests.utils import (
get_graphql_content,
get_graphql_content_from_response,
)
+from ..mutations.order_cancel import clean_order_cancel
+from ..mutations.order_capture import clean_order_capture
+from ..mutations.order_refund import clean_refund_payment
+from ..mutations.utils import try_payment_action
from ..utils import validate_draft_order
from .utils import assert_order_and_payment_ids
@@ -2434,7 +2432,7 @@ def test_draft_order_create_variant_with_0_price(
assert created_draft_event.parameters == {}
-@patch("saleor.graphql.order.mutations.draft_orders.add_variant_to_order")
+@patch("saleor.graphql.order.mutations.draft_order_create.add_variant_to_order")
def test_draft_order_create_tax_error(
add_variant_to_order_mock,
staff_api_client,
@@ -3160,7 +3158,7 @@ def test_draft_order_update_with_non_draft_order(
assert error["code"] == OrderErrorCode.INVALID.name
-@patch("saleor.graphql.order.mutations.draft_orders.update_order_prices")
+@patch("saleor.graphql.order.mutations.draft_order_create.update_order_prices")
def test_draft_order_update_tax_error(
update_order_prices_mock,
staff_api_client,
@@ -5670,8 +5668,8 @@ mutation cancelOrder($id: ID!) {
"""
-@patch("saleor.graphql.order.mutations.orders.cancel_order")
-@patch("saleor.graphql.order.mutations.orders.clean_order_cancel")
+@patch("saleor.graphql.order.mutations.order_cancel.cancel_order")
+@patch("saleor.graphql.order.mutations.order_cancel.clean_order_cancel")
def test_order_cancel(
mock_clean_order_cancel,
mock_cancel_order,
@@ -5695,8 +5693,8 @@ def test_order_cancel(
)
-@patch("saleor.graphql.order.mutations.orders.cancel_order")
-@patch("saleor.graphql.order.mutations.orders.clean_order_cancel")
+@patch("saleor.graphql.order.mutations.order_cancel.cancel_order")
+@patch("saleor.graphql.order.mutations.order_cancel.clean_order_cancel")
def test_order_cancel_as_app(
mock_clean_order_cancel,
mock_cancel_order,
@@ -5720,8 +5718,8 @@ def test_order_cancel_as_app(
)
-@patch("saleor.graphql.order.mutations.orders.cancel_order")
-@patch("saleor.graphql.order.mutations.orders.clean_order_cancel")
+@patch("saleor.graphql.order.mutations.order_cancel.cancel_order")
+@patch("saleor.graphql.order.mutations.order_cancel.clean_order_cancel")
def test_order_cancel_with_bought_gift_cards(
mock_clean_order_cancel,
mock_cancel_order,
diff --git a/saleor/shipping/tasks.py b/saleor/shipping/tasks.py
index 5bf182d8ac..ad5f42d01a 100644
--- a/saleor/shipping/tasks.py
+++ b/saleor/shipping/tasks.py
@@ -2,7 +2,7 @@ from typing import Iterable, Union
from ..celeryconf import app
from ..checkout.models import Checkout
-from ..graphql.order.mutations.orders import ORDER_EDITABLE_STATUS
+from ..graphql.order.mutations.utils import ORDER_EDITABLE_STATUS
from ..order.models import Order