Skip to content

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

Fix draft order voucher assignment (#14336)

Iga Karbowiak5d5bfa1d93c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc9bb95206..ba8b4903cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
### GraphQL API
+- Fix draft order voucher assignment - #14336 by @IKarbowiak
### Saleor Apps
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 955f7fb510..f91e7addc8 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -422,6 +422,17 @@ class DraftOrderCreate(
# Process addresses
cls._save_addresses(instance, cleaned_input)
+ try:
+ # Process any lines to add
+ cls._save_lines(
+ info, instance, cleaned_input.get("lines_data"), app, manager
+ )
+ except TaxError as tax_error:
+ raise ValidationError(
+ f"Unable to calculate taxes - {str(tax_error)}",
+ code=OrderErrorCode.TAX_ERROR.value,
+ )
+
if "shipping_method" in cleaned_input:
method = cleaned_input["shipping_method"]
if method is None:
@@ -435,22 +446,12 @@ class DraftOrderCreate(
shipping_channel_listing,
)
cls.update_shipping_method(instance, method, shipping_method_data)
+ cls._update_shipping_price(instance, shipping_channel_listing)
updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)
# Save any changes create/update the draft
cls._commit_changes(info, instance, cleaned_input, is_new_instance, app)
- try:
- # Process any lines to add
- cls._save_lines(
- info, instance, cleaned_input.get("lines_data"), app, manager
- )
- except TaxError as tax_error:
- raise ValidationError(
- f"Unable to calculate taxes - {str(tax_error)}",
- code=OrderErrorCode.TAX_ERROR.value,
- )
-
update_order_display_gross_prices(instance)
if is_new_instance:
@@ -470,10 +471,7 @@ class DraftOrderCreate(
)
if cls.should_invalidate_prices(instance, cleaned_input, is_new_instance):
invalidate_order_prices(instance)
- cls._update_shipping_price(instance, shipping_channel_listing)
- updated_fields.extend(
- ["should_refresh_prices", "base_shipping_price_amount"]
- )
+ updated_fields.extend(["should_refresh_prices"])
recalculate_order_weight(instance)
update_order_search_vector(instance, save=False)
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
index e80fdfc442..d835ff6599 100644
--- a/saleor/graphql/order/mutations/draft_order_update.py
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -53,12 +53,13 @@ class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
@classmethod
def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
return any(
- cleaned_input.get(field) is not None
+ field in cleaned_input
for field in [
"shipping_address",
"billing_address",
"shipping_method",
"lines",
+ "voucher",
]
)
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_create.py b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
index 12a2df79d7..679b0f6c3b 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -9,6 +9,7 @@ from prices import Money
from .....checkout import AddressType
from .....core.taxes import TaxError, zero_taxed_money
+from .....discount import DiscountType, DiscountValueType
from .....discount.models import VoucherChannelListing
from .....order import OrderStatus
from .....order import events as order_events
@@ -136,20 +137,28 @@ def test_draft_order_create(
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ channel_listing_0 = variant_0.channel_listings.get(channel=channel_USD)
+ variant_0_qty = 2
+
variant_1 = product_without_shipping.variants.first()
- variant_1.quantity = 2
- variant_1.save()
+ variant_1_qty = 1
+ channel_listing_1 = variant_1.channel_listings.get(channel=channel_USD)
+
variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
discount = "10"
customer_note = "Test note"
variant_list = [
- {"variantId": variant_0_id, "quantity": 2},
- {"variantId": variant_1_id, "quantity": 1},
+ {"variantId": variant_0_id, "quantity": variant_0_qty},
+ {"variantId": variant_1_id, "quantity": variant_1_qty},
]
shipping_address = graphql_address_data
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_listing = voucher.channel_listings.get(channel=channel_USD)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ voucher_listing = voucher.channel_listings.get(channel=channel_USD)
+
redirect_url = "https://www.example.com"
external_reference = "test-ext-ref"
@@ -189,6 +198,18 @@ def test_draft_order_create(
)
assert data["billingAddress"]["metadata"] == graphql_address_data["metadata"]
assert data["shippingAddress"]["metadata"] == graphql_address_data["metadata"]
+ shipping_total = shipping_method.channel_listings.get(
+ channel=channel_USD
+ ).get_total()
+ order_total = (
+ channel_listing_0.discounted_price_amount * variant_0_qty
+ + channel_listing_1.discounted_price_amount * variant_1_qty
+ + shipping_total.amount
+ )
+ assert data["undiscountedTotal"]["gross"]["amount"] == order_total
+ assert (
+ data["total"]["gross"]["amount"] == order_total - voucher_listing.discount_value
+ )
order = Order.objects.first()
assert order.user == customer_user
@@ -229,6 +250,15 @@ def test_draft_order_create(
assert event_parameters["lines"][1]["line_pk"] == str(order_lines[1].pk)
assert event_parameters["lines"][1]["quantity"] == 1
+ # Ensure order discount object was properly created
+ assert order.discounts.count() == 1
+ order_discount = order.discounts.first()
+ assert order_discount.voucher == voucher
+ assert order_discount.type == DiscountType.VOUCHER
+ assert order_discount.value_type == DiscountValueType.FIXED
+ assert order_discount.value == voucher_listing.discount_value
+ assert order_discount.amount_value == voucher_listing.discount_value
+
def test_draft_order_create_by_user_no_channel_access(
staff_api_client,
@@ -453,7 +483,9 @@ def test_draft_order_create_with_inactive_channel(
user_id = graphene.Node.to_global_id("User", customer_user.id)
channel_USD.is_active = False
channel_USD.save()
+
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+
variant_1 = product_without_shipping.variants.first()
variant_1.quantity = 2
variant_1.save()
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_update.py b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
index 84f0d6c270..41e3b2199f 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -3,6 +3,7 @@ from prices import TaxedMoney
from .....core.prices import quantize_price
from .....core.taxes import zero_money
+from .....discount import DiscountType, DiscountValueType
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
@@ -28,6 +29,16 @@ DRAFT_ORDER_UPDATE_MUTATION = """
channel {
id
}
+ total {
+ net {
+ amount
+ }
+ }
+ undiscountedTotal {
+ net {
+ amount
+ }
+ }
billingAddress{
city
streetAddress1
@@ -111,6 +122,7 @@ def test_draft_order_update(
voucher,
graphql_address_data,
):
+ # given
order = draft_order
assert not order.voucher
assert not order.customer_note
@@ -118,8 +130,11 @@ def test_draft_order_update(
query = DRAFT_ORDER_UPDATE_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
customer_note = "Test customer note"
external_reference = "test-ext-ref"
+ order_total = order.total_net_amount
+
variables = {
"id": order_id,
"input": {
@@ -131,7 +146,10 @@ def test_draft_order_update(
},
}
+ # when
response = staff_api_client.post_graphql(query, variables)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["draftOrderUpdate"]
stored_metadata = {"public": "public_value"}
@@ -142,6 +160,11 @@ def test_draft_order_update(
assert (
data["order"]["shippingAddress"]["metadata"] == graphql_address_data["metadata"]
)
+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total
+ assert (
+ data["order"]["total"]["net"]["amount"]
+ == order_total - voucher_listing.discount_value
+ )
assert not data["errors"]
order.refresh_from_db()
@@ -156,6 +179,69 @@ def test_draft_order_update(
== order.external_reference
)
+ # Ensure order discount object was properly created
+ assert order.discounts.count() == 1
+ order_discount = order.discounts.first()
+ assert order_discount.voucher == voucher
+ assert order_discount.type == DiscountType.VOUCHER
+ assert order_discount.value_type == DiscountValueType.FIXED
+ assert order_discount.value == voucher_listing.discount_value
+ assert order_discount.amount_value == voucher_listing.discount_value
+
+
+def test_draft_order_update_clear_voucher(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+ graphql_address_data,
+):
+ # given
+ order = draft_order
+ order.voucher = voucher
+ order.save(update_fields=["voucher"])
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = voucher_listing.discount_value
+ order.discounts.create(
+ voucher=voucher,
+ value=discount_amount,
+ type=DiscountType.VOUCHER,
+ )
+
+ order.total_gross_amount -= discount_amount
+ order.total_net_amount -= discount_amount
+ order.save(update_fields=["total_net_amount", "total_gross_amount"])
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ order_total = order.undiscounted_total_net_amount
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucher": None,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+
+ assert data["order"]["undiscountedTotal"]["net"]["amount"] == order_total
+ assert data["order"]["total"]["net"]["amount"] == order_total
+
+ assert not data["errors"]
+ order.refresh_from_db()
+ assert not order.voucher
+ assert order.search_vector
+
+ assert not order.discounts.count()
+
def test_draft_order_update_with_non_draft_order(
staff_api_client, permission_group_manage_orders, order_with_lines, voucher
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 642fdc449b..b937a86d2b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -12567,6 +12567,7 @@ enum OrderErrorCode @doc(category: "Orders") {
DUPLICATED_INPUT_ITEM
NOT_AVAILABLE_IN_CHANNEL
CHANNEL_INACTIVE
+ INVALID_VOUCHER
}
"""An enumeration."""
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index 36a9ba1c5c..b01b7bb4b4 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -7,6 +7,7 @@ from prices import Money, TaxedMoney
from ..core.prices import quantize_price
from ..core.taxes import TaxData, TaxError, zero_taxed_money
+from ..discount import DiscountType
from ..order import base_calculations
from ..payment.model_helpers import get_subtotal
from ..plugins.manager import PluginsManager
@@ -202,6 +203,8 @@ def fetch_order_prices_if_expired(
charge_taxes = get_charge_taxes_for_order(order)
should_charge_tax = charge_taxes and not order.tax_exemption
+ _update_order_discount_for_voucher(order)
+
if lines is None:
lines = list(order.lines.select_related("variant__product__product_type"))
else:
@@ -263,6 +266,37 @@ def fetch_order_prices_if_expired(
return order, lines
+def _update_order_discount_for_voucher(order: Order):
+ """Create or delete OrderDiscount instances."""
+ if not order.voucher_id:
+ order.discounts.filter(type=DiscountType.VOUCHER).delete()
+
+ elif (
+ order.voucher_id and not order.discounts.filter(voucher=order.voucher).exists()
+ ):
+ voucher = order.voucher
+ voucher_channel_listing = voucher.channel_listings.filter( # type: ignore
+ channel=order.channel
+ ).first()
+ if voucher_channel_listing:
+ order.discounts.create(
+ value_type=voucher.discount_value_type, # type: ignore
+ value=voucher_channel_listing.discount_value,
+ reason=f"Voucher: {voucher.name}", # type: ignore
+ voucher=voucher,
+ type=DiscountType.VOUCHER,
+ )
+
+ # Prefetch has to be cleared and refreshed to avoid returning cached discounts
+ if (
+ hasattr(order, "_prefetched_objects_cache")
+ and "discounts" in order._prefetched_objects_cache
+ ):
+ del order._prefetched_objects_cache["discounts"]
+
+ prefetch_related_objects([order], "discounts")
+
+
def _calculate_and_add_tax(
tax_calculation_strategy: str,
order: "Order",
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index da5ccfb392..1a08f70832 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -34,6 +34,7 @@ class OrderErrorCode(Enum):
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
NOT_AVAILABLE_IN_CHANNEL = "not_available_in_channel"
CHANNEL_INACTIVE = "channel_inactive"
+ INVALID_VOUCHER = "invalid_voucher"
class OrderGrantRefundCreateErrorCode(Enum):