Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Possibility to apply discount on order (#6930)
Maciej Korycinski326a5b88207a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ddd8252517..86441c1194 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,8 @@ All notable, unreleased changes to this project will be documented in this file.- Add missing span in PluginManager - #6900 by @fowczarek- Fix Sentry reporting - #6902 by @fowczarek- Fix removing page types in cleardb command - #6918 by @fowczarek+- Add possibility to apply discount to order/order line with status `DRAFT` - #6930 by @korycins+- Deprecate API fields `Order.discount`, `Order.discountName`, `Order.translatedDiscountName` - #6874 by @korycins- Fix argument validation in page resolver - #6960 by @fowczarek- Drop `data` field from checkout line model - #6961 by @fowczarek@@ -24,6 +26,10 @@ All notable, unreleased changes to this project will be documented in this file.- Drop `CHECKOUT_QUANTITY_CHANGED` webhook - #6797 by @d-wysocki- Drop deprecated `taxRate` field from `ProductType` - #6795 by @d-wysocki- Remove resolving user's location from GeoIP; drop `PaymentInput.billingAddress` input field - #6784 by @maarcingebala+- Change the payload of the order webhook to handle discounts list, added fields: `Order.discounts`,+`OrderLine.unit_discount_amount`,`OrderLine.unit_discount_type`, `OrderLine.unit_discount_reason` , remove fields:+`Order.discount_amount`, `Order.discount_name`, `Order.translated_discount_name`- #6874 by @korycins+- Update checkout performance - introduce `CheckoutInfo` data class - #6958 by @IKarbowiak; Introduced changes in plugin methods definitions:- in the following methods, the `checkout` parameter changed to `checkout_info`:- `calculate_checkout_total`diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 2ae64f9913..a582bfb69e 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -16,7 +16,7 @@ from ..checkout.error_codes import CheckoutErrorCodefrom ..core.exceptions import InsufficientStockfrom ..core.taxes import TaxError, zero_taxed_moneyfrom ..core.utils.url import validate_storefront_url-from ..discount import DiscountInfo+from ..discount import DiscountInfo, DiscountValueType, OrderDiscountTypefrom ..discount.models import NotApplicablefrom ..discount.utils import (add_voucher_usage_by_customer,@@ -69,9 +69,6 @@ def _get_voucher_data_for_order(checkout_info: "CheckoutInfo") -> dict:add_voucher_usage_by_customer(voucher, checkout_info.get_customer_email())return {"voucher": voucher,- "discount": checkout.discount,- "discount_name": checkout.discount_name,- "translated_discount_name": checkout.translated_discount_name,}@@ -281,6 +278,7 @@ def _prepare_order_data(taxed_total.net -= cards_totaltaxed_total = max(taxed_total, zero_taxed_money(checkout.currency))+ undiscounted_total = taxed_total + checkout.discountshipping_total = manager.calculate_checkout_shipping(checkout_info, lines, address, discounts@@ -297,6 +295,7 @@ def _prepare_order_data("language_code": get_language(),"tracking_client_id": checkout.tracking_code or "","total": taxed_total,+ "undiscounted_total": undiscounted_total,"shipping_tax_rate": shipping_tax_rate,})@@ -362,6 +361,20 @@ def _create_order(status=status,channel=checkout_info.channel,)+ if checkout.discount:+ # store voucher as a fixed value as it this the simplest solution for now.+ # This will be solved when we refactor the voucher logic to use .discounts+ # relations+ order.discounts.create(+ type=OrderDiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=checkout.discount.amount,+ name=checkout.discount_name,+ translated_name=checkout.translated_discount_name,+ currency=checkout.currency,+ amount_value=checkout.discount_amount,+ )+order_lines = []for line_info in order_lines_info:line = line_info.linediff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.pyindex ed8d3243a9..a3588cf6e6 100644--- a/saleor/discount/__init__.py+++ b/saleor/discount/__init__.py@@ -18,6 +18,12 @@ class DiscountValueType:]+class OrderDiscountType:+ VOUCHER = "voucher"+ MANUAL = "manual"+ CHOICES = [(VOUCHER, "Voucher"), (MANUAL, "Manual")]++class VoucherType:SHIPPING = "shipping"ENTIRE_ORDER = "entire_order"diff --git a/saleor/discount/migrations/0024_orderdiscount.py b/saleor/discount/migrations/0024_orderdiscount.pynew file mode 100644index 0000000000..d84e4c5ce5--- /dev/null+++ b/saleor/discount/migrations/0024_orderdiscount.py@@ -0,0 +1,70 @@+# Generated by Django 3.1.5 on 2021-02-05 12:10++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0097_auto_20210107_1148"),+ ("discount", "0023_voucher_channel_listing"),+ ]++ operations = [+ migrations.CreateModel(+ name="OrderDiscount",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "type",+ models.CharField(+ choices=[("voucher", "Voucher"), ("manual", "Manual")],+ default="manual",+ max_length=10,+ ),+ ),+ (+ "value_type",+ models.CharField(+ choices=[("fixed", "fixed"), ("percentage", "%")],+ default="fixed",+ max_length=10,+ ),+ ),+ (+ "value",+ models.DecimalField(decimal_places=3, max_digits=12, default=0),+ ),+ (+ "amount_value",+ models.DecimalField(decimal_places=3, max_digits=12, default=0),+ ),+ ("currency", models.CharField(max_length=3)),+ ("name", models.CharField(blank=True, max_length=255, null=True)),+ (+ "translated_name",+ models.CharField(blank=True, max_length=255, null=True),+ ),+ ("reason", models.TextField(blank=True, null=True)),+ (+ "order",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="discounts",+ to="order.order",+ ),+ ),+ ],+ ),+ ]diff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex e603e9f097..0aa8e65f88 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -13,7 +13,7 @@ from prices import Money, fixed_discount, percentage_discountfrom ..channel.models import Channelfrom ..core.permissions import DiscountPermissionsfrom ..core.utils.translations import TranslationProxy-from . import DiscountValueType, VoucherType+from . import DiscountValueType, OrderDiscountType, VoucherTypeclass NotApplicable(ValueError):@@ -307,3 +307,42 @@ class SaleTranslation(models.Model):class Meta:ordering = ("language_code", "name", "pk")unique_together = (("language_code", "sale"),)+++class OrderDiscount(models.Model):+ order = models.ForeignKey(+ "order.Order",+ related_name="discounts",+ blank=True,+ null=True,+ on_delete=models.CASCADE,+ )+ type = models.CharField(+ max_length=10,+ choices=OrderDiscountType.CHOICES,+ default=OrderDiscountType.MANUAL,+ )+ value_type = models.CharField(+ max_length=10,+ choices=DiscountValueType.CHOICES,+ default=DiscountValueType.FIXED,+ )+ value = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )++ amount_value = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )+ amount = MoneyField(amount_field="amount_value", currency_field="currency")+ currency = models.CharField(+ max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,+ )++ name = models.CharField(max_length=255, null=True, blank=True)+ translated_name = models.CharField(max_length=255, null=True, blank=True)+ reason = models.TextField(blank=True, null=True)diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex f31a890c4e..73883da073 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -468,9 +468,12 @@ class ModelMutation(BaseMutation):The expected graphene type can be lazy (str)."""object_id = data.get("id")+ qs = data.get("qs")if object_id:model_type = cls.get_type_for_model()- instance = cls.get_node_or_error(info, object_id, only_type=model_type)+ instance = cls.get_node_or_error(+ info, object_id, only_type=model_type, qs=qs+ )else:instance = cls._meta.model()return instancediff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.pyindex e86ccee156..20d305c428 100644--- a/saleor/graphql/discount/dataloaders.py+++ b/saleor/graphql/discount/dataloaders.py@@ -3,7 +3,13 @@ from collections import defaultdictfrom django.db.models import Ffrom ...discount import DiscountInfo-from ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing+from ...discount.models import (+ OrderDiscount,+ Sale,+ SaleChannelListing,+ Voucher,+ VoucherChannelListing,+)from ...discount.utils import (fetch_categories,fetch_collections,@@ -117,3 +123,14 @@ class VoucherChannelListingByVoucherIdLoader(DataLoader):return [voucher_channel_listings_by_voucher_map[voucher_id] for voucher_id in keys]+++class OrderDiscountsByOrderIDLoader(DataLoader):+ context_key = "orderdiscounts_by_order_id"++ def batch_load(self, keys):+ discounts = OrderDiscount.objects.filter(order_id__in=keys)+ discount_map = defaultdict(list)+ for discount in discounts:+ discount_map[discount.order_id].append(discount)+ return [discount_map.get(order_id, []) for order_id in keys]diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.pyindex 54b5a5e8f2..0d079906df 100644--- a/saleor/graphql/discount/types.py+++ b/saleor/graphql/discount/types.py@@ -1,7 +1,7 @@import graphenefrom graphene import relay-from ...core.permissions import DiscountPermissions+from ...core.permissions import DiscountPermissions, OrderPermissionsfrom ...discount import modelsfrom ..channel.dataloaders import ChannelByIdLoaderfrom ..channel.types import ChannelContext, ChannelContextType@@ -12,6 +12,7 @@ from ..core.fields import (ChannelQsContext,PrefetchingConnectionField,)+from ..core.scalars import PositiveDecimalfrom ..core.types import Moneyfrom ..decorators import permission_requiredfrom ..product.types import Category, Collection, Product@@ -266,3 +267,42 @@ class Voucher(ChannelContextType, CountableDjangoObjectType):@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)def resolve_channel_listings(root: ChannelContext[models.Voucher], info, **_kwargs):return VoucherChannelListingByVoucherIdLoader(info.context).load(root.node.id)+++class OrderDiscount(CountableDjangoObjectType):+ 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."+ )+ amount = graphene.Field(+ Money, description="Returns amount of discount.", required=True+ )++ class Meta:+ description = (+ "Contains all details related to the applied discount to the order."+ )+ only_fields = [+ "id",+ "type",+ "value",+ "value_type",+ "reason",+ "name",+ "translated_name",+ ]+ interfaces = [relay.Node]+ model = models.OrderDiscount++ @staticmethod+ @permission_required(OrderPermissions.MANAGE_ORDERS)+ def resolve_reason(root: models.OrderDiscount, _info):+ return root.reasondiff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex bc9ff49fdf..aa213b1e89 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -70,8 +70,8 @@ def filter_created_range(qs, _, value):def filter_order_search(qs, _, value):order_fields = ["pk",- "discount_name",- "translated_discount_name",+ "discounts__name",+ "discounts__translated_name","user_email","user__first_name","user__last_name",diff --git a/saleor/graphql/order/mutations/discount_order.py b/saleor/graphql/order/mutations/discount_order.pynew file mode 100644index 0000000000..8f3d7ddd55--- /dev/null+++ b/saleor/graphql/order/mutations/discount_order.py@@ -0,0 +1,381 @@+import copy++import graphene+from django.core.exceptions import ValidationError+from django.db import transaction+from prices import Money++from ....core.permissions import OrderPermissions+from ....order import OrderStatus, events, models+from ....order.error_codes import OrderErrorCode+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.common import OrderError+from ...discount.enums import DiscountValueTypeEnum+from ...utils import get_user_or_app_from_context+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):+ # This condition can be removed when we introduce discount for the rest type of+ # the orders.+ if order.status != OrderStatus.DRAFT:+ error_msg = "Only draft 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",+ ]+ )+++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+ @transaction.atomic+ def perform_mutation(cls, root, info, **data):+ requester = get_user_or_app_from_context(info.context)+ 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=requester,+ 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+ @transaction.atomic+ def perform_mutation(cls, root, info, **data):+ requester = get_user_or_app_from_context(info.context)+ 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=requester,+ 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+ @transaction.atomic+ def perform_mutation(cls, root, info, **data):+ requester = get_user_or_app_from_context(info.context)+ 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=requester,+ order_discount=order_discount,+ )++ order.refresh_from_db()++ cls.recalculate_order(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+ @transaction.atomic+ def perform_mutation(cls, root, info, **data):++ requester = get_user_or_app_from_context(info.context)+ 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=requester,+ 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+ @transaction.atomic+ def perform_mutation(cls, root, info, **data):+ tax_included = info.context.site.settings.include_taxes_in_prices+ requester = get_user_or_app_from_context(info.context)+ 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=requester,+ line=order_line,+ )++ recalculate_order(order)+ return OrderLineDiscountRemove(order_line=order_line, order=order)diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 573ef474c0..75ff66246b 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -243,10 +243,18 @@ class DraftOrderCreate(ModelMutation, I18nMixin):returnshipping_address = cleaned_input.get("shipping_address")if shipping_address and instance.is_shipping_required():- update_order_prices(instance, info.context.discounts)+ update_order_prices(+ instance,+ info.context.plugins,+ info.context.site.settings.include_taxes_in_prices,+ )billing_address = cleaned_input.get("billing_address")if billing_address and not instance.is_shipping_required():- update_order_prices(instance, info.context.discounts)+ update_order_prices(+ instance,+ info.context.plugins,+ info.context.site.settings.include_taxes_in_prices,+ )@classmethod@transaction.atomic@@ -295,7 +303,9 @@ class DraftOrderUpdate(DraftOrderCreate):@classmethoddef get_instance(cls, info, **data):- instance = super().get_instance(info, **data)+ instance = super().get_instance(+ info, qs=models.Order.objects.prefetch_related("lines"), **data+ )if instance.status != OrderStatus.DRAFT:raise ValidationError({diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.pyindex e18944973f..05ed6273f9 100644--- a/saleor/graphql/order/mutations/orders.py+++ b/saleor/graphql/order/mutations/orders.py@@ -218,7 +218,12 @@ class OrderUpdateShipping(BaseMutation):@classmethoddef perform_mutation(cls, _root, info, **data):- order = cls.get_node_or_error(info, data.get("id"), only_type=Order)+ order = cls.get_node_or_error(+ info,+ data.get("id"),+ only_type=Order,+ qs=models.Order.objects.prefetch_related("lines"),+ )data = data.get("input")if not data["shipping_method"]:@@ -275,7 +280,7 @@ class OrderUpdateShipping(BaseMutation):"shipping_tax_rate",])- update_order_prices(order, info.context.discounts)+ update_order_prices(order, info.context.plugins, info.context.site.settings)# Post-process the resultsorder_shipping_updated(order)return OrderUpdateShipping(order=order)diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.pyindex 2d66509703..3b444494e1 100644--- a/saleor/graphql/order/schema.py+++ b/saleor/graphql/order/schema.py@@ -10,6 +10,13 @@ from .bulk_mutations.draft_orders import DraftOrderBulkDelete, DraftOrderLinesBufrom .bulk_mutations.orders import OrderBulkCancelfrom .enums import OrderStatusFilterfrom .filters import DraftOrderFilter, OrderFilter+from .mutations.discount_order import (+ OrderDiscountAdd,+ OrderDiscountDelete,+ OrderDiscountUpdate,+ OrderLineDiscountRemove,+ OrderLineDiscountUpdate,+)from .mutations.draft_orders import (DraftOrderComplete,DraftOrderCreate,@@ -169,6 +176,13 @@ class OrderMutations(graphene.ObjectType):order_fulfillment_refund_products = FulfillmentRefundProducts.Field()order_fulfillment_return_products = FulfillmentReturnProducts.Field()+ order_discount_add = OrderDiscountAdd.Field()+ order_discount_update = OrderDiscountUpdate.Field()+ order_discount_delete = OrderDiscountDelete.Field()++ order_line_discount_update = OrderLineDiscountUpdate.Field()+ order_line_discount_remove = OrderLineDiscountRemove.Field()+order_mark_as_paid = OrderMarkAsPaid.Field()order_refund = OrderRefund.Field()order_update = OrderUpdate.Field()diff --git a/saleor/graphql/order/tests/benchmark/test_order.py b/saleor/graphql/order/tests/benchmark/test_order.pyindex 3c61aab5b8..051b21d62a 100644--- a/saleor/graphql/order/tests/benchmark/test_order.py+++ b/saleor/graphql/order/tests/benchmark/test_order.py@@ -1,3 +1,4 @@+import grapheneimport pytestfrom ....checkout.tests.benchmark.test_checkout_mutations import (@@ -6,9 +7,21 @@ from ....checkout.tests.benchmark.test_checkout_mutations import ()from ....tests.utils import get_graphql_content+FRAGMENT_DISCOUNTS = """+ fragment OrderDiscounts on OrderDiscount {+ id+ type+ valueType+ value+ name+ translatedName+ }+"""+FRAGMENT_ORDER_DETAILS = (FRAGMENT_ADDRESS+ FRAGMENT_PRODUCT_VARIANT+ + FRAGMENT_DISCOUNTS+ """fragment OrderDetail on Order {userEmail@@ -21,6 +34,9 @@ FRAGMENT_ORDER_DETAILS = (shippingAddress {...Address}+ discounts {+ ...OrderDiscounts+ }lines {productNamequantity@@ -48,7 +64,9 @@ FRAGMENT_ORDER_DETAILS = (@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)-def test_user_order_details(user_api_client, order_with_lines, count_queries):+def test_user_order_details(+ user_api_client, order_with_lines_and_events, count_queries+):query = (FRAGMENT_ORDER_DETAILS+ """@@ -60,6 +78,77 @@ def test_user_order_details(user_api_client, order_with_lines, count_queries):""")variables = {- "token": order_with_lines.token,+ "token": order_with_lines_and_events.token,}get_graphql_content(user_api_client.post_graphql(query, variables))+++FRAGMENT_STAFF_ORDER_DETAILS = (+ FRAGMENT_ORDER_DETAILS+ + """+ fragment OrderStaffDetail on Order {+ ...OrderDetail+ events {+ id+ date+ type+ user {+ }+ message+ emailType+ amount+ paymentId+ paymentGateway+ quantity+ composedId+ orderNumber+ invoiceNumber+ oversoldItems+ lines {+ itemName+ }+ fulfilledItems {+ orderLine {+ id+ }+ }+ warehouse {+ id+ }+ transactionReference+ shippingCostsIncluded+ relatedOrder {+ id+ }+ }+ }++ """+)++[email protected]_queries(autouse=False)+def test_staff_order_details(+ staff_api_client,+ permission_manage_orders,+ order_with_lines_and_events,+ count_queries,+):+ query = (+ FRAGMENT_STAFF_ORDER_DETAILS+ + """+ query Order($id: ID!) {+ order(id: $id) {+ ...OrderStaffDetail+ }+ }+ """+ )+ variables = {+ "id": graphene.Node.to_global_id("Order", order_with_lines_and_events.id),+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ get_graphql_content(staff_api_client.post_graphql(query, variables))diff --git a/saleor/graphql/order/tests/test_discount_order.py b/saleor/graphql/order/tests/test_discount_order.pynew file mode 100644index 0000000000..def066066c--- /dev/null+++ b/saleor/graphql/order/tests/test_discount_order.py@@ -0,0 +1,713 @@+from decimal import Decimal+from functools import partial+from unittest.mock import patch++import graphene+import pytest+from prices import Money, TaxedMoney, fixed_discount, percentage_discount++from ....core.prices import quantize_price+from ....discount import DiscountValueType+from ....order import OrderEvents, OrderStatus+from ....order.error_codes import OrderErrorCode+from ...discount.enums import DiscountValueTypeEnum+from ...tests.utils import get_graphql_content++ORDER_DISCOUNT_ADD = """+mutation OrderDiscountAdd($orderId: ID!, $input: OrderDiscountCommonInput!){+ orderDiscountAdd(orderId:$orderId, input:$input){+ order{+ lines{+ id+ }+ total{+ gross{+ amount+ }+ net{+ amount+ }+ }+ }+ orderErrors{+ field+ code+ message+ }+ }+}+"""+++ "value,value_type",+ [+ (Decimal("2222222"), DiscountValueTypeEnum.FIXED.name),+ (Decimal("101"), DiscountValueTypeEnum.PERCENTAGE.name),+ ],+)+def test_add_order_discount_incorrect_values(+ value, value_type, draft_order, staff_api_client, permission_manage_orders+):+ variables = {+ "orderId": graphene.Node.to_global_id("Order", draft_order.pk),+ "input": {"valueType": value_type, "value": value},+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountAdd"]++ errors = data["orderErrors"]++ error = data["orderErrors"][0]+ assert error["field"] == "value"+ assert error["code"] == OrderErrorCode.INVALID.name++ assert len(errors) == 1+++def test_add_fixed_order_discount_order_is_not_draft(+ order_with_lines, staff_api_client, permission_manage_orders+):+ value = Decimal("10")+ variables = {+ "orderId": graphene.Node.to_global_id("Order", order_with_lines.pk),+ "input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountAdd"]++ errors = data["orderErrors"]+ assert len(errors) == 1+ error = data["orderErrors"][0]+ assert error["field"] == "orderId"+ assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name+++def test_add_fixed_order_discount_to_order(+ draft_order, staff_api_client, permission_manage_orders+):+ total_before_order_discount = draft_order.total+ value = Decimal("10")+ variables = {+ "orderId": graphene.Node.to_global_id("Order", draft_order.pk),+ "input": {"valueType": DiscountValueTypeEnum.FIXED.name, "value": value},+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountAdd"]++ draft_order.refresh_from_db()+ expected_gross = total_before_order_discount.gross.amount - value+ expected_net = total_before_order_discount.net.amount - value++ errors = data["orderErrors"]+ assert len(errors) == 0++ assert expected_gross == draft_order.total.gross.amount+ assert expected_net == draft_order.total.net.amount++ assert draft_order.undiscounted_total == total_before_order_discount++ assert draft_order.discounts.count() == 1+ order_discount = draft_order.discounts.first()+ assert order_discount.value == value+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.amount.amount == value+ assert order_discount.reason is None++ event = draft_order.events.get()+ assert event.type == OrderEvents.ORDER_DISCOUNT_ADDED+ parameters = event.parameters+ discount_data = parameters.get("discount")++ assert discount_data["value"] == str(value)+ assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value+ assert discount_data["amount_value"] == str(order_discount.amount.amount)+++def test_add_percentage_order_discount_to_order(+ draft_order, staff_api_client, permission_manage_orders+):+ total_before_order_discount = draft_order.total+ reason = "The reason of the discount"+ value = Decimal("10.000")+ variables = {+ "orderId": graphene.Node.to_global_id("Order", draft_order.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,+ "value": value,+ "reason": reason,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountAdd"]++ draft_order.refresh_from_db()++ discount = partial(percentage_discount, percentage=value)+ expected_net_total = discount(total_before_order_discount.net)+ expected_gross_total = discount(total_before_order_discount.gross)+ expected_total = TaxedMoney(expected_net_total, expected_gross_total)++ errors = data["orderErrors"]+ assert len(errors) == 0++ assert expected_total == draft_order.total++ assert draft_order.undiscounted_total == total_before_order_discount++ assert draft_order.discounts.count() == 1+ order_discount = draft_order.discounts.first()+ assert order_discount.value == value+ assert order_discount.value_type == DiscountValueType.PERCENTAGE+ assert order_discount.amount == (total_before_order_discount - expected_total).gross+ assert order_discount.reason == reason++ event = draft_order.events.get()+ assert event.type == OrderEvents.ORDER_DISCOUNT_ADDED+ parameters = event.parameters+ discount_data = parameters.get("discount")++ assert discount_data["value"] == str(value)+ assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value+ assert discount_data["amount_value"] == str(order_discount.amount.amount)+++ORDER_DISCOUNT_UPDATE = """+mutation OrderDiscountUpdate($discountId: ID!, $input: OrderDiscountCommonInput!){+ orderDiscountUpdate(discountId:$discountId, input: $input){+ order{+ id+ total{+ gross{+ amount+ }+ }+ undiscountedTotal{+ gross{+ amount+ }+ }+ }+ orderErrors{+ field+ message+ code+ }+ }+}+"""+++def test_update_percentage_order_discount_to_order(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order = draft_order_with_fixed_discount_order+ order_discount = draft_order_with_fixed_discount_order.discounts.get()+ current_undiscounted_total = draft_order.undiscounted_total++ reason = "The reason of the discount"+ value = Decimal("10.000")+ variables = {+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,+ "value": value,+ "reason": reason,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountUpdate"]++ draft_order.refresh_from_db()++ discount = partial(percentage_discount, percentage=value)+ expected_net_total = discount(current_undiscounted_total.net)+ expected_gross_total = discount(current_undiscounted_total.gross)+ expected_total = TaxedMoney(expected_net_total, expected_gross_total)++ errors = data["orderErrors"]+ assert len(errors) == 0++ assert draft_order.undiscounted_total == current_undiscounted_total++ assert expected_total == draft_order.total++ assert draft_order.discounts.count() == 1+ order_discount = draft_order.discounts.first()+ assert order_discount.value == value+ assert order_discount.value_type == DiscountValueType.PERCENTAGE+ assert order_discount.amount == (current_undiscounted_total - expected_total).gross+ assert order_discount.reason == reason++ event = draft_order.events.get()+ assert event.type == OrderEvents.ORDER_DISCOUNT_UPDATED+ parameters = event.parameters+ discount_data = parameters.get("discount")++ assert discount_data["value"] == str(value)+ assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value+ assert discount_data["amount_value"] == str(order_discount.amount.amount)+++def test_update_fixed_order_discount_to_order(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order = draft_order_with_fixed_discount_order+ order_discount = draft_order_with_fixed_discount_order.discounts.get()+ current_undiscounted_total = draft_order.undiscounted_total++ value = Decimal("50.000")+ variables = {+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.FIXED.name,+ "value": value,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountUpdate"]++ draft_order.refresh_from_db()++ discount = partial(+ fixed_discount, discount=Money(value, currency=draft_order.currency)+ )+ expected_total = discount(current_undiscounted_total)++ errors = data["orderErrors"]+ assert len(errors) == 0++ assert draft_order.undiscounted_total == current_undiscounted_total++ assert expected_total == draft_order.total++ assert draft_order.discounts.count() == 1+ order_discount = draft_order.discounts.first()+ assert order_discount.value == value+ assert order_discount.value_type == DiscountValueType.FIXED+ assert order_discount.amount == (current_undiscounted_total - expected_total).gross++ event = draft_order.events.get()+ assert event.type == OrderEvents.ORDER_DISCOUNT_UPDATED+ parameters = event.parameters+ discount_data = parameters.get("discount")++ assert discount_data["value"] == str(value)+ assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value+ assert discount_data["amount_value"] == str(order_discount.amount.amount)+++def test_update_order_discount_order_is_not_draft(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED+ draft_order_with_fixed_discount_order.save()++ order_discount = draft_order_with_fixed_discount_order.discounts.get()++ value = Decimal("50")+ variables = {+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.FIXED.name,+ "value": value,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountUpdate"]++ errors = data["orderErrors"]+ assert len(errors) == 1++ error = data["orderErrors"][0]+ assert error["field"] == "orderId"+ assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name+++ "value,value_type",+ [+ (Decimal("2222222"), DiscountValueTypeEnum.FIXED.name),+ (Decimal("101"), DiscountValueTypeEnum.PERCENTAGE.name),+ ],+)+def test_update_order_discount_incorrect_values(+ value,+ value_type,+ draft_order_with_fixed_discount_order,+ staff_api_client,+ permission_manage_orders,+):+ order_discount = draft_order_with_fixed_discount_order.discounts.get()++ variables = {+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),+ "input": {+ "valueType": value_type,+ "value": value,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountUpdate"]++ errors = data["orderErrors"]+ assert len(errors) == 1++ error = errors[0]+ assert error["field"] == "value"+ assert error["code"] == OrderErrorCode.INVALID.name+++ORDER_DISCOUNT_DELETE = """+mutation OrderDiscountDelete($discountId: ID!){+ orderDiscountDelete(discountId: $discountId){+ order{+ id+ }+ orderErrors{+ field+ message+ code+ }+ }+}+"""+++def test_delete_order_discount_from_order(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order = draft_order_with_fixed_discount_order+ order_discount = draft_order_with_fixed_discount_order.discounts.get()+ current_undiscounted_total = draft_order.undiscounted_total++ variables = {+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountDelete"]++ draft_order.refresh_from_db()++ errors = data["orderErrors"]+ assert len(errors) == 0++ assert draft_order.undiscounted_total == current_undiscounted_total+ assert draft_order.total == current_undiscounted_total++ event = draft_order.events.get()+ assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED+++def test_delete_order_discount_order_is_not_draft(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED+ draft_order_with_fixed_discount_order.save()++ order_discount = draft_order_with_fixed_discount_order.discounts.get()++ variables = {+ "discountId": graphene.Node.to_global_id("OrderDiscount", order_discount.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderDiscountDelete"]++ errors = data["orderErrors"]+ assert len(errors) == 1++ assert draft_order_with_fixed_discount_order.discounts.get()++ error = data["orderErrors"][0]+ assert error["field"] == "orderId"+ assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name+++ORDER_LINE_DISCOUNT_UPDATE = """+mutation OrderLineDiscountUpdate($input: OrderDiscountCommonInput!, $orderLineId: ID!){+ orderLineDiscountUpdate(orderLineId: $orderLineId, input: $input){+ orderLine{+ unitPrice{+ gross{+ amount+ }+ }+ }+ orderErrors{+ field+ message+ code+ }+ }+}+"""+++def test_update_order_line_discount(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ line_to_discount = draft_order_with_fixed_discount_order.lines.first()+ unit_price = Money(Decimal(7.3), currency="USD")+ line_to_discount.unit_price = TaxedMoney(unit_price, unit_price)+ line_to_discount.save()++ line_price_before_discount = line_to_discount.unit_price++ value = Decimal("5")+ reason = "New reason for unit discount"+ variables = {+ "orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.FIXED.name,+ "value": value,+ "reason": reason,+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderLineDiscountUpdate"]++ line_to_discount.refresh_from_db()++ errors = data["orderErrors"]+ assert not errors++ discount = partial(+ fixed_discount,+ discount=Money(value, currency=draft_order_with_fixed_discount_order.currency),+ )+ expected_line_price = discount(line_price_before_discount)++ assert line_to_discount.unit_price == quantize_price(expected_line_price, "USD")+ unit_discount = line_to_discount.unit_discount+ assert unit_discount == (line_price_before_discount - expected_line_price).gross++ event = draft_order_with_fixed_discount_order.events.get()+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_UPDATED+ parameters = event.parameters+ lines = parameters.get("lines", {})+ assert len(lines) == 1++ line_data = lines[0]+ assert line_data.get("line_pk") == line_to_discount.pk+ discount_data = line_data.get("discount")++ assert discount_data["value"] == str(value)+ assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value+ assert discount_data["amount_value"] == str(unit_discount.amount)+++def test_update_order_line_discount_line_with_discount(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ line_to_discount = draft_order_with_fixed_discount_order.lines.first()+ unit_price = quantize_price(Money(Decimal(7.3), currency="USD"), currency="USD")+ line_to_discount.unit_price = TaxedMoney(unit_price, unit_price)++ line_to_discount.unit_discount_amount = Decimal("2.500")+ line_to_discount.unit_discount_type = DiscountValueType.FIXED+ line_to_discount.unit_discount_value = Decimal("2.500")+ line_to_discount.save()++ line_discount_amount_before_update = line_to_discount.unit_discount_amount+ line_discount_value_before_update = line_to_discount.unit_discount_value++ line_undiscounted_price = line_to_discount.undiscounted_unit_price++ value = Decimal("50")+ reason = "New reason for unit discount"+ variables = {+ "orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.PERCENTAGE.name,+ "value": value,+ "reason": reason,+ },+ }++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderLineDiscountUpdate"]++ line_to_discount.refresh_from_db()++ errors = data["orderErrors"]+ assert not errors++ discount = partial(+ percentage_discount,+ percentage=value,+ )+ expected_line_price = discount(line_undiscounted_price)++ assert line_to_discount.unit_price == expected_line_price+ unit_discount = line_to_discount.unit_discount+ assert unit_discount == (line_undiscounted_price - expected_line_price).gross++ event = draft_order_with_fixed_discount_order.events.get()+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_UPDATED+ parameters = event.parameters+ lines = parameters.get("lines", {})+ assert len(lines) == 1++ line_data = lines[0]+ assert line_data.get("line_pk") == line_to_discount.pk+ discount_data = line_data.get("discount")++ assert discount_data["value"] == str(value)+ assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value+ assert discount_data["amount_value"] == str(unit_discount.amount)++ assert discount_data["old_value"] == str(line_discount_value_before_update)+ assert discount_data["old_value_type"] == DiscountValueTypeEnum.FIXED.value+ assert discount_data["old_amount_value"] == str(line_discount_amount_before_update)+++def test_update_order_line_discount_order_is_not_draft(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED+ draft_order_with_fixed_discount_order.save()++ line_to_discount = draft_order_with_fixed_discount_order.lines.first()++ variables = {+ "orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),+ "input": {+ "valueType": DiscountValueTypeEnum.FIXED.name,+ "value": Decimal("5"),+ "reason": "New reason for unit discount",+ },+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderLineDiscountUpdate"]++ line_to_discount.refresh_from_db()++ errors = data["orderErrors"]+ assert len(errors) == 1++ error = data["orderErrors"][0]+ assert error["field"] == "orderId"+ assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name++ assert line_to_discount.unit_discount_amount == Decimal("0")+++ORDER_LINE_DISCOUNT_REMOVE = """+mutation OrderLineDiscountRemove($orderLineId: ID!){+ orderLineDiscountRemove(orderLineId: $orderLineId){+ orderLine{+ id+ }+ orderErrors{+ field+ message+ code+ }+ }+}+"""+++@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")+def test_delete_discount_from_order_line(+ mocked_calculate_order_line_unit,+ draft_order_with_fixed_discount_order,+ staff_api_client,+ permission_manage_orders,+):+ line = draft_order_with_fixed_discount_order.lines.first()++ line_undiscounted_price = line.undiscounted_unit_price++ mocked_calculate_order_line_unit.return_value = line_undiscounted_price++ line.unit_discount_amount = Decimal("2.5")+ line.unit_discount_type = DiscountValueType.FIXED+ line.unit_discount_value = Decimal("2.5")+ line.save()++ variables = {+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderLineDiscountRemove"]++ errors = data["orderErrors"]+ assert len(errors) == 0++ line.refresh_from_db()++ assert line.unit_price == line_undiscounted_price+ unit_discount = line.unit_discount+ currency = draft_order_with_fixed_discount_order.currency+ assert unit_discount == Money(Decimal(0), currency=currency)++ event = draft_order_with_fixed_discount_order.events.get()+ assert event.type == OrderEvents.ORDER_LINE_DISCOUNT_REMOVED+ parameters = event.parameters+ lines = parameters.get("lines", {})+ assert len(lines) == 1++ line_data = lines[0]+ assert line_data.get("line_pk") == line.pk+++def test_delete_order_line_discount_order_is_not_draft(+ draft_order_with_fixed_discount_order, staff_api_client, permission_manage_orders+):+ draft_order_with_fixed_discount_order.status = OrderStatus.UNFULFILLED+ draft_order_with_fixed_discount_order.save()++ line = draft_order_with_fixed_discount_order.lines.first()++ line.unit_discount_amount = Decimal("2.5")+ line.unit_discount_type = DiscountValueType.FIXED+ line.unit_discount_value = Decimal("2.5")+ line.save()++ variables = {+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),+ }+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)+ content = get_graphql_content(response)+ data = content["data"]["orderLineDiscountRemove"]++ errors = data["orderErrors"]+ assert len(errors) == 1++ assert draft_order_with_fixed_discount_order.discounts.get()++ error = data["orderErrors"][0]+ assert error["field"] == "orderId"+ assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name++ assert line.unit_discount_amount == Decimal("2.5")diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 78620cb393..8a6462fd24 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -12,7 +12,9 @@ from freezegun import freeze_timefrom prices import Money, TaxedMoneyfrom ....account.models import CustomerEvent+from ....core.prices import quantize_pricefrom ....core.taxes import TaxError, zero_taxed_money+from ....discount.models import OrderDiscountfrom ....order import OrderStatusfrom ....order import events as order_eventsfrom ....order.error_codes import OrderErrorCode@@ -267,6 +269,28 @@ query OrdersQuery {shippingTaxRatelines {id+ unitPrice{+ gross{+ amount+ }+ }+ unitDiscount{+ amount+ }+ undiscountedUnitPrice{+ gross{+ amount+ }+ }+ }+ discounts{+ id+ valueType+ value+ reason+ amount{+ amount+ }}fulfillments {fulfillmentOrder@@ -368,6 +392,95 @@ def test_order_query(assert expected_method.type.upper() == method["type"]+def test_order_discounts_query(+ staff_api_client,+ permission_manage_orders,+ draft_order_with_fixed_discount_order,+):+ # given+ order = draft_order_with_fixed_discount_order+ order.status = OrderStatus.UNFULFILLED+ order.save()++ discount = order.discounts.get()++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ discounts_data = order_data.get("discounts")+ assert len(discounts_data) == 1+ discount_data = discounts_data[0]+ _, discount_id = graphene.Node.from_global_id(discount_data["id"])+ assert int(discount_id) == discount.id+ assert discount_data["valueType"] == discount.value_type.upper()+ assert discount_data["value"] == discount.value+ assert discount_data["amount"]["amount"] == discount.amount_value+ assert discount_data["reason"] == discount.reason+++def test_order_line_discount_query(+ staff_api_client,+ permission_manage_orders,+ draft_order_with_fixed_discount_order,+):+ # given+ order = draft_order_with_fixed_discount_order+ order.status = OrderStatus.UNFULFILLED+ order.save()++ unit_discount_value = Decimal("5.0")+ line = order.lines.first()+ line.unit_discount = Money(unit_discount_value, currency=order.currency)+ line.unit_price -= line.unit_discount+ line.save()++ line_with_discount_id = graphene.Node.to_global_id("OrderLine", line.pk)++ staff_api_client.user.user_permissions.add(permission_manage_orders)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ lines_data = order_data.get("lines")+ line_with_discount = [+ line for line in lines_data if line["id"] == line_with_discount_id+ ][0]++ unit_gross_amount = quantize_price(+ Decimal(line_with_discount["unitPrice"]["gross"]["amount"]),+ currency=order.currency,+ )+ unit_discount_amount = quantize_price(+ Decimal(line_with_discount["unitDiscount"]["amount"]), currency=order.currency+ )+ undiscounted_unit_price = quantize_price(+ Decimal(line_with_discount["undiscountedUnitPrice"]["gross"]["amount"]),+ currency=order.currency,+ )++ expected_unit_price_gross_amount = quantize_price(+ line.unit_price.gross.amount, currency=order.currency+ )+ expected_unit_discount_amount = quantize_price(+ line.unit_discount.amount, currency=order.currency+ )+ expected_undiscounted_unit_price = quantize_price(+ line.undiscounted_unit_price.gross.amount, currency=order.currency+ )++ assert unit_gross_amount == expected_unit_price_gross_amount+ assert unit_discount_amount == expected_unit_discount_amount+ assert undiscounted_unit_price == expected_undiscounted_unit_price++def test_order_query_in_pln_channel(staff_api_client,permission_manage_orders,@@ -4730,9 +4843,7 @@ def test_orders_query_with_filter_search(Order(user=customer_user,token=str(uuid.uuid4()),- discount_name="test_discount1",user_email="[email protected]",- translated_discount_name="translated_discount1_name",channel=channel_USD,),Order(@@ -4743,12 +4854,29 @@ def test_orders_query_with_filter_search(Order(token=str(uuid.uuid4()),user_email="[email protected]",- discount_name="test_discount2",- translated_discount_name="translated_discount2_name",channel=channel_USD,),])++ OrderDiscount.objects.bulk_create(+ [+ OrderDiscount(+ order=orders[0],+ name="test_discount1",+ value=Decimal("1"),+ amount_value=Decimal("1"),+ translated_name="translated_discount1_name",+ ),+ OrderDiscount(+ order=orders[2],+ name="test_discount2",+ value=Decimal("10"),+ amount_value=Decimal("10"),+ translated_name="translated_discount2_name",+ ),+ ]+ )order_with_payment = orders[1]payment = Payment.objects.create(order=order_with_payment)payment.transactions.create(@@ -4775,9 +4903,7 @@ def test_orders_query_with_filter_search_by_global_payment_id(user=customer_user,token=str(uuid.uuid4()),channel=channel_USD,- discount_name="test_discount1",user_email="[email protected]",- translated_discount_name="translated_discount1_name",),Order(token=str(uuid.uuid4()),@@ -4786,6 +4912,14 @@ def test_orders_query_with_filter_search_by_global_payment_id(),])+ OrderDiscount.objects.create(+ order=orders[0],+ name="test_discount1",+ value=Decimal("1"),+ amount_value=Decimal("1"),+ translated_name="translated_discount1_name",+ ),+order_with_payment = orders[0]payment = Payment.objects.create(order=order_with_payment)global_id = graphene.Node.to_global_id("Payment", payment.pk)@@ -4830,14 +4964,12 @@ def test_draft_orders_query_with_filter_search(customer_user,channel_USD,):- Order.objects.bulk_create(+ orders = Order.objects.bulk_create([Order(user=customer_user,token=str(uuid.uuid4()),- discount_name="test_discount1",user_email="[email protected]",- translated_discount_name="translated_discount1_name",status=OrderStatus.DRAFT,channel=channel_USD,),@@ -4850,13 +4982,29 @@ def test_draft_orders_query_with_filter_search(Order(token=str(uuid.uuid4()),user_email="[email protected]",- discount_name="test_discount2",- translated_discount_name="translated_discount2_name",status=OrderStatus.DRAFT,channel=channel_USD,),])+ OrderDiscount.objects.bulk_create(+ [+ OrderDiscount(+ order=orders[0],+ name="test_discount1",+ value=Decimal("1"),+ amount_value=Decimal("1"),+ translated_name="translated_discount1_name",+ ),+ OrderDiscount(+ order=orders[2],+ name="test_discount2",+ value=Decimal("10"),+ amount_value=Decimal("10"),+ translated_name="translated_discount2_name",+ ),+ ]+ )variables = {"filter": draft_orders_filter}staff_api_client.user.user_permissions.add(permission_manage_orders)response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.pyindex 7befd0ccb5..6d8b53d8f7 100644--- a/saleor/graphql/order/tests/test_pagination.py+++ b/saleor/graphql/order/tests/test_pagination.py@@ -1,11 +1,13 @@import uuidfrom datetime import date, timedelta+from decimal import Decimalimport grapheneimport pytestfrom freezegun import freeze_timefrom prices import Money, TaxedMoney+from ....discount.models import OrderDiscountfrom ....order.models import Order, OrderStatusfrom ....payment import ChargeStatusfrom ...tests.utils import get_graphql_content@@ -414,14 +416,12 @@ def test_orders_query_pagination_with_filter_search(orders_for_pagination,channel_USD,):- Order.objects.bulk_create(+ orders = Order.objects.bulk_create([Order(user=customer_user,token=str(uuid.uuid4()),- discount_name="test_discount1",user_email="[email protected]",- translated_discount_name="translated_discount1_name",channel=channel_USD,),Order(@@ -432,12 +432,28 @@ def test_orders_query_pagination_with_filter_search(Order(token=str(uuid.uuid4()),user_email="[email protected]",- discount_name="test_discount2",- translated_discount_name="translated_discount2_name",channel=channel_USD,),])+ OrderDiscount.objects.bulk_create(+ [+ OrderDiscount(+ order=orders[0],+ name="test_discount1",+ value=Decimal("1"),+ amount_value=Decimal("1"),+ translated_name="translated_discount1_name",+ ),+ OrderDiscount(+ order=orders[2],+ name="test_discount2",+ value=Decimal("10"),+ amount_value=Decimal("10"),+ translated_name="translated_discount2_name",+ ),+ ]+ )page_size = 2variables = {"first": page_size, "after": None, "filter": orders_filter}staff_api_client.user.user_permissions.add(permission_manage_orders)@@ -487,14 +503,12 @@ def test_draft_orders_query_pagination_with_filter_search(draft_orders_for_pagination,channel_USD,):- Order.objects.bulk_create(+ orders = Order.objects.bulk_create([Order(user=customer_user,token=str(uuid.uuid4()),- discount_name="test_discount1",user_email="[email protected]",- translated_discount_name="translated_discount1_name",status=OrderStatus.DRAFT,channel=channel_USD,),@@ -507,13 +521,29 @@ def test_draft_orders_query_pagination_with_filter_search(Order(token=str(uuid.uuid4()),user_email="[email protected]",- discount_name="test_discount2",- translated_discount_name="translated_discount2_name",status=OrderStatus.DRAFT,channel=channel_USD,),])+ OrderDiscount.objects.bulk_create(+ [+ OrderDiscount(+ order=orders[0],+ name="test_discount1",+ value=Decimal("1"),+ amount_value=Decimal("1"),+ translated_name="translated_discount1_name",+ ),+ OrderDiscount(+ order=orders[2],+ name="test_discount2",+ value=Decimal("10"),+ amount_value=Decimal("10"),+ translated_name="translated_discount2_name",+ ),+ ]+ )page_size = 2variables = {"first": page_size, "after": None, "filter": draft_orders_filter}staff_api_client.user.user_permissions.add(permission_manage_orders)diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 6f73a8f1c2..010dd51e85 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -1,4 +1,8 @@+from decimal import Decimal+from typing import Optional+import graphene+import pricesfrom django.core.exceptions import ValidationErrorfrom graphene import relayfrom promise import Promise@@ -8,6 +12,7 @@ from ...core.anonymize import obfuscate_address, obfuscate_emailfrom ...core.exceptions import PermissionDeniedfrom ...core.permissions import AccountPermissions, OrderPermissions, ProductPermissionsfrom ...core.taxes import display_gross_prices+from ...discount import OrderDiscountTypefrom ...graphql.utils import get_user_or_app_from_contextfrom ...order import OrderStatus, modelsfrom ...order.models import FulfillmentStatus@@ -20,10 +25,12 @@ from ..account.utils import requestor_has_accessfrom ..channel import ChannelContextfrom ..channel.dataloaders import ChannelByIdLoader, ChannelByOrderLineIdLoaderfrom ..core.connection import CountableDjangoObjectType+from ..core.scalars import PositiveDecimalfrom ..core.types.common import Imagefrom ..core.types.money import Money, TaxedMoneyfrom ..decorators import one_of_permissions_required, permission_required-from ..discount.dataloaders import VoucherByIdLoader+from ..discount.dataloaders import OrderDiscountsByOrderIDLoader, VoucherByIdLoader+from ..discount.enums import DiscountValueTypeEnumfrom ..giftcard.types import GiftCardfrom ..invoice.types import Invoicefrom ..meta.types import ObjectWithMetadata@@ -39,16 +46,72 @@ from ..warehouse.types import Allocation, Warehousefrom .dataloaders import (AllocationsByOrderLineIdLoader,OrderByIdLoader,+ OrderLineByIdLoader,OrderLinesByOrderIdLoader,)from .enums import OrderEventsEmailsEnum, OrderEventsEnumfrom .utils import validate_draft_order+def get_order_discount_event(discount_obj: dict):+ currency = discount_obj["currency"]++ amount = prices.Money(Decimal(discount_obj["amount_value"]), currency)++ old_amount = None+ old_amount_value = discount_obj.get("old_amount_value")+ if old_amount_value:+ old_amount = prices.Money(Decimal(old_amount_value), currency)++ return OrderEventDiscountObject(+ value=discount_obj.get("value"),+ amount=amount,+ value_type=discount_obj.get("value_type"),+ reason=discount_obj.get("reason"),+ old_value_type=discount_obj.get("old_value_type"),+ old_value=discount_obj.get("old_value"),+ old_amount=old_amount,+ )+++class OrderDiscount(graphene.ObjectType):+ 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."+ )+ amount = graphene.Field(Money, description="Returns amount of discount.")+++class OrderEventDiscountObject(OrderDiscount):+ old_value_type = graphene.Field(+ DiscountValueTypeEnum,+ required=False,+ description="Type of the discount: fixed or percent.",+ )+ old_value = PositiveDecimal(+ required=False,+ description="Value of the discount. Can store fixed value or percent value.",+ )+ old_amount = graphene.Field(+ Money, required=False, description="Returns amount of discount."+ )++class OrderEventOrderLineObject(graphene.ObjectType):quantity = graphene.Int(description="The variant quantity.")order_line = graphene.Field(lambda: OrderLine, description="The order line.")item_name = graphene.String(description="The variant name.")+ discount = graphene.Field(+ OrderEventDiscountObject, description="The discount applied to the order line."+ )class OrderEvent(CountableDjangoObjectType):@@ -90,6 +153,9 @@ class OrderEvent(CountableDjangoObjectType):related_order = graphene.Field(lambda: Order, description="The order which is related to this order.")+ discount = graphene.Field(+ OrderEventDiscountObject, description="The discount applied to the order."+ )class Meta:description = "History log of the order."@@ -155,7 +221,7 @@ class OrderEvent(CountableDjangoObjectType):return root.parameters.get("invoice_number")@staticmethod- def resolve_lines(root: models.OrderEvent, _info):+ def resolve_lines(root: models.OrderEvent, info):raw_lines = root.parameters.get("lines", None)if not raw_lines:@@ -163,25 +229,33 @@ class OrderEvent(CountableDjangoObjectType):line_pks = []for entry in raw_lines:- line_pks.append(entry.get("line_pk", None))-- lines = models.OrderLine.objects.filter(pk__in=line_pks).all()- results = []- for raw_line, line_pk in zip(raw_lines, line_pks):- line_object = None- for line in lines:- if line.pk == line_pk:- line_object = line- break- results.append(- OrderEventOrderLineObject(- quantity=raw_line["quantity"],- order_line=line_object,- item_name=raw_line["item"],+ line_pk = entry.get("line_pk", None)+ if line_pk:+ line_pks.append(line_pk)++ def _resolve_lines(lines):+ results = []+ lines_dict = {line.pk: line for line in lines if line}+ for raw_line in raw_lines:+ line_pk = raw_line.get("line_pk")+ line_object = lines_dict.get(line_pk)+ discount = raw_line.get("discount")+ if discount:+ discount = get_order_discount_event(discount)+ results.append(+ OrderEventOrderLineObject(+ quantity=raw_line["quantity"],+ order_line=line_object,+ item_name=raw_line["item"],+ discount=discount,+ ))- )- return results+ return results++ return (+ OrderLineByIdLoader(info.context).load_many(line_pks).then(_resolve_lines)+ )@staticmethoddef resolve_fulfilled_items(root: models.OrderEvent, _info):@@ -208,6 +282,13 @@ class OrderEvent(CountableDjangoObjectType):return Nonereturn OrderByIdLoader(info.context).load(order_pk)+ @staticmethod+ def resolve_discount(root: models.OrderEvent, info):+ discount_obj = root.parameters.get("discount")+ if not discount_obj:+ return None+ return get_order_discount_event(discount_obj)+class FulfillmentLine(CountableDjangoObjectType):order_line = graphene.Field(lambda: OrderLine)@@ -271,6 +352,24 @@ class OrderLine(CountableDjangoObjectType):description="Price of the single item in the order line.",required=True,)+ undiscounted_unit_price = graphene.Field(+ TaxedMoney,+ description=(+ "Price of the single item in the order line without applied an order line "+ "discount."+ ),+ required=True,+ )+ unit_discount = graphene.Field(+ Money,+ description="The discount applied to the single order line.",+ required=True,+ )+ unit_discount_value = graphene.Field(+ PositiveDecimal,+ description="Value of the discount. Can store fixed value or percent value",+ required=True,+ )total_price = graphene.Field(TaxedMoney, description="Price of the order line.", required=True)@@ -292,6 +391,10 @@ class OrderLine(CountableDjangoObjectType):graphene.NonNull(Allocation),description="List of allocations across warehouses.",)+ unit_discount_type = graphene.Field(+ DiscountValueTypeEnum,+ description="Type of the discount: fixed or percent",+ )class Meta:description = "Represents order line of particular order."@@ -307,6 +410,7 @@ class OrderLine(CountableDjangoObjectType):"quantity","quantity_fulfilled","tax_rate",+ "unit_discount_reason",]@staticmethod@@ -324,6 +428,22 @@ class OrderLine(CountableDjangoObjectType):def resolve_unit_price(root: models.OrderLine, _info):return root.unit_price+ @staticmethod+ def resolve_undiscounted_unit_price(root: models.OrderLine, _info):+ return root.undiscounted_unit_price++ @staticmethod+ def resolve_unit_discount_type(root: models.OrderLine, _info):+ return root.unit_discount_type++ @staticmethod+ def resolve_unit_discount_value(root: models.OrderLine, _info):+ return root.unit_discount_value++ @staticmethod+ def resolve_unit_discount(root: models.OrderLine, _info):+ return root.unit_discount+@staticmethoddef resolve_total_price(root: models.OrderLine, _info):return root.total_price@@ -410,6 +530,9 @@ class Order(CountableDjangoObjectType):total = graphene.Field(TaxedMoney, description="Total amount of the order.", required=True)+ undiscounted_total = graphene.Field(+ TaxedMoney, description="Undiscounted total amount of the order.", required=True+ )shipping_price = graphene.Field(TaxedMoney, description="Total price of shipping.", required=True)@@ -447,6 +570,32 @@ class Order(CountableDjangoObjectType):is_shipping_required = graphene.Boolean(description="Returns True, if order requires shipping.", required=True)+ discount = graphene.Field(+ Money,+ description="Returns applied discount.",+ deprecation_reason=(+ "Use discounts field. This field will be removed in Saleor 4.0."+ ),+ )+ discount_name = graphene.String(+ description="Discount name.",+ deprecation_reason=(+ "Use discounts field. This field will be removed in Saleor 4.0."+ ),+ )++ translated_discount_name = graphene.String(+ description="Translated discount name.",+ deprecation_reason=(+ "Use discounts field. This field will be removed in Saleor 4.0."+ ),+ )++ discounts = graphene.List(+ graphene.NonNull("saleor.graphql.discount.types.OrderDiscount"),+ description="List of all discounts assigned to the order.",+ required=False,+ )class Meta:description = "Represents an order in the shop."@@ -478,6 +627,58 @@ class Order(CountableDjangoObjectType):"redirect_url",]+ @staticmethod+ def resolve_discounts(root: models.Order, info):+ return OrderDiscountsByOrderIDLoader(info.context).load(root.id)++ @staticmethod+ def resolve_discount(root: models.Order, info):+ def return_voucher_discount(discounts) -> Optional[Money]:+ if not discounts:+ return None+ for discount in discounts:+ if discount.type == OrderDiscountType.VOUCHER:+ return Money(amount=discount.value, currency=discount.currency)+ return None++ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(root.id)+ .then(return_voucher_discount)+ )++ @staticmethod+ def resolve_discount_name(root: models.Order, info):+ def return_voucher_name(discounts) -> Optional[Money]:+ if not discounts:+ return None+ for discount in discounts:+ if discount.type == OrderDiscountType.VOUCHER:+ return discount.name+ return None++ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(root.id)+ .then(return_voucher_name)+ )++ @staticmethod+ def resolve_translated_discount_name(root: models.Order, info):+ def return_voucher_translated_name(discounts) -> Optional[Money]:+ if not discounts:+ return None+ for discount in discounts:+ if discount.type == OrderDiscountType.VOUCHER:+ return discount.translated_name+ return None++ return (+ OrderDiscountsByOrderIDLoader(info.context)+ .load(root.id)+ .then(return_voucher_translated_name)+ )+@staticmethoddef resolve_billing_address(root: models.Order, info):requester = get_user_or_app_from_context(info.context)@@ -518,6 +719,10 @@ class Order(CountableDjangoObjectType):def resolve_total(root: models.Order, _info):return root.total+ @staticmethod+ def resolve_undiscounted_total(root: models.Order, _info):+ return root.undiscounted_total+@staticmethoddef resolve_total_authorized(root: models.Order, _info):# FIXME adjust to multiple payments in the future@@ -548,7 +753,7 @@ class Order(CountableDjangoObjectType):@staticmethod@permission_required(OrderPermissions.MANAGE_ORDERS)def resolve_events(root: models.Order, _info):- return root.events.all().order_by("pk")+ return root.events.prefetch_related("user").all().order_by("pk")@staticmethoddef resolve_is_paid(root: models.Order, _info):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4a5b97ca62..5d0c1ce915 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2706,6 +2706,11 @@ type Mutation {orderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTrackingorderFulfillmentRefundProducts(input: OrderRefundProductsInput!, order: ID!): FulfillmentRefundProductsorderFulfillmentReturnProducts(input: OrderReturnProductsInput!, order: ID!): FulfillmentReturnProducts+ orderDiscountAdd(input: OrderDiscountCommonInput!, orderId: ID!): OrderDiscountAdd+ orderDiscountUpdate(discountId: ID!, input: OrderDiscountCommonInput!): OrderDiscountUpdate+ orderDiscountDelete(discountId: ID!): OrderDiscountDelete+ orderLineDiscountUpdate(input: OrderDiscountCommonInput!, orderLineId: ID!): OrderLineDiscountUpdate+ orderLineDiscountRemove(orderLineId: ID!): OrderLineDiscountRemoveorderMarkAsPaid(id: ID!, transactionReference: String): OrderMarkAsPaidorderRefund(amount: PositiveDecimal!, id: ID!): OrderRefundorderUpdate(id: ID!, input: OrderUpdateInput!): OrderUpdate@@ -2881,9 +2886,6 @@ type Order implements Node & ObjectWithMetadata {token: String!voucher: VouchergiftCards: [GiftCard]- discount: Money- discountName: String- translatedDiscountName: StringdisplayGrossPrices: Boolean!customerNote: String!weight: Weight@@ -2901,6 +2903,7 @@ type Order implements Node & ObjectWithMetadata {paymentStatusDisplay: String!payments: [Payment]total: TaxedMoney!+ undiscountedTotal: TaxedMoney!subtotal: TaxedMoney!statusDisplay: StringcanFinalize: Boolean!@@ -2910,6 +2913,10 @@ type Order implements Node & ObjectWithMetadata {totalBalance: Money!userEmail: StringisShippingRequired: Boolean!+ discount: Money @deprecated(reason: "Use discounts field. This field will be removed in Saleor 4.0.")+ discountName: String @deprecated(reason: "Use discounts field. This field will be removed in Saleor 4.0.")+ translatedDiscountName: String @deprecated(reason: "Use discounts field. This field will be removed in Saleor 4.0.")+ discounts: [OrderDiscount!]}enum OrderAction {@@ -2970,6 +2977,46 @@ enum OrderDirection {DESC}+type OrderDiscount implements Node {+ id: ID!+ type: OrderDiscountType!+ valueType: DiscountValueTypeEnum!+ value: PositiveDecimal!+ name: String+ translatedName: String+ reason: String+ amount: Money!+}++type OrderDiscountAdd {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderErrors: [OrderError!]!+}++input OrderDiscountCommonInput {+ valueType: DiscountValueTypeEnum!+ value: PositiveDecimal!+ reason: String+}++type OrderDiscountDelete {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderErrors: [OrderError!]!+}++enum OrderDiscountType {+ VOUCHER+ MANUAL+}++type OrderDiscountUpdate {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ order: Order+ orderErrors: [OrderError!]!+}+input OrderDraftFilterInput {customer: Stringcreated: DateRangeInput@@ -2991,6 +3038,7 @@ enum OrderErrorCode {CANNOT_CANCEL_FULFILLMENTCANNOT_CANCEL_ORDERCANNOT_DELETE+ CANNOT_DISCOUNTCANNOT_REFUNDCAPTURE_INACTIVE_PAYMENTNOT_EDITABLE@@ -3039,6 +3087,7 @@ type OrderEvent implements Node {transactionReference: StringshippingCostsIncluded: BooleanrelatedOrder: Order+ discount: OrderEventDiscountObject}type OrderEventCountableConnection {@@ -3052,10 +3101,21 @@ type OrderEventCountableEdge {cursor: String!}+type OrderEventDiscountObject {+ valueType: DiscountValueTypeEnum!+ value: PositiveDecimal!+ reason: String+ amount: Money+ oldValueType: DiscountValueTypeEnum+ oldValue: PositiveDecimal+ oldAmount: Money+}+type OrderEventOrderLineObject {quantity: IntorderLine: OrderLineitemName: String+ discount: OrderEventDiscountObject}enum OrderEventsEmailsEnum {@@ -3082,6 +3142,12 @@ enum OrderEventsEnum {ORDER_MARKED_AS_PAIDORDER_FULLY_PAIDORDER_REPLACEMENT_CREATED+ ORDER_DISCOUNT_ADDED+ ORDER_DISCOUNT_AUTOMATICALLY_UPDATED+ ORDER_DISCOUNT_UPDATED+ ORDER_DISCOUNT_DELETED+ ORDER_LINE_DISCOUNT_UPDATED+ ORDER_LINE_DISCOUNT_REMOVEDUPDATED_ADDRESSEMAIL_SENTCONFIRMED@@ -3145,15 +3211,20 @@ type OrderLine implements Node {isShippingRequired: Boolean!quantity: Int!quantityFulfilled: Int!+ unitDiscountReason: StringtaxRate: Float!digitalContentUrl: DigitalContentUrlthumbnail(size: Int): ImageunitPrice: TaxedMoney!+ undiscountedUnitPrice: TaxedMoney!+ unitDiscount: Money!+ unitDiscountValue: PositiveDecimal!totalPrice: TaxedMoney!variant: ProductVarianttranslatedProductName: String!translatedVariantName: String!allocations: [Allocation!]+ unitDiscountType: DiscountValueTypeEnum}input OrderLineCreateInput {@@ -3161,6 +3232,20 @@ input OrderLineCreateInput {variantId: ID!}+type OrderLineDiscountRemove {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ orderLine: OrderLine+ order: Order+ orderErrors: [OrderError!]!+}++type OrderLineDiscountUpdate {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ orderLine: OrderLine+ order: Order+ orderErrors: [OrderError!]!+}+input OrderLineInput {quantity: Int!}diff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex a0fae0557d..d063888acf 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -75,6 +75,13 @@ class OrderEvents:ORDER_FULLY_PAID = "order_fully_paid"ORDER_REPLACEMENT_CREATED = "order_replacement_created"+ ORDER_DISCOUNT_ADDED = "order_discount_added"+ ORDER_DISCOUNT_AUTOMATICALLY_UPDATED = "order_discount_automatically_updated"+ ORDER_DISCOUNT_UPDATED = "order_discount_updated"+ ORDER_DISCOUNT_DELETED = "order_discount_deleted"+ ORDER_LINE_DISCOUNT_UPDATED = "order_line_discount_updated"+ ORDER_LINE_DISCOUNT_REMOVED = "order_line_discount_removed"+UPDATED_ADDRESS = "updated_address"EMAIL_SENT = "email_sent"@@ -115,6 +122,15 @@ class OrderEvents:(ORDER_MARKED_AS_PAID, "The order was manually marked as fully paid"),(ORDER_FULLY_PAID, "The order was fully paid"),(ORDER_REPLACEMENT_CREATED, "The draft order was created based on this order."),+ (ORDER_DISCOUNT_ADDED, "New order discount applied to this order."),+ (+ ORDER_DISCOUNT_AUTOMATICALLY_UPDATED,+ "Order discount was automatically updated after the changes in order.",+ ),+ (ORDER_DISCOUNT_UPDATED, "Order discount was updated for this order."),+ (ORDER_DISCOUNT_DELETED, "Order discount was deleted for this order."),+ (ORDER_LINE_DISCOUNT_UPDATED, "Order line was discounted."),+ (ORDER_LINE_DISCOUNT_REMOVED, "The discount for order line was removed."),(UPDATED_ADDRESS, "The address from the placed order was updated"),(EMAIL_SENT, "The email was sent"),(CONFIRMED, "Order was confirmed"),diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.pyindex 442d84dc24..51b521a850 100644--- a/saleor/order/error_codes.py+++ b/saleor/order/error_codes.py@@ -6,6 +6,7 @@ class OrderErrorCode(Enum):CANNOT_CANCEL_FULFILLMENT = "cannot_cancel_fulfillment"CANNOT_CANCEL_ORDER = "cannot_cancel_order"CANNOT_DELETE = "cannot_delete"+ CANNOT_DISCOUNT = "cannot_discount"CANNOT_REFUND = "cannot_refund"CAPTURE_INACTIVE_PAYMENT = "capture_inactive_payment"NOT_EDITABLE = "not_editable"diff --git a/saleor/order/events.py b/saleor/order/events.pyindex 8bfe42a08d..9ee67150d3 100644--- a/saleor/order/events.py+++ b/saleor/order/events.py@@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Tuple, Unionfrom ..account import events as account_eventsfrom ..account.models import User+from ..discount.models import OrderDiscountfrom ..order.models import Fulfillment, FulfillmentLine, Order, OrderLinefrom ..payment.models import Paymentfrom . import OrderEvents, OrderEventsEmails@@ -11,9 +12,13 @@ from .models import OrderEventUserType = Optional[User]+def _line_per_quantity_to_line_object(quantity, line):+ return {"quantity": quantity, "line_pk": line.pk, "item": str(line)}++def _lines_per_quantity_to_line_object_list(quantities_per_order_line):return [- {"quantity": quantity, "line_pk": line.pk, "item": str(line)}+ _line_per_quantity_to_line_object(quantity, line)for quantity, line in quantities_per_order_line]@@ -469,3 +474,165 @@ def order_note_added_event(*, order: Order, user: UserType, message: str) -> Ordparameters={"message": message},**kwargs,)+++def _prepare_discount_object(+ order_discount: "OrderDiscount",+ old_order_discount: Optional["OrderDiscount"] = None,+):+ discount_parameters = {+ "value": order_discount.value,+ "amount_value": order_discount.amount_value,+ "currency": order_discount.currency,+ "value_type": order_discount.value_type,+ "reason": order_discount.reason,+ }+ if old_order_discount:+ discount_parameters["old_value"] = old_order_discount.value+ discount_parameters["old_value_type"] = old_order_discount.value_type+ discount_parameters["old_amount_value"] = old_order_discount.amount_value+ return discount_parameters+++def order_discount_event(+ *,+ event_type: str,+ order: Order,+ user: UserType,+ order_discount: "OrderDiscount",+ old_order_discount: Optional["OrderDiscount"] = None+) -> OrderEvent:+ if not _user_is_valid(user):+ user = None+ discount_parameters = _prepare_discount_object(order_discount, old_order_discount)++ return OrderEvent.objects.create(+ order=order,+ type=event_type,+ user=user,+ parameters={"discount": discount_parameters},+ )+++def order_discounts_automatically_updated_event(+ order: Order, changed_order_discounts: List[Tuple["OrderDiscount", "OrderDiscount"]]+):+ for previous_order_discount, current_order_discount in changed_order_discounts:+ order_discount_automatically_updated_event(+ order=order,+ order_discount=current_order_discount,+ old_order_discount=previous_order_discount,+ )+++def order_discount_automatically_updated_event(+ order: Order, order_discount: "OrderDiscount", old_order_discount: "OrderDiscount"+):+ return order_discount_event(+ event_type=OrderEvents.ORDER_DISCOUNT_AUTOMATICALLY_UPDATED,+ order=order,+ user=None,+ order_discount=order_discount,+ old_order_discount=old_order_discount,+ )+++def order_discount_added_event(+ order: Order, user: UserType, order_discount: "OrderDiscount"+) -> OrderEvent:+ return order_discount_event(+ event_type=OrderEvents.ORDER_DISCOUNT_ADDED,+ order=order,+ user=user,+ order_discount=order_discount,+ )+++def order_discount_updated_event(+ order: Order,+ user: UserType,+ order_discount: "OrderDiscount",+ old_order_discount: Optional["OrderDiscount"] = None,+) -> OrderEvent:+ return order_discount_event(+ event_type=OrderEvents.ORDER_DISCOUNT_UPDATED,+ order=order,+ user=user,+ order_discount=order_discount,+ old_order_discount=old_order_discount,+ )+++def order_discount_deleted_event(+ order: Order,+ user: UserType,+ order_discount: "OrderDiscount",+) -> OrderEvent:+ return order_discount_event(+ event_type=OrderEvents.ORDER_DISCOUNT_DELETED,+ order=order,+ user=user,+ order_discount=order_discount,+ )+++def order_line_discount_event(+ *,+ event_type: str,+ order: Order,+ user: UserType,+ line: OrderLine,+ line_before_update: Optional["OrderLine"] = None+) -> OrderEvent:+ if not _user_is_valid(user):+ user = None+ discount_parameters = {+ "value": line.unit_discount_value,+ "amount_value": line.unit_discount_amount,+ "currency": line.currency,+ "value_type": line.unit_discount_type,+ "reason": line.unit_discount_reason,+ }+ if line_before_update:+ discount_parameters["old_value"] = line_before_update.unit_discount_value+ discount_parameters["old_value_type"] = line_before_update.unit_discount_type+ discount_parameters[+ "old_amount_value"+ ] = line_before_update.unit_discount_amount++ line_data = _line_per_quantity_to_line_object(line.quantity, line)+ line_data["discount"] = discount_parameters+ return OrderEvent.objects.create(+ order=order,+ type=event_type,+ user=user,+ parameters={"lines": [line_data]},+ )+++def order_line_discount_updated_event(+ order: Order,+ user: UserType,+ line: OrderLine,+ line_before_update: Optional["OrderLine"] = None,+) -> OrderEvent:+ return order_line_discount_event(+ event_type=OrderEvents.ORDER_LINE_DISCOUNT_UPDATED,+ order=order,+ line=line,+ line_before_update=line_before_update,+ user=user,+ )+++def order_line_discount_removed_event(+ order: Order,+ user: UserType,+ line: OrderLine,+) -> OrderEvent:+ return order_line_discount_event(+ event_type=OrderEvents.ORDER_LINE_DISCOUNT_REMOVED,+ order=order,+ line=line,+ user=user,+ )diff --git a/saleor/order/migrations/0098_discounts_relation.py b/saleor/order/migrations/0098_discounts_relation.pynew file mode 100644index 0000000000..8f20126ca7--- /dev/null+++ b/saleor/order/migrations/0098_discounts_relation.py@@ -0,0 +1,73 @@+from django.db import migrations, models+from django.db.models import F+++def calculate_undiscounted_total_values(apps, *_args, **_kwargs):+ Order = apps.get_model("order", "Order")+ Order.objects.update(+ undiscounted_total_gross_amount=F("total_gross_amount") + F("discount_amount")+ )+ Order.objects.update(+ undiscounted_total_net_amount=F("total_net_amount") + F("discount_amount")+ )+++def create_order_discount_relations(apps, *_args, **_kwargs):+ Order = apps.get_model("order", "Order")+ orders_with_discount = Order.objects.exclude(discount_amount=0.0)+ for order in orders_with_discount.iterator():+ order.discounts.create(+ value_type="fixed",+ value=order.discount_amount,+ amount_value=order.discount_amount,+ name=order.discount_name,+ type="voucher",+ translated_name=order.translated_discount_name,+ )+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0097_auto_20210107_1148"),+ ("discount", "0024_orderdiscount"),+ ]++ operations = [+ migrations.AddField(+ model_name="order",+ name="undiscounted_total_gross_amount",+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),+ ),+ migrations.AddField(+ model_name="order",+ name="undiscounted_total_net_amount",+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),+ ),+ migrations.AddField(+ model_name="orderline",+ name="unit_discount_amount",+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),+ ),+ migrations.AddField(+ model_name="orderline",+ name="unit_discount_value",+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),+ ),+ migrations.AddField(+ model_name="orderline",+ name="unit_discount_reason",+ field=models.TextField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="orderline",+ name="unit_discount_type",+ field=models.CharField(+ choices=[("fixed", "fixed"), ("percentage", "%")],+ default="fixed",+ max_length=10,+ ),+ ),+ migrations.RunPython(calculate_undiscounted_total_values),+ migrations.RunPython(create_order_discount_relations),+ ]diff --git a/saleor/order/migrations/0099_auto_20210209_0856.py b/saleor/order/migrations/0099_auto_20210209_0856.pynew file mode 100644index 0000000000..a970620277--- /dev/null+++ b/saleor/order/migrations/0099_auto_20210209_0856.py@@ -0,0 +1,25 @@+# Generated by Django 3.1.5 on 2021-02-09 08:56++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0098_discounts_relation"),+ ]++ operations = [+ migrations.RemoveField(+ model_name="order",+ name="discount_amount",+ ),+ migrations.RemoveField(+ model_name="order",+ name="discount_name",+ ),+ migrations.RemoveField(+ model_name="order",+ name="translated_discount_name",+ ),+ ]diff --git a/saleor/order/migrations/0100_auto_20210216_0914.py b/saleor/order/migrations/0100_auto_20210216_0914.pynew file mode 100644index 0000000000..2f13130053--- /dev/null+++ b/saleor/order/migrations/0100_auto_20210216_0914.py@@ -0,0 +1,64 @@+# Generated by Django 3.1.5 on 2021-02-16 09:14++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0099_auto_20210209_0856"),+ ]++ operations = [+ migrations.AlterField(+ model_name="orderevent",+ name="type",+ field=models.CharField(+ choices=[+ ("DRAFT_CREATED", "draft_created"),+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),+ ("DRAFT_ADDED_PRODUCTS", "draft_added_products"),+ ("DRAFT_REMOVED_PRODUCTS", "draft_removed_products"),+ ("PLACED", "placed"),+ ("PLACED_FROM_DRAFT", "placed_from_draft"),+ ("OVERSOLD_ITEMS", "oversold_items"),+ ("CANCELED", "canceled"),+ ("ORDER_MARKED_AS_PAID", "order_marked_as_paid"),+ ("ORDER_FULLY_PAID", "order_fully_paid"),+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),+ ("ORDER_DISCOUNT_ADDED", "order_discount_added"),+ (+ "ORDER_DISCOUNT_AUTOMATICALLY_UPDATED",+ "order_discount_automatically_updated",+ ),+ ("ORDER_DISCOUNT_UPDATED", "order_discount_updated"),+ ("ORDER_DISCOUNT_DELETED", "order_discount_deleted"),+ ("ORDER_LINE_DISCOUNT_UPDATED", "order_line_discount_updated"),+ ("ORDER_LINE_DISCOUNT_REMOVED", "order_line_discount_removed"),+ ("UPDATED_ADDRESS", "updated_address"),+ ("EMAIL_SENT", "email_sent"),+ ("CONFIRMED", "confirmed"),+ ("PAYMENT_AUTHORIZED", "payment_authorized"),+ ("PAYMENT_CAPTURED", "payment_captured"),+ ("EXTERNAL_SERVICE_NOTIFICATION", "external_service_notification"),+ ("PAYMENT_REFUNDED", "payment_refunded"),+ ("PAYMENT_VOIDED", "payment_voided"),+ ("PAYMENT_FAILED", "payment_failed"),+ ("INVOICE_REQUESTED", "invoice_requested"),+ ("INVOICE_GENERATED", "invoice_generated"),+ ("INVOICE_UPDATED", "invoice_updated"),+ ("INVOICE_SENT", "invoice_sent"),+ ("FULFILLMENT_CANCELED", "fulfillment_canceled"),+ ("FULFILLMENT_RESTOCKED_ITEMS", "fulfillment_restocked_items"),+ ("FULFILLMENT_FULFILLED_ITEMS", "fulfillment_fulfilled_items"),+ ("FULFILLMENT_REFUNDED", "fulfillment_refunded"),+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),+ ("TRACKING_UPDATED", "tracking_updated"),+ ("NOTE_ADDED", "note_added"),+ ("OTHER", "other"),+ ],+ max_length=255,+ ),+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 640e86bfa5..9ad3767289 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -13,7 +13,7 @@ from django.utils.timezone import nowfrom django_measurement.models import MeasurementFieldfrom django_prices.models import MoneyField, TaxedMoneyFieldfrom measurement.measures import Weight-from prices import Money+from prices import Money, TaxedMoneyfrom ..account.models import Addressfrom ..channel.models import Channel@@ -22,6 +22,7 @@ from ..core.permissions import OrderPermissionsfrom ..core.taxes import zero_money, zero_taxed_moneyfrom ..core.utils.json_serializer import CustomJsonEncoderfrom ..core.weight import WeightUnits, zero_weight+from ..discount import DiscountValueTypefrom ..discount.models import Voucherfrom ..giftcard.models import GiftCardfrom ..payment import ChargeStatus, TransactionKind@@ -154,35 +155,51 @@ class Order(ModelWithMetadata):decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=0,)+ undiscounted_total_net_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )+total_net = MoneyField(amount_field="total_net_amount", currency_field="currency")+ undiscounted_total_net = MoneyField(+ amount_field="undiscounted_total_net_amount", currency_field="currency"+ )total_gross_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=0,)+ undiscounted_total_gross_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )+total_gross = MoneyField(amount_field="total_gross_amount", currency_field="currency")+ undiscounted_total_gross = MoneyField(+ amount_field="undiscounted_total_gross_amount", currency_field="currency"+ )total = TaxedMoneyField(net_amount_field="total_net_amount",gross_amount_field="total_gross_amount",currency_field="currency",)+ undiscounted_total = TaxedMoneyField(+ net_amount_field="undiscounted_total_net_amount",+ gross_amount_field="undiscounted_total_gross_amount",+ currency_field="currency",+ )voucher = models.ForeignKey(Voucher, blank=True, null=True, related_name="+", on_delete=models.SET_NULL)gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="orders")- discount_amount = models.DecimalField(- max_digits=settings.DEFAULT_MAX_DIGITS,- decimal_places=settings.DEFAULT_DECIMAL_PLACES,- default=0,- )- discount = MoneyField(amount_field="discount_amount", currency_field="currency")- discount_name = models.CharField(max_length=255, blank=True, null=True)- translated_discount_name = models.CharField(max_length=255, blank=True, null=True)+display_gross_prices = models.BooleanField(default=True)customer_note = models.TextField(blank=True, default="")weight = MeasurementField(@@ -391,10 +408,31 @@ class OrderLine(models.Model):max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)+ unit_discount_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )+ unit_discount = MoneyField(+ amount_field="unit_discount_amount", currency_field="currency"+ )+ unit_discount_type = models.CharField(+ max_length=10,+ choices=DiscountValueType.CHOICES,+ default=DiscountValueType.FIXED,+ )+ unit_discount_reason = models.TextField(blank=True, null=True)+unit_price_net_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,)+ # stores the value of the applied discount. Like 20 of %+ unit_discount_value = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )unit_price_net = MoneyField(amount_field="unit_price_net_amount", currency_field="currency")@@ -453,6 +491,10 @@ class OrderLine(models.Model):else self.product_name)+ @property+ def undiscounted_unit_price(self) -> "TaxedMoney":+ return self.unit_price + self.unit_discount+@propertydef quantity_unfulfilled(self):return self.quantity - self.quantity_fulfilleddiff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 194f88aa03..92dc44ea0f 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -5,6 +5,7 @@ import pytestfrom prices import Money, TaxedMoneyfrom ...core.weight import zero_weight+from ...discount import OrderDiscountTypefrom ...discount.models import (DiscountValueType,NotApplicable,@@ -15,6 +16,7 @@ from ...discount.models import (from ...discount.utils import validate_voucher_in_orderfrom ...payment import ChargeStatusfrom ...payment.models import Payment+from ...plugins.manager import get_plugins_managerfrom ...product.models import Collectionfrom ...warehouse.models import Stockfrom ...warehouse.tests.utils import get_quantity_allocated_for_stock@@ -48,12 +50,17 @@ def test_total_setter():def test_order_get_subtotal(order_with_lines):- order_with_lines.discount_name = "Test discount"- order_with_lines.discount = order_with_lines.total.gross * Decimal("0.5")+ order_with_lines.discounts.create(+ type=OrderDiscountType.VOUCHER,+ value_type=DiscountValueType.FIXED,+ value=order_with_lines.total.gross.amount * Decimal("0.5"),+ amount_value=order_with_lines.total.gross.amount * Decimal("0.5"),+ name="Test discount",+ )+recalculate_order(order_with_lines)target_subtotal = order_with_lines.total - order_with_lines.shipping_price- target_subtotal += order_with_lines.discountassert order_with_lines.get_subtotal() == target_subtotal@@ -448,7 +455,11 @@ def test_queryset_ready_to_capture(channel_USD):assert OrderStatus.CANCELED not in statuses-def test_update_order_prices(order_with_lines):+@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")+def test_update_order_prices(+ mocked_calculate_order_line_unit, order_with_lines, site_settings+):+ manager = get_plugins_manager()channel = order_with_lines.channeladdress = order_with_lines.shipping_addressaddress.country = "DE"@@ -472,12 +483,14 @@ def test_update_order_prices(order_with_lines):)price_2 = TaxedMoney(net=price_2, gross=price_2)+ mocked_calculate_order_line_unit.side_effect = [price_1, price_2]+shipping_price = order_with_lines.shipping_method.channel_listings.get(channel_id=order_with_lines.channel_id).priceshipping_price = TaxedMoney(net=shipping_price, gross=shipping_price)- update_order_prices(order_with_lines, None)+ update_order_prices(order_with_lines, manager, site_settings)line_1.refresh_from_db()line_2.refresh_from_db()@@ -489,7 +502,9 @@ def test_update_order_prices(order_with_lines):assert order_with_lines.total == total-def test_update_order_prices_tax_included(order_with_lines, vatlayer):+def test_update_order_prices_tax_included(order_with_lines, vatlayer, site_settings):+ manager = get_plugins_manager()+channel = order_with_lines.channeladdress = order_with_lines.shipping_addressaddress.country = "DE"@@ -502,6 +517,8 @@ def test_update_order_prices_tax_included(order_with_lines, vatlayer):price_1 = variant_1.get_price(product_1, [], channel, variant_channel_listing_1, None)+ line_1.unit_price_gross = price_1+ line_1.save()line_2 = order_with_lines.lines.last()variant_2 = line_2.variant@@ -510,12 +527,14 @@ def test_update_order_prices_tax_included(order_with_lines, vatlayer):price_2 = variant_2.get_price(product_2, [], channel, variant_channel_listing_2, None)+ line_2.unit_price_gross = price_2+ line_2.save()shipping_price = order_with_lines.shipping_method.channel_listings.get(channel_id=order_with_lines.channel_id).price- update_order_prices(order_with_lines, None)+ update_order_prices(order_with_lines, manager, site_settings)line_1.refresh_from_db()line_2.refresh_from_db()diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 9f3c502633..7e8abd1433 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -1,16 +1,18 @@+import copyfrom decimal import Decimal-from functools import wraps-from typing import Iterable, List+from functools import partial, wraps+from typing import Iterable, List, Optional, Tuple, Unionfrom django.conf import settingsfrom django.db import transactionfrom django.utils import timezone-from prices import Money, TaxedMoney+from prices import Money, TaxedMoney, fixed_discount, percentage_discountfrom ..account.models import Userfrom ..core.taxes import zero_moneyfrom ..core.weight import zero_weight-from ..discount.models import NotApplicable, Voucher, VoucherType+from ..discount import DiscountValueType, OrderDiscountType+from ..discount.models import NotApplicable, OrderDiscount, Voucher, VoucherTypefrom ..discount.utils import get_products_voucher_discount, validate_voucher_in_orderfrom ..order import FulfillmentStatus, OrderLineData, OrderStatusfrom ..order.models import Order, OrderLine@@ -65,13 +67,78 @@ def update_voucher_discount(func):discount = get_voucher_discount_for_order(order)except NotApplicable:discount = zero_money(order.currency)- order.discount = discount- return func(*args, **kwargs)+ return func(*args, **kwargs, discount=discount)return decorator+def get_voucher_discount_assigned_to_order(order: Order):+ return order.discounts.filter(type=OrderDiscountType.VOUCHER).first()+++def recalculate_order_discounts(+ order: Order,+) -> List[Tuple[OrderDiscount, OrderDiscount]]:+ """Recalculate all order discounts assigned to order.++ It returns the list of tuples which contains order discounts where the amount has+ been changed.+ """++ changed_order_discounts = []+ order_discounts = order.discounts.filter(type=OrderDiscountType.MANUAL)+ for order_discount in order_discounts:+ previous_order_discount = copy.deepcopy(order_discount)+ current_total = order.total.gross.amount++ update_order_discount_for_order(+ order,+ order_discount,+ )+ discount_value = order_discount.value+ discount_type = order_discount.value_type+ amount = order_discount.amount++ if (+ (+ discount_type == DiscountValueType.PERCENTAGE+ or current_total < discount_value+ )+ # No need to add new event when new and old amount of discount is the same+ and amount != previous_order_discount.amount+ ):+ changed_order_discounts.append(+ # order discount before changes, order discount after update+ (previous_order_discount, order_discount)+ )+ return changed_order_discounts++@update_voucher_discount+def recalculate_order_prices(order: Order, **kwargs):+ # avoid using prefetched order lines+ lines = OrderLine.objects.filter(order_id=order.pk)+ prices = [line.total_price for line in lines]+ total = sum(prices, order.shipping_price)+ undiscounted_total = TaxedMoney(total.net, total.gross)++ voucher_discount = kwargs.get("discount", zero_money(order.currency))++ # discount amount can't be greater than order total+ voucher_discount = min(voucher_discount, total.gross)+ total -= voucher_discount++ order.total = total+ order.undiscounted_total = undiscounted_total++ if voucher_discount:+ assigned_order_discount = get_voucher_discount_assigned_to_order(order)+ if assigned_order_discount:+ assigned_order_discount.amount_value = voucher_discount.amount+ assigned_order_discount.value = voucher_discount.amount+ assigned_order_discount.save(update_fields=["value", "amount_value"])++def recalculate_order(order: Order, **kwargs):"""Recalculate and assign total price of order.@@ -81,20 +148,18 @@ def recalculate_order(order: Order, **kwargs):Voucher discount amount is recalculated by default. To avoid this, passupdate_voucher_discount argument set to False."""- # avoid using prefetched order lines- lines = [OrderLine.objects.get(pk=line.pk) for line in order]- prices = [line.total_price for line in lines]- total = sum(prices, order.shipping_price)- # discount amount can't be greater than order total- order.discount_amount = min(order.discount_amount, total.gross.amount)- if order.discount:- total -= order.discount- order.total = total++ recalculate_order_prices(order, **kwargs)++ changed_order_discounts = recalculate_order_discounts(order)+ events.order_discounts_automatically_updated_event(order, changed_order_discounts)+order.save(update_fields=[- "discount_amount","total_net_amount","total_gross_amount",+ "undiscounted_total_net_amount",+ "undiscounted_total_gross_amount","currency",])@@ -111,37 +176,43 @@ def recalculate_order_weight(order):order.save(update_fields=["weight"])-def update_order_prices(order, discounts):+def update_taxes_for_order_line(+ line: "OrderLine", order: "Order", manager, tax_included+):+ variant = line.variant+ product = variant.product # type: ignore++ line_price = line.unit_price.gross if tax_included else line.unit_price.net+ line.unit_price = TaxedMoney(line_price, line_price)++ price = manager.calculate_order_line_unit(order, line, variant, product)+ line.unit_price = price+ line.total_price = line.unit_price * line.quantity+ if price.tax and price.net:+ line.tax_rate = manager.get_order_line_tax_rate(order, product, None, price)+++def update_taxes_for_order_lines(+ lines: List[OrderLine], order: "Order", manager, tax_included+):+ for line in lines:+ update_taxes_for_order_line(line, order, manager, tax_included=tax_included)+ OrderLine.objects.bulk_update(+ lines,+ [+ "tax_rate",+ "unit_price_net_amount",+ "unit_price_gross_amount",+ "total_price_net_amount",+ "total_price_gross_amount",+ ],+ )+++def update_order_prices(order, manager, tax_included):"""Update prices in order with given discounts and proper taxes."""- manager = get_plugins_manager()- channel = order.channel- for line in order: # type: OrderLine- if line.variant:- variant = line.variant- product = variant.product- channel_listing = line.variant.channel_listings.get(channel=channel)- collections = product.collections.all()- unit_price = line.variant.get_price(- product, collections, channel, channel_listing, discounts- )- unit_price = TaxedMoney(unit_price, unit_price)- line.unit_price = unit_price- line.save(- update_fields=[- "currency",- "unit_price_net_amount",- "unit_price_gross_amount",- ]- )- price = manager.calculate_order_line_unit(order, line, variant, product)- if price != line.unit_price:- line.unit_price = price- if price.tax and price.net:- line.tax_rate = manager.get_order_line_tax_rate(- order, product, None, price- )- line.save()+ update_taxes_for_order_lines(order.lines.all(), order, manager, tax_included)if order.shipping_method:shipping_price = manager.calculate_order_shipping(order)@@ -468,3 +539,207 @@ def get_voucher_discount_for_order(order: Order) -> Money:def match_orders_with_new_user(user: User) -> None:Order.objects.confirmed().filter(user_email=user.email, user=None).update(user=user)+++def get_total_order_discount(order: Order) -> Money:+ """Return total order discount assigned to the order."""+ all_discounts = order.discounts.all()+ total_order_discount = Money(+ sum([discount.amount_value for discount in all_discounts]),+ currency=order.currency,+ )+ total_order_discount = min(total_order_discount, order.undiscounted_total_gross)+ return total_order_discount+++def get_order_discounts(order: Order) -> List[OrderDiscount]:+ """Return all discounts applied to the order by staff user."""+ return list(order.discounts.filter(type=OrderDiscountType.MANUAL))+++def apply_discount_to_value(+ value: Decimal,+ value_type: str,+ currency: str,+ price_to_discount: Union[Money, TaxedMoney],+):+ """Calculate the price based on the provided values."""+ if value_type == DiscountValueType.FIXED:+ discount_method = fixed_discount+ discount_kwargs = {"discount": Money(value, currency)}+ else:+ discount_method = percentage_discount+ discount_kwargs = {"percentage": value}+ discount = partial(+ discount_method,+ **discount_kwargs,+ )+ return discount(price_to_discount)+++def create_order_discount_for_order(+ order: Order, reason: str, value_type: str, value: Decimal+):+ """Add new order discount and update the prices."""++ current_total = order.total+ currency = order.currency++ net_total = apply_discount_to_value(value, value_type, currency, current_total.net)+ gross_total = apply_discount_to_value(+ value, value_type, currency, current_total.gross+ )++ new_amount = (current_total - gross_total).gross++ order_discount = order.discounts.create(+ value_type=value_type,+ value=value,+ reason=reason,+ amount=new_amount, # type: ignore+ )+ order.total = TaxedMoney(net_total, gross_total)+ order.save(update_fields=["total_net_amount", "total_gross_amount"])+ return order_discount+++def update_order_discount_for_order(+ order: Order,+ order_discount_to_update: OrderDiscount,+ reason: Optional[str] = None,+ value_type: Optional[str] = None,+ value: Optional[Decimal] = None,+):+ """Update the order_discount for an order and recalculate the order's prices."""+ current_value = order_discount_to_update.value+ value = value if value is not None else current_value+ value_type = value_type or order_discount_to_update.value_type+ currency = order_discount_to_update.currency+ fields_to_update = []+ if reason is not None:+ order_discount_to_update.reason = reason+ fields_to_update.append("reason")++ current_total = order.total++ net_total = apply_discount_to_value(value, value_type, currency, current_total.net)+ gross_total = apply_discount_to_value(+ value, value_type, currency, current_total.gross+ )++ new_amount = (current_total - gross_total).gross++ order_discount_to_update.amount = new_amount+ order_discount_to_update.value = value+ order_discount_to_update.value_type = value_type+ fields_to_update.extend(["value_type", "value", "amount_value"])++ order.total = TaxedMoney(net_total, gross_total)++ order_discount_to_update.save(update_fields=fields_to_update)+++def remove_order_discount_from_order(order: Order, order_discount: OrderDiscount):+ """Remove the order discount from order and update the prices."""++ discount_amount = order_discount.amount+ order_discount.delete()++ order.total += discount_amount+ order.save(update_fields=["total_net_amount", "total_gross_amount"])+++def update_discount_for_order_line(+ order_line: OrderLine,+ order: "Order",+ reason: Optional[str],+ value_type: Optional[str],+ value: Optional[Decimal],+ manager,+ tax_included,+):+ """Update discount fields for order line. Apply discount to the price."""+ current_value = order_line.unit_discount_value+ current_value_type = order_line.unit_discount_type+ value = value or current_value+ value_type = value_type or current_value_type+ fields_to_update = []+ if reason is not None:+ order_line.unit_discount_reason = reason+ fields_to_update.append("unit_discount_reason")+ if current_value != value or current_value_type != value_type:+ undiscounted_unit_price = order_line.undiscounted_unit_price+ currency = undiscounted_unit_price.currency+ unit_price_with_discount = apply_discount_to_value(+ value, value_type, currency, undiscounted_unit_price+ )++ order_line.unit_discount = (+ undiscounted_unit_price - unit_price_with_discount+ ).gross++ order_line.unit_price = unit_price_with_discount+ order_line.unit_discount_type = value_type+ order_line.unit_discount_value = value+ order_line.total_price = order_line.unit_price * order_line.quantity+ fields_to_update.extend(+ [+ "tax_rate",+ "unit_discount_value",+ "unit_discount_amount",+ "unit_discount_type",+ "unit_discount_reason",+ "unit_price_gross_amount",+ "unit_price_net_amount",+ "total_price_net_amount",+ "total_price_gross_amount",+ ]+ )++ # Save lines before calculating the taxes as some plugin can fetch all order data+ # from db+ order_line.save(update_fields=fields_to_update)++ update_taxes_for_order_line(order_line, order, manager, tax_included)+ order_line.save(+ update_fields=[+ "unit_price_gross_amount",+ "unit_price_net_amount",+ "total_price_net_amount",+ "total_price_gross_amount",+ "tax_rate",+ ]+ )+++def remove_discount_from_order_line(+ order_line: OrderLine, order: "Order", manager, tax_included+):+ """Drop discount applied to order line. Restore undiscounted price."""+ order_line.unit_price = order_line.undiscounted_unit_price+ order_line.unit_discount_amount = Decimal(0)+ order_line.unit_discount_value = Decimal(0)+ order_line.unit_discount_reason = ""+ order_line.total_price = order_line.unit_price * order_line.quantity+ order_line.save(+ update_fields=[+ "unit_discount_value",+ "unit_discount_amount",+ "unit_discount_reason",+ "unit_price_gross_amount",+ "unit_price_net_amount",+ "total_price_net_amount",+ "total_price_gross_amount",+ ]+ )++ update_taxes_for_order_line(order_line, order, manager, tax_included)+ order_line.save(+ update_fields=[+ "unit_price_gross_amount",+ "unit_price_net_amount",+ "total_price_net_amount",+ "total_price_gross_amount",+ "tax_rate",+ ]+ )diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex c627ac117d..bebfa7ebde 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -15,6 +15,7 @@ from requests.auth import HTTPBasicAuthfrom ...checkout import base_calculationsfrom ...core.taxes import TaxError+from ...order.utils import get_total_order_discountif TYPE_CHECKING:from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo@@ -293,14 +294,16 @@ def get_order_lines_data(name=line.variant.product.name,tax_included=tax_included,)- if order.discount_amount:++ discount_amount = get_total_order_discount(order)+ if discount_amount:append_line_to_data(data=data,quantity=1,- amount=order.discount_amount * -1,+ amount=discount_amount.amount * -1,tax_code=COMMON_DISCOUNT_VOUCHER_CODE,item_code="Voucher",- name=order.discount_name,+ name="Order discount",tax_included=True, # Voucher should be always applied as a gross amount)append_shipping_to_data(data, order.shipping_method, order.channel_id)diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex e84f8a2675..571b4020dc 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -22,7 +22,7 @@ from django.test.utils import CaptureQueriesContext as BaseCaptureQueriesContextfrom django.utils import timezonefrom django_countries import countriesfrom PIL import Image-from prices import Money, TaxedMoney+from prices import Money, TaxedMoney, fixed_discountfrom ..account.models import Address, StaffNotificationRecipient, Userfrom ..app.models import App, AppInstallation@@ -55,7 +55,11 @@ from ..giftcard.models import GiftCardfrom ..menu.models import Menu, MenuItem, MenuItemTranslationfrom ..order import OrderLineData, OrderStatusfrom ..order.actions import cancel_fulfillment, fulfill_order_lines-from ..order.events import OrderEvents+from ..order.events import (+ OrderEvents,+ draft_order_added_products_event,+ fulfillment_refunded_event,+)from ..order.models import FulfillmentStatus, Order, OrderEvent, OrderLinefrom ..order.utils import recalculate_orderfrom ..page.models import Page, PageTranslation, PageType@@ -2265,6 +2269,33 @@ def order_with_lines(return order+def order_with_lines_and_events(order_with_lines, staff_user):+ events = []+ for event_type, _ in OrderEvents.CHOICES:+ events.append(+ OrderEvent(+ type=event_type,+ order=order_with_lines,+ user=staff_user,+ )+ )+ OrderEvent.objects.bulk_create(events)+ fulfillment_refunded_event(+ order=order_with_lines,+ user=staff_user,+ refunded_lines=[(1, order_with_lines.lines.first())],+ amount=Decimal("10.0"),+ shipping_costs_included=False,+ )+ draft_order_added_products_event(+ order=order_with_lines,+ user=staff_user,+ order_lines=[(1, order_with_lines.lines.first())],+ )+ return order_with_lines++@pytest.fixturedef order_with_lines_channel_PLN(customer_user,@@ -2513,6 +2544,22 @@ def draft_order(order_with_lines):return order_with_lines+def draft_order_with_fixed_discount_order(draft_order):+ value = Decimal("20")+ discount = partial(fixed_discount, discount=Money(value, draft_order.currency))+ draft_order.undiscounted_total = draft_order.total+ draft_order.total = discount(draft_order.total)+ draft_order.discounts.create(+ value_type=DiscountValueType.FIXED,+ value=value,+ reason="Discount reason",+ amount=(draft_order.undiscounted_total - draft_order.total).gross, # type: ignore+ )+ draft_order.save()+ return draft_order++@pytest.fixturedef draft_order_without_inventory_tracking(order_with_line_without_inventory_tracking):order_with_line_without_inventory_tracking.status = OrderStatus.DRAFTdiff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 979eee750e..9d5f9dcd6c 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -49,9 +49,6 @@ ORDER_FIELDS = ("total_gross_amount","shipping_price_net_amount","shipping_price_gross_amount",- "discount_amount",- "discount_name",- "translated_discount_name","weight","private_metadata","metadata",@@ -69,6 +66,9 @@ def generate_order_lines_payload(lines: Iterable[OrderLine]):"currency","unit_price_net_amount","unit_price_gross_amount",+ "unit_discount_amount",+ "unit_discount_type",+ "unit_discount_reason","total_price_net_amount","total_price_gross_amount","tax_rate",@@ -111,6 +111,15 @@ def generate_order_payload(order: "Order"):"billing_country_area",)+ discount_fields = (+ "type",+ "value_type",+ "value",+ "amount_value",+ "name",+ "translated_name",+ "reason",+ )shipping_method_fields = ("name", "type", "currency", "price_amount")lines = order.lines.all()order_data = serializer.serialize(@@ -122,6 +131,7 @@ def generate_order_payload(order: "Order"):"shipping_address": (lambda o: o.shipping_address, ADDRESS_FIELDS),"billing_address": (lambda o: o.billing_address, ADDRESS_FIELDS),"fulfillments": (lambda o: o.fulfillments.all(), fulfillment_fields),+ "discounts": (lambda o: o.discounts.all(), discount_fields),},extra_dict_data={"lines": json.loads(generate_order_lines_payload(lines))},)diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 7558772bb0..9e3c0cd48a 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -3,14 +3,28 @@ from decimal import Decimalimport graphene+from ...discount import DiscountValueType, OrderDiscountTypefrom ..payloads import ORDER_FIELDS, generate_order_payloaddef test_generate_order_payload(order_with_lines, fulfilled_order, payment_txn_captured):- order_with_lines.discount_name = "Test discount"- order_with_lines.translated_discount_name = "Translated discount"+ order_with_lines.discounts.create(+ type=OrderDiscountType.MANUAL,+ value_type=DiscountValueType.PERCENTAGE,+ value=Decimal("20"),+ amount_value=Decimal("33.0"),+ reason="Discount from staff",+ )+ order_with_lines.discounts.create(+ type=OrderDiscountType.VOUCHER,+ value_type=DiscountValueType.PERCENTAGE,+ value=Decimal("10"),+ amount_value=Decimal("16.5"),+ name="Voucher",+ )+order_id = graphene.Node.to_global_id("Order", order_with_lines.id)payload = json.loads(generate_order_payload(order_with_lines))[0]@@ -26,11 +40,16 @@ def test_generate_order_payload(assert payload.get("shipping_address")assert payload.get("billing_address")assert payload.get("fulfillments")+ assert payload.get("discounts")def test_order_lines_have_all_required_fields(order, order_line_with_one_allocation):order.lines.add(order_line_with_one_allocation)line = order_line_with_one_allocation+ line.unit_discount_amount = Decimal("10.0")+ line.unit_discount_type = DiscountValueType.FIXED+ line.save()+payload = json.loads(generate_order_payload(order))[0]lines_payload = payload.get("lines")@@ -39,6 +58,8 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocatline_payload = lines_payload[0]unit_net_amount = line.unit_price_net_amount.quantize(Decimal("0.001"))unit_gross_amount = line.unit_price_gross_amount.quantize(Decimal("0.001"))+ unit_discount_amount = line.unit_discount_amount.quantize(Decimal("0.001"))+total_line = line.total_priceassert line_payload == {"id": line_id,@@ -50,6 +71,9 @@ def test_order_lines_have_all_required_fields(order, order_line_with_one_allocat"product_sku": line.product_sku,"quantity": line.quantity,"currency": line.currency,+ "unit_discount_amount": str(unit_discount_amount),+ "unit_discount_type": line.unit_discount_type,+ "unit_discount_reason": line.unit_discount_reason,"unit_price_net_amount": str(unit_net_amount),"unit_price_gross_amount": str(unit_gross_amount),"total_price_net_amount": str(total_line.net.amount.quantize(Decimal("0.001"))),