Skip to content

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

Calculate order promotions in draft order (#15459)

Piotr Zabieglikeb0c3f25e9f7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e79571decb..f6c83ed37f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Remove `prefetched_for_webhook` to legacy payload generators - #15369 by @AjmalPonneth
- Don't raise InsufficientStock for track_inventory=False variants #15475 by @carlosa54
- DB performance improvements in attribute dataloaders - #15474 by @AjmalPonneth
+- Calculate order promotions in draft orders - #15459 by @zedzior
# 3.19.0
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 4aa267258d..94084f66b2 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -32,8 +32,8 @@ from ..discount.models import (
VoucherCode,
)
from ..discount.utils import (
- create_discount_objects_for_catalogue_promotions,
- create_discount_objects_for_order_promotions,
+ create_checkout_discount_objects_for_order_promotions,
+ create_checkout_line_discount_objects_for_catalogue_promotions,
delete_gift_line,
get_products_voucher_discount,
get_voucher_code_instance,
@@ -96,7 +96,7 @@ def recalculate_checkout_discounts(
Update line and checkout discounts from vouchers and promotions.
Create or remove gift line if needed.
"""
- create_discount_objects_for_catalogue_promotions(lines)
+ create_checkout_line_discount_objects_for_catalogue_promotions(lines)
recalculate_checkout_discount(manager, checkout_info, lines)
@@ -692,7 +692,9 @@ def recalculate_checkout_discount(
else:
remove_voucher_from_checkout(checkout)
- create_discount_objects_for_order_promotions(checkout_info, lines, save=True)
+ create_checkout_discount_objects_for_order_promotions(
+ checkout_info, lines, save=True
+ )
def add_promo_code_to_checkout(
diff --git a/saleor/discount/interface.py b/saleor/discount/interface.py
index 1919f33269..d835c58b2f 100644
--- a/saleor/discount/interface.py
+++ b/saleor/discount/interface.py
@@ -53,14 +53,22 @@ class VariantPromotionRuleInfo(NamedTuple):
def fetch_variant_rules_info(
variant_channel_listing: "ProductVariantChannelListing",
translation_language_code: str,
-):
+) -> list[VariantPromotionRuleInfo]:
listings_rules = (
variant_channel_listing.variantlistingpromotionrule.all()
if variant_channel_listing
else []
)
+
rules_info = []
- for listing_promotion_rule in listings_rules:
+ if listings_rules:
+ # Before introducing unique_type on discount models, there was possibility
+ # to have multiple catalogue discount associated with single line. In such a
+ # case, we should pick the best discount (with the highest discount amount)
+ listing_promotion_rule = max(
+ list(listings_rules),
+ key=lambda x: x.discount_amount,
+ )
promotion = listing_promotion_rule.promotion_rule.promotion
promotion_translation, rule_translation = get_rule_translations(
diff --git a/saleor/discount/tests/test_utils/fixtures.py b/saleor/discount/tests/test_utils/fixtures.py
index 7cc5a0d4d7..b3244fb7b1 100644
--- a/saleor/discount/tests/test_utils/fixtures.py
+++ b/saleor/discount/tests/test_utils/fixtures.py
@@ -1,7 +1,16 @@
+from decimal import Decimal
+
+import graphene
import pytest
+from prices import TaxedMoney
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....core.taxes import zero_money
+from ....discount import RewardType, RewardValueType
+from ....order import OrderStatus
from ....plugins.manager import get_plugins_manager
+from ....product.models import VariantChannelListingPromotionRule
+from ....warehouse.models import Stock
@pytest.fixture
@@ -51,3 +60,80 @@ def checkout_lines_with_multiple_quantity_info(
lines_info, _ = fetch_checkout_lines(checkout_with_items)
return lines_info
+
+
+def draft_order_and_promotions(
+ order_with_lines,
+ order_promotion_without_rules,
+ catalogue_promotion_without_rules,
+ channel_USD,
+):
+ # given
+ order = order_with_lines
+ line_1 = order.lines.get(quantity=3)
+ line_2 = order.lines.get(quantity=2)
+
+ # prepare catalogue promotions
+ catalogue_promotion = catalogue_promotion_without_rules
+ variant_1 = line_1.variant
+ variant_2 = line_2.variant
+ rule_catalogue = catalogue_promotion.rules.create(
+ name="Catalogue rule fixed",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal(3),
+ )
+ rule_catalogue.channels.add(channel_USD)
+
+ listing = variant_2.channel_listings.first()
+ listing.discounted_price_amount = Decimal(17)
+ listing.save(update_fields=["discounted_price_amount"])
+
+ currency = order.currency
+ VariantChannelListingPromotionRule.objects.create(
+ variant_channel_listing=listing,
+ promotion_rule=rule_catalogue,
+ discount_amount=Decimal(3),
+ currency=currency,
+ )
+
+ # prepare order promotion - subtotal
+ order_promotion = order_promotion_without_rules
+ rule_total = order_promotion.rules.create(
+ name="Fixed subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal(25),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule_total.channels.add(channel_USD)
+
+ # prepare order promotion - gift
+ rule_gift = order_promotion.rules.create(
+ name="Gift subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_type=RewardType.GIFT,
+ )
+ rule_gift.channels.add(channel_USD)
+ rule_gift.gifts.set([variant_1, variant_2])
+ Stock.objects.update(quantity=100)
+
+ # reset prices
+ order.total = TaxedMoney(net=zero_money(currency), gross=zero_money(currency))
+ order.subtotal = TaxedMoney(net=zero_money(currency), gross=zero_money(currency))
+ order.undiscounted_total = TaxedMoney(
+ net=zero_money(currency), gross=zero_money(currency)
+ )
+ order.status = OrderStatus.DRAFT
+ order.save()
+
+ return order, rule_catalogue, rule_total, rule_gift
diff --git a/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py b/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py
new file mode 100644
index 0000000000..cd832bdb51
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_copy_unit_discount_data_to_order_line.py
@@ -0,0 +1,96 @@
+from decimal import Decimal
+
+import graphene
+
+from ....order.fetch import fetch_draft_order_lines_info
+from ... import DiscountType, DiscountValueType
+from ...models import PromotionRule
+from ...utils import _copy_unit_discount_data_to_order_line
+
+
+def test_copy_unit_discount_data_to_order_line_multiple_discounts(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ rule = PromotionRule.objects.get()
+ rule_reward_value = rule.reward_value
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ rule_discount_reason = f"Promotion: {promotion_id}"
+
+ line = order.lines.first()
+ rule_discount = line.discounts.get()
+ rule_discount.reason = rule_discount_reason
+ rule_discount.save(update_fields=["reason"])
+
+ manual_reward_value = Decimal("2")
+ manual_discount_reason = "Manual discount"
+ line.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=manual_reward_value,
+ amount_value=manual_reward_value * line.quantity,
+ currency=order.currency,
+ reason=manual_discount_reason,
+ )
+
+ assert line.discounts.count() == 2
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ _copy_unit_discount_data_to_order_line(lines_info)
+
+ # then
+ line = lines_info[0].line
+ assert line.unit_discount_amount == rule_reward_value + manual_reward_value
+ assert rule_discount_reason in line.unit_discount_reason
+ assert manual_discount_reason in line.unit_discount_reason
+ assert line.unit_discount_type == DiscountValueType.FIXED
+ assert line.unit_discount_value == line.unit_discount_amount
+
+
+def test_copy_unit_discount_data_to_order_line_single_discount(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ rule = PromotionRule.objects.get()
+ rule_reward_value = rule.reward_value
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ rule_discount_reason = f"Promotion: {promotion_id}"
+
+ line = order.lines.first()
+ rule_discount = line.discounts.get()
+ rule_discount.reason = rule_discount_reason
+ rule_discount.save(update_fields=["reason"])
+
+ assert line.discounts.count() == 1
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ _copy_unit_discount_data_to_order_line(lines_info)
+
+ # then
+ line = lines_info[0].line
+ assert line.unit_discount_amount == rule_reward_value
+ assert line.unit_discount_reason == rule_discount_reason
+ assert line.unit_discount_type == rule.reward_value_type
+ assert line.unit_discount_value == rule_reward_value
+
+
+def test_copy_unit_discount_data_to_order_line_no_discount(order_with_lines):
+ # given
+ order = order_with_lines
+ line = order.lines.first()
+ assert not line.discounts.exists()
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ _copy_unit_discount_data_to_order_line(lines_info)
+
+ # then
+ line = lines_info[0].line
+ assert line.unit_discount_amount == Decimal(0)
+ assert not line.unit_discount_reason
+ assert line.unit_discount_type == DiscountValueType.FIXED
+ assert line.unit_discount_value == Decimal(0)
diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py
index 92d59f356d..2e5b940ab3 100644
--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py
+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py
@@ -21,9 +21,9 @@ from ....product.models import (
from ... import DiscountType, RewardType, RewardValueType
from ...models import CheckoutDiscount, CheckoutLineDiscount, PromotionRule
from ...utils import (
- _create_or_update_checkout_discount,
_get_best_gift_reward,
- create_discount_objects_for_order_promotions,
+ create_checkout_discount_objects_for_order_promotions,
+ create_checkout_line_discount_objects_for_catalogue_promotions,
create_or_update_discount_objects_from_promotion_for_checkout,
)
@@ -115,7 +115,14 @@ def test_create_fixed_discount(
== discount_from_db.name
== f"{catalogue_promotion_without_rules.name}: {rule.name}"
)
- assert discount_from_info.reason == discount_from_db.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info.reason
+ == discount_from_db.reason
+ == f"Promotion: {promotion_id}"
+ )
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
assert discount_from_info.voucher == discount_from_db.voucher is None
assert (
@@ -123,11 +130,90 @@ def test_create_fixed_discount(
== discount_from_db.translated_name
== promotion_translation_fr.name
)
+ assert (
+ discount_from_info.unique_type
+ == discount_from_db.unique_type
+ == DiscountType.PROMOTION
+ )
for checkout_line_info in checkout_lines_info[1:]:
assert not checkout_line_info.discounts
+@freeze_time("2020-12-12 12:00:00")
+def test_update_catalogue_discount(
+ checkout_info,
+ checkout_lines_info,
+ catalogue_promotion_without_rules,
+ promotion_translation_fr,
+):
+ # given
+ line_info1 = checkout_lines_info[0]
+ product_line1 = line_info1.product
+
+ actual_reward_value = Decimal("5")
+ discount_to_update = line_info1.line.discounts.create(
+ type=DiscountType.PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=actual_reward_value,
+ name="Fixed 5 catalogue discount",
+ currency=line_info1.channel.currency_code,
+ amount_value=actual_reward_value * line_info1.line.quantity,
+ )
+ checkout_lines_info[0].discounts.append(discount_to_update)
+
+ reward_value = Decimal("7")
+ assert reward_value > actual_reward_value
+ rule = catalogue_promotion_without_rules.rules.create(
+ name="Percentage promotion rule",
+ catalogue_predicate={
+ "productPredicate": {
+ "ids": [graphene.Node.to_global_id("Product", product_line1.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(line_info1.channel)
+
+ listing = line_info1.channel_listing
+ discounted_price = listing.price.amount - reward_value
+ listing.discounted_price_amount = discounted_price
+ listing.save(update_fields=["discounted_price_amount"])
+
+ listing_promotion_rule = VariantChannelListingPromotionRule.objects.create(
+ variant_channel_listing=listing,
+ promotion_rule=rule,
+ discount_amount=reward_value,
+ currency=line_info1.channel.currency_code,
+ )
+ line_info1.rules_info = [
+ VariantPromotionRuleInfo(
+ rule=rule,
+ variant_listing_promotion_rule=listing_promotion_rule,
+ promotion=catalogue_promotion_without_rules,
+ promotion_translation=promotion_translation_fr,
+ rule_translation=None,
+ )
+ ]
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_checkout(
+ checkout_info, checkout_lines_info
+ )
+
+ # then
+ assert len(line_info1.discounts) == 1
+ assert CheckoutLineDiscount.objects.count() == 1
+
+ discount = line_info1.discounts[0]
+ assert discount.id == discount_to_update.id
+ assert discount.value == reward_value
+ assert discount.promotion_rule_id == rule.id
+ assert discount.amount_value == reward_value * line_info1.line.quantity
+ assert discount.unique_type == DiscountType.PROMOTION
+
+
@freeze_time("2020-12-12 12:00:00")
def test_create_fixed_discount_multiple_quantity_in_lines(
checkout_info,
@@ -203,7 +289,14 @@ def test_create_fixed_discount_multiple_quantity_in_lines(
== discount_from_db.name
== catalogue_promotion_without_rules.name
)
- assert discount_from_info.reason == discount_from_db.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info.reason
+ == discount_from_db.reason
+ == f"Promotion: {promotion_id}"
+ )
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
assert discount_from_info.voucher == discount_from_db.voucher is None
@@ -358,7 +451,14 @@ def test_create_percentage_discount(
== discount_from_db.name
== f"{catalogue_promotion_without_rules.name}: {rule.name}"
)
- assert discount_from_info.reason == discount_from_db.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info.reason
+ == discount_from_db.reason
+ == f"Promotion: {promotion_id}"
+ )
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
assert discount_from_info.voucher == discount_from_db.voucher is None
@@ -441,7 +541,14 @@ def test_create_percentage_discount_multiple_quantity_in_lines(
assert discount_from_info.currency == discount_from_db.currency == "USD"
discount_name = f"{catalogue_promotion_without_rules.name}: {rule.name}"
assert discount_from_info.name == discount_from_db.name == discount_name
- assert discount_from_info.reason == discount_from_db.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info.reason
+ == discount_from_db.reason
+ == f"Promotion: {promotion_id}"
+ )
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
assert discount_from_info.voucher == discount_from_db.voucher is None
@@ -449,127 +556,6 @@ def test_create_percentage_discount_multiple_quantity_in_lines(
assert not checkout_line_info.discounts
-def test_create_discount_multiple_rules_applied(
- checkout_info, checkout_lines_info, catalogue_promotion_without_rules
-):
- # given
- line_info1 = checkout_lines_info[0]
- product_line1 = line_info1.product
-
- reward_value_1 = Decimal("2")
- reward_value_2 = Decimal("10")
- rule_1, rule_2 = PromotionRule.objects.bulk_create(
- [
- PromotionRule(
- name="Percentage promotion rule 1",
- promotion=catalogue_promotion_without_rules,
- reward_value_type=RewardValueType.FIXED,
- reward_value=reward_value_1,
- catalogue_predicate={
- "productPredicate": {
- "ids": [graphene.Node.to_global_id("Product", product_line1.id)]
- }
- },
- ),
- PromotionRule(
- name="Percentage promotion rule 2",
- promotion=catalogue_promotion_without_rules,
- reward_value_type=RewardValueType.PERCENTAGE,
- reward_value=reward_value_2,
- catalogue_predicate={
- "variantPredicate": {
- "ids": [
- graphene.Node.to_global_id(
- "ProductVariant", line_info1.variant.id
- )
- ]
- }
- },
- ),
- ]
- )
-
- rule_1.channels.add(line_info1.channel)
- rule_2.channels.add(line_info1.channel)
-
- listing = line_info1.channel_listing
- discount_amount_2 = reward_value_2 / 100 * listing.price.amount
- discounted_price = listing.price.amount - reward_value_1 - discount_amount_2
- listing.discounted_price_amount = discounted_price
- listing.save(update_fields=["discounted_price_amount"])
-
- (
- listing_promotion_rule_1,
- listing_promotion_rule_2,
- ) = VariantChannelListingPromotionRule.objects.bulk_create(
- [
- VariantChannelListingPromotionRule(
- variant_channel_listing=listing,
- promotion_rule=rule_1,
- discount_amount=reward_value_1,
- currency=line_info1.channel.currency_code,
- ),
- VariantChannelListingPromotionRule(
- variant_channel_listing=listing,
- promotion_rule=rule_2,
- discount_amount=discount_amount_2,
- currency=line_info1.channel.currency_code,
- ),
- ]
- )
-
- line_info1.rules_info = [
- VariantPromotionRuleInfo(
- rule=rule_1,
- variant_listing_promotion_rule=listing_promotion_rule_1,
- promotion=catalogue_promotion_without_rules,
- promotion_translation=None,
- rule_translation=None,
- ),
- VariantPromotionRuleInfo(
- rule=rule_2,
- variant_listing_promotion_rule=listing_promotion_rule_2,
- promotion=catalogue_promotion_without_rules,
- promotion_translation=None,
- rule_translation=None,
- ),
- ]
-
- # when
- create_or_update_discount_objects_from_promotion_for_checkout(
- checkout_info, checkout_lines_info
- )
-
- # then
- assert len(line_info1.discounts) == 2
- discount_for_rule_1 = line_info1.line.discounts.get(promotion_rule=rule_1)
- discount_for_rule_2 = line_info1.line.discounts.get(promotion_rule=rule_2)
-
- assert discount_for_rule_1.line == line_info1.line
- assert discount_for_rule_2.line == line_info1.line
-
- assert discount_for_rule_1.type == DiscountType.PROMOTION
- assert discount_for_rule_2.type == DiscountType.PROMOTION
-
- assert discount_for_rule_1.value_type == RewardValueType.FIXED
- assert discount_for_rule_2.value_type == RewardValueType.PERCENTAGE
-
- assert discount_for_rule_1.value == reward_value_1
- assert discount_for_rule_2.value == reward_value_2
-
- assert discount_for_rule_1.amount_value == reward_value_1
- assert discount_for_rule_2.amount_value == discount_amount_2
-
- assert discount_for_rule_1.currency == "USD"
- assert discount_for_rule_2.currency == "USD"
-
- assert discount_for_rule_1.promotion_rule == rule_1
- assert discount_for_rule_2.promotion_rule == rule_2
-
- for checkout_line_info in checkout_lines_info[1:]:
- assert not checkout_line_info.discounts
-
-
def test_two_promotions_applied_to_two_different_lines(
checkout_info, checkout_lines_info, catalogue_promotion_without_rules
):
@@ -691,7 +677,14 @@ def test_two_promotions_applied_to_two_different_lines(
== discount_from_db_1.name
== f"{catalogue_promotion_without_rules.name}: {rule_1.name}"
)
- assert discount_from_info_1.reason == discount_from_db_1.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info_1.reason
+ == discount_from_db_1.reason
+ == f"Promotion: {promotion_id}"
+ )
assert (
discount_from_info_1.promotion_rule
== discount_from_db_1.promotion_rule
@@ -722,7 +715,14 @@ def test_two_promotions_applied_to_two_different_lines(
== discount_from_db_2.name
== f"{catalogue_promotion_without_rules.name}: {rule_2.name}"
)
- assert discount_from_info_2.reason == discount_from_db_2.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info_2.reason
+ == discount_from_db_2.reason
+ == f"Promotion: {promotion_id}"
+ )
assert (
discount_from_info_2.promotion_rule
== discount_from_db_2.promotion_rule
@@ -815,7 +815,14 @@ def test_create_percentage_discount_1_cent_variant_on_10_percentage_discount(
== discount_from_db.name
== f"{catalogue_promotion_without_rules.name}: {rule.name}"
)
- assert discount_from_info.reason == discount_from_db.reason is None
+ promotion_id = graphene.Node.to_global_id(
+ "Promotion", catalogue_promotion_without_rules.pk
+ )
+ assert (
+ discount_from_info.reason
+ == discount_from_db.reason
+ == f"Promotion: {promotion_id}"
+ )
assert discount_from_info.promotion_rule == discount_from_db.promotion_rule == rule
assert discount_from_info.voucher == discount_from_db.voucher is None
@@ -2103,10 +2110,12 @@ def test_create_discount_objects_for_order_promotions_race_condition(
)
with before_after.before(
- "saleor.discount.utils._create_or_update_checkout_discount",
+ "saleor.discount.utils.create_checkout_discount_objects_for_order_promotions",
call_before_creating_discount_object,
):
- create_discount_objects_for_order_promotions(checkout_info, checkout_lines_info)
+ create_checkout_discount_objects_for_order_promotions(
+ checkout_info, checkout_lines_info
+ )
# then
discounts = list(checkout_info.checkout.discounts.all())
@@ -2114,16 +2123,14 @@ def test_create_discount_objects_for_order_promotions_race_condition(
assert discounts[0].amount_value == reward_value
-def test_create_or_update_checkout_discount_race_condition(
+def test_create_or_update_order_discount_race_condition(
checkout_info,
checkout_lines_info,
catalogue_promotion_without_rules,
):
# given
promotion = catalogue_promotion_without_rules
- checkout = checkout_info.checkout
channel = checkout_info.channel
- currency = channel.currency_code
reward_value = Decimal("2")
rule = promotion.rules.create(
@@ -2141,20 +2148,14 @@ def test_create_or_update_checkout_discount_race_condition(
rule.channels.add(channel)
def call_update(*args, **kwargs):
- _create_or_update_checkout_discount(
- checkout,
+ create_checkout_discount_objects_for_order_promotions(
checkout_info,
checkout_lines_info,
- rule,
- reward_value,
- None,
- currency,
- promotion,
- True,
+ save=True,
)
with before_after.before(
- "saleor.discount.utils.get_rule_translations", call_update
+ "saleor.discount.utils._set_checkout_base_prices", call_update
):
call_update()
@@ -2163,37 +2164,23 @@ def test_create_or_update_checkout_discount_race_condition(
assert len(discounts) == 1
-def test_create_or_update_checkout_discount_gift_reward_race_condition(
+def test_create_or_update_order_discount_gift_reward_race_condition(
checkout_info,
checkout_lines_info,
gift_promotion_rule,
):
# given
- rule = gift_promotion_rule
- promotion = gift_promotion_rule.promotion
checkout = checkout_info.checkout
- channel = checkout_info.channel
- currency = channel.currency_code
-
- variants = gift_promotion_rule.gifts.all()
- variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)
- listing = max(list(variant_listings), key=lambda x: x.discounted_price_amount)
def call_update(*args, **kwargs):
- _create_or_update_checkout_discount(
- checkout,
+ create_checkout_discount_objects_for_order_promotions(
checkout_info,
checkout_lines_info,
- rule,
- listing.discounted_price_amount,
- listing,
- currency,
- promotion,
- True,
+ save=True,
)
with before_after.before(
- "saleor.discount.utils.get_rule_translations", call_update
+ "saleor.discount.utils._set_checkout_base_prices", call_update
):
call_update()
@@ -2298,3 +2285,27 @@ def test_get_best_gift_reward_no_variants_in_channel(gift_promotion_rule, channe
# then
assert rule is None
assert listing is None
+
+
+def test_create_checkout_line_discount_objects_for_catalogue_promotions_race_condition(
+ checkout_with_item_on_promotion,
+ plugins_manager,
+):
+ # given
+ checkout = checkout_with_item_on_promotion
+ CheckoutLineDiscount.objects.all().delete()
+
+ # when
+ def call_before_creating_catalogue_line_discount(*args, **kwargs):
+ lines_info, _ = fetch_checkout_lines(checkout)
+ create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)
+
+ with before_after.before(
+ "saleor.discount.utils.prepare_line_discount_objects_for_catalogue_promotions",
+ call_before_creating_catalogue_line_discount,
+ ):
+ lines_info, _ = fetch_checkout_lines(checkout)
+ create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)
+
+ # then
+ assert CheckoutLineDiscount.objects.count() == 1
diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py
new file mode 100644
index 0000000000..86a3a48bdb
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_order.py
@@ -0,0 +1,523 @@
+from decimal import Decimal
+
+import graphene
+
+from ....order.fetch import fetch_draft_order_lines_info
+from ....product.models import (
+ ProductVariantChannelListing,
+ VariantChannelListingPromotionRule,
+)
+from ....warehouse.models import Stock
+from ... import DiscountType, RewardType, RewardValueType
+from ...models import OrderDiscount, OrderLineDiscount
+from ...utils import create_or_update_discount_objects_from_promotion_for_order
+
+
+def test_create_catalogue_discount_fixed(
+ order_with_lines,
+ catalogue_promotion_without_rules,
+):
+ # given
+ order = order_with_lines
+ promotion = catalogue_promotion_without_rules
+ channel = order.channel
+ line_1 = order.lines.get(quantity=3)
+
+ # prepare catalogue promotions
+ variant_1 = line_1.variant
+ reward_value = Decimal(3)
+ rule = promotion.rules.create(
+ name="Catalogue rule fixed",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_1.id)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel)
+
+ listing = variant_1.channel_listings.get(channel=channel)
+ undiscounted_price = listing.price_amount
+ listing.discounted_price_amount = undiscounted_price - reward_value
+ listing.save(update_fields=["discounted_price_amount"])
+
+ currency = order.currency
+ VariantChannelListingPromotionRule.objects.create(
+ variant_channel_listing=listing,
+ promotion_rule=rule,
+ discount_amount=reward_value,
+ currency=currency,
+ )
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+ discount = OrderLineDiscount.objects.get()
+ assert discount.line == line_1
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.PROMOTION
+ assert discount.value_type == RewardValueType.FIXED
+ assert discount.value == reward_value == Decimal(3)
+ assert discount.amount_value == reward_value * line_1.quantity == Decimal(9)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+
+ line = [line_info.line for line_info in lines_info if line_info.line == line_1][0]
+ assert line.base_unit_price_amount == Decimal(7)
+
+
+def test_create_catalogue_discount_percentage(
+ order_with_lines,
+ catalogue_promotion_without_rules,
+):
+ # given
+ order = order_with_lines
+ promotion = catalogue_promotion_without_rules
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ channel = order.channel
+ line_1 = order.lines.get(quantity=3)
+
+ variant_1 = line_1.variant
+ reward_value = Decimal(50)
+ rule = promotion.rules.create(
+ name="Catalogue rule percentage",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_1.id)]
+ }
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel)
+
+ listing = variant_1.channel_listings.get(channel=channel)
+ undiscounted_price = listing.price_amount
+ discount_amount = undiscounted_price * reward_value / 100
+ listing.discounted_price_amount = discount_amount
+ listing.save(update_fields=["discounted_price_amount"])
+
+ currency = order.currency
+ VariantChannelListingPromotionRule.objects.create(
+ variant_channel_listing=listing,
+ promotion_rule=rule,
+ discount_amount=discount_amount,
+ currency=currency,
+ )
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+ discount = OrderLineDiscount.objects.get()
+ assert discount.line == line_1
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.PROMOTION
+ assert discount.value_type == RewardValueType.PERCENTAGE
+ assert discount.value == reward_value == Decimal(50)
+ assert discount.amount_value == discount_amount * line_1.quantity == Decimal(15)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+ line = [line_info.line for line_info in lines_info if line_info.line == line_1][0]
+ assert line.base_unit_price_amount == Decimal(5)
+
+
+def test_create_order_discount_subtotal_fixed(
+ order_with_lines, order_promotion_without_rules
+):
+ # given
+ order = order_with_lines
+ channel = order.channel
+ promotion = order_promotion_without_rules
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ reward_value = Decimal(25)
+ rule = promotion.rules.create(
+ name="Fixed subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseTotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(order.channel)
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ assert not OrderLineDiscount.objects.exists()
+ discount = OrderDiscount.objects.get()
+ assert discount.order == order
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.value_type == RewardValueType.FIXED
+ assert discount.value == reward_value == Decimal(25)
+ assert discount.amount_value == reward_value == Decimal(25)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+
+def test_create_order_discount_subtotal_percentage(
+ order_with_lines, order_promotion_without_rules
+):
+ # given
+ order = order_with_lines
+ channel = order.channel
+ promotion = order_promotion_without_rules
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ reward_value = Decimal(50)
+ rule = promotion.rules.create(
+ name="Percentage subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"eq": 70}}
+ },
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(order.channel)
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ assert not OrderLineDiscount.objects.exists()
+ discount = OrderDiscount.objects.get()
+ assert discount.order == order
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.value_type == RewardValueType.PERCENTAGE
+ assert discount.value == reward_value == Decimal(50)
+ assert discount.amount_value == Decimal(35)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+
+def test_create_order_discount_gift(
+ order_with_lines, order_promotion_without_rules, variant_with_many_stocks
+):
+ # given
+ order = order_with_lines
+ variant = variant_with_many_stocks
+ channel = order.channel
+ promotion = order_promotion_without_rules
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ rule = promotion.rules.create(
+ name="Gift subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_type=RewardType.GIFT,
+ )
+ rule.channels.add(channel)
+ rule.gifts.set([variant])
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+ lines = order.lines.all()
+ assert len(lines) == 3
+
+ gift_line = [line for line in lines if line.is_gift][0]
+ discount = OrderLineDiscount.objects.get()
+ assert discount.line == gift_line
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ listing = ProductVariantChannelListing.objects.filter(
+ channel=channel, variant=variant
+ ).first()
+ assert discount.value == listing.price_amount == Decimal(10)
+ assert discount.amount_value == Decimal(10)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+ assert gift_line.quantity == 1
+ assert gift_line.variant == variant
+ assert gift_line.total_price_gross_amount == Decimal(0)
+ assert gift_line.total_price_net_amount == Decimal(0)
+ assert gift_line.undiscounted_total_price_gross_amount == Decimal(0)
+ assert gift_line.undiscounted_total_price_net_amount == Decimal(0)
+ assert gift_line.unit_price_gross_amount == Decimal(0)
+ assert gift_line.unit_price_net_amount == Decimal(0)
+ assert gift_line.base_unit_price_amount == Decimal(0)
+ assert gift_line.unit_discount_amount == Decimal(0)
+ assert gift_line.unit_discount_type == RewardValueType.FIXED
+ assert gift_line.unit_discount_value == Decimal(0)
+
+
+def test_multiple_rules_subtotal_and_catalogue_discount_applied(
+ draft_order_and_promotions,
+):
+ # given
+ order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ lines_info = fetch_draft_order_lines_info(order)
+ discounted_variant_global_id = rule_catalogue.catalogue_predicate[
+ "variantPredicate"
+ ]["ids"][0]
+ _, discounted_variant_id = graphene.Node.from_global_id(
+ discounted_variant_global_id
+ )
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ order.refresh_from_db()
+ assert OrderLineDiscount.objects.count() == 1
+ line = order.lines.get(variant_id=discounted_variant_id)
+ catalogue_discount = line.discounts.first()
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.value == Decimal(3)
+ assert catalogue_discount.value == rule_catalogue.reward_value
+ assert catalogue_discount.amount_value == Decimal(6)
+ assert (
+ catalogue_discount.amount_value == line.quantity * rule_catalogue.reward_value
+ )
+ assert catalogue_discount.value_type == RewardValueType.FIXED
+
+ assert OrderDiscount.objects.count() == 1
+ order_discount = order.discounts.first()
+ assert order_discount.type == DiscountType.ORDER_PROMOTION
+ assert order_discount.amount_value == Decimal(25)
+ assert order_discount.amount_value == rule_total.reward_value
+ assert order_discount.value_type == RewardValueType.FIXED
+
+
+def test_multiple_rules_gift_and_catalogue_discount_applied(draft_order_and_promotions):
+ # given
+ order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ lines_info = fetch_draft_order_lines_info(order)
+ rule_total.reward_value = Decimal(0)
+ rule_total.save(update_fields=["reward_value"])
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ order.refresh_from_db()
+ # If gift reward applies and gift is discounted by catalogue promotion,
+ # do not create discount object for catalogue promotion. Instead, create discount
+ # object for gift promotion and set reward amount to undiscounted price
+ assert OrderLineDiscount.objects.count() == 2
+ lines = order.lines.all()
+ assert len(lines) == 3
+ gift_line = [line for line in lines if line.is_gift][0]
+ gift_discount = gift_line.discounts.get()
+ assert gift_discount.type == DiscountType.ORDER_PROMOTION
+ listing = ProductVariantChannelListing.objects.filter(
+ channel=order.channel, variant=gift_line.variant
+ ).first()
+ assert gift_discount.value == listing.price_amount
+ assert not gift_discount.value == listing.discounted_price_amount
+ assert gift_discount.value == Decimal(20)
+
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ assert not line_1.discounts.exists()
+ catalogue_discount = line_2.discounts.first()
+ assert catalogue_discount.type == DiscountType.PROMOTION
+
+ assert not OrderDiscount.objects.exists()
+
+
+def test_multiple_rules_no_discount_applied(
+ draft_order_and_promotions, product_variant_list
+):
+ # given
+ order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ rule_total.order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100000}}}
+ }
+ rule_total.save(update_fields=["order_predicate"])
+ rule_gift.order_predicate = {
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100000}}}
+ }
+ rule_gift.save(update_fields=["order_predicate"])
+
+ line_2 = [line for line in order.lines.all() if line.quantity == 2][0]
+ discounted_variant = line_2.variant
+ listing = discounted_variant.channel_listings.get(channel=order.channel)
+ listing.discounted_price_amount = listing.price_amount
+ listing.variantlistingpromotionrule.all().delete()
+ listing.save(update_fields=["discounted_price_amount"])
+ rule_catalogue.catalogue_predicate = {
+ "variantPredicate": {
+ "ids": [
+ graphene.Node.to_global_id("ProductVariant", product_variant_list[0].id)
+ ]
+ }
+ }
+ rule_catalogue.save(update_fields=["catalogue_predicate"])
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert not OrderLineDiscount.objects.exists()
+ assert not OrderDiscount.objects.exists()
+
+
+def test_update_catalogue_discount(
+ order_with_lines_and_catalogue_promotion, catalogue_promotion_without_rules
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ promotion = catalogue_promotion_without_rules
+
+ channel = order.channel
+ line = order.lines.get(quantity=3)
+ variant = line.variant
+ assert OrderLineDiscount.objects.count() == 1
+ discount_to_update = line.discounts.get()
+
+ reward_value = Decimal(6)
+ assert reward_value > promotion.rules.first().reward_value
+ rule = promotion.rules.create(
+ name="New catalogue rule fixed",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel)
+
+ variant_channel_listing = variant.channel_listings.get(channel=channel)
+ undiscounted_price = variant_channel_listing.price_amount
+ variant_channel_listing.discounted_price_amount = undiscounted_price - reward_value
+ variant_channel_listing.save(update_fields=["discounted_price_amount"])
+
+ variant_rule_listing = variant_channel_listing.variantlistingpromotionrule.get()
+ variant_rule_listing.discount_amount = reward_value
+ variant_rule_listing.promotion_rule = rule
+ variant_rule_listing.save(update_fields=["discount_amount", "promotion_rule"])
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ discount = OrderLineDiscount.objects.get()
+ assert discount_to_update.id == discount.id
+ assert discount.line == line
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.PROMOTION
+ assert discount.value_type == RewardValueType.FIXED
+ assert discount.value == reward_value == Decimal(6)
+ assert discount.amount_value == reward_value * line.quantity == Decimal(18)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+
+ line = [line_info.line for line_info in lines_info if line_info.line == line][0]
+ assert line.base_unit_price_amount == Decimal(4)
+
+
+def test_update_order_discount_subtotal(
+ order_with_lines_and_order_promotion, order_promotion_without_rules
+):
+ # given
+ order = order_with_lines_and_order_promotion
+ channel = order.channel
+ promotion = order_promotion_without_rules
+
+ reward_value = Decimal(30)
+ assert reward_value > promotion.rules.first().reward_value
+ rule = promotion.rules.create(
+ name="Fixed subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseTotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(order.channel)
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.get()
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.value_type == RewardValueType.FIXED
+ assert discount.value == reward_value == Decimal(30)
+ assert discount.amount_value == reward_value == Decimal(30)
+ assert discount.currency == channel.currency_code
+ assert discount.name == f"{promotion.name}: {rule.name}"
+
+
+def test_update_gift_discount_new_gift_available(
+ order_with_lines_and_gift_promotion, product_variant_list, warehouse
+):
+ # given
+ order = order_with_lines_and_gift_promotion
+ variant = product_variant_list[0]
+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=100)
+ channel = order.channel
+ current_discount = OrderLineDiscount.objects.get()
+ rule = current_discount.promotion_rule
+
+ gift_price = Decimal(50)
+ listing = variant.channel_listings.get(channel=channel)
+ listing.discounted_price_amount = gift_price
+ listing.price_amount = gift_price
+ listing.save(update_fields=["discounted_price_amount", "price_amount"])
+ rule.gifts.add(variant)
+
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # when
+ create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ lines = order.lines.all()
+ assert len(lines) == 3
+
+ gift_line = [line for line in lines if line.is_gift][0]
+ discount = OrderLineDiscount.objects.get()
+ assert discount.line == gift_line
+ assert discount.promotion_rule == rule
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.value == gift_price == Decimal(50)
+ assert discount.amount_value == gift_price
+ assert discount.currency == channel.currency_code
+
+ assert gift_line.quantity == 1
+ assert gift_line.variant == variant
diff --git a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py
index a090088b4c..8e41130a53 100644
--- a/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py
+++ b/saleor/discount/tests/test_utils/test_fetch_promotion_rules_for_checkout.py
@@ -2,7 +2,7 @@ from decimal import Decimal
from ... import RewardType, RewardValueType
from ...models import PromotionRule
-from ...utils import fetch_promotion_rules_for_checkout
+from ...utils import fetch_promotion_rules_for_checkout_or_order
def test_fetch_promotion_rules_for_checkout(
@@ -23,7 +23,7 @@ def test_fetch_promotion_rules_for_checkout(
)
# when
- rules_per_promotion_id = fetch_promotion_rules_for_checkout(checkout)
+ rules_per_promotion_id = fetch_promotion_rules_for_checkout_or_order(checkout)
# then
assert len(rules_per_promotion_id) == 1
@@ -48,7 +48,7 @@ def test_fetch_promotion_rules_for_checkout_no_matching_rule(
)
# when
- rules_per_promotion_id = fetch_promotion_rules_for_checkout(checkout)
+ rules_per_promotion_id = fetch_promotion_rules_for_checkout_or_order(checkout)
# then
assert not rules_per_promotion_id
@@ -77,7 +77,7 @@ def test_fetch_promotion_rules_for_checkout_relevant_channel_only(
rule_2.channels.add(checkout_JPY.channel)
# when
- rules_per_promotion_id = fetch_promotion_rules_for_checkout(checkout_JPY)
+ rules_per_promotion_id = fetch_promotion_rules_for_checkout_or_order(checkout_JPY)
# then
assert len(rules_per_promotion_id) == 1
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 8e081480f0..c3db0fb11a 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -19,12 +19,14 @@ from ..checkout.base_calculations import (
base_checkout_delivery_price,
base_checkout_subtotal,
)
-from ..checkout.fetch import CheckoutLineInfo, find_checkout_line_info
-from ..checkout.models import Checkout, CheckoutLine
+from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
+from ..checkout.models import Checkout
from ..core.db.connection import allow_writer
from ..core.exceptions import InsufficientStock
from ..core.taxes import zero_money
from ..core.utils.promo_code import InvalidPromoCode
+from ..order.fetch import DraftOrderLineInfo
+from ..order.models import Order, OrderLine
from ..product.models import (
Product,
ProductChannelListing,
@@ -44,6 +46,8 @@ from .models import (
CheckoutLineDiscount,
DiscountValueType,
NotApplicable,
+ OrderDiscount,
+ OrderLineDiscount,
Promotion,
PromotionRule,
Voucher,
@@ -53,8 +57,6 @@ from .models import (
if TYPE_CHECKING:
from ..account.models import User
- from ..checkout.fetch import CheckoutInfo
- from ..order.models import Order, OrderLine
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
from ..product.models import VariantChannelListingPromotionRule
@@ -305,7 +307,7 @@ def validate_voucher_in_order(
def validate_voucher(
voucher: "Voucher",
- total_price: TaxedMoney,
+ total_price: Money,
quantity: int,
customer_email: str,
channel: Channel,
@@ -355,76 +357,125 @@ def create_or_update_discount_objects_from_promotion_for_checkout(
lines_info: Iterable["CheckoutLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- create_discount_objects_for_catalogue_promotions(lines_info)
- create_discount_objects_for_order_promotions(
+ create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)
+ create_checkout_discount_objects_for_order_promotions(
checkout_info, lines_info, database_connection_name=database_connection_name
)
-def create_discount_objects_for_catalogue_promotions(
- lines_info: Iterable["CheckoutLineInfo"],
+def create_checkout_line_discount_objects_for_catalogue_promotions(
+ lines_info: Iterable[CheckoutLineInfo],
):
- line_discounts_to_create = []
- line_discounts_to_update = []
- line_discount_ids_to_remove = []
+ discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)
+ if not discount_data or not lines_info:
+ return
+
+ (
+ discounts_to_create_inputs,
+ discounts_to_update,
+ discount_to_remove,
+ updated_fields,
+ ) = discount_data
+
+ new_line_discounts = []
+ with allow_writer():
+ with transaction.atomic():
+ # Protect against potential thread race. CheckoutLine object can have only
+ # single catalogue discount applied.
+ checkout_id = lines_info[0].line.checkout_id # type: ignore[index]
+ _checkout_lock = list(
+ Checkout.objects.filter(pk=checkout_id).select_for_update(of=(["self"]))
+ )
+
+ if discount_ids_to_remove := [
+ discount.id for discount in discount_to_remove
+ ]:
+ CheckoutLineDiscount.objects.filter(
+ id__in=discount_ids_to_remove
+ ).delete()
+
+ if discounts_to_create_inputs:
+ new_line_discounts = [
+ CheckoutLineDiscount(**input)
+ for input in discounts_to_create_inputs
+ ]
+ CheckoutLineDiscount.objects.bulk_create(
+ new_line_discounts, ignore_conflicts=True
+ )
+
+ if discounts_to_update and updated_fields:
+ CheckoutLineDiscount.objects.bulk_update(
+ discounts_to_update, updated_fields
+ )
+
+ _update_line_info_cached_discounts(
+ lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove
+ )
+
+
+def prepare_line_discount_objects_for_catalogue_promotions(
+ lines_info: Union[Iterable["CheckoutLineInfo"], Iterable["DraftOrderLineInfo"]],
+):
+ line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_update: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []
+ line_discounts_to_remove: list[Union[CheckoutLineDiscount, OrderLineDiscount]] = []
updated_fields: list[str] = []
+ if not lines_info:
+ return
+
for line_info in lines_info:
line = line_info.line
+ # get the existing catalogue discount for the line
+ discount_to_update = None
+ if discounts_to_update := line_info.get_catalogue_discounts():
+ discount_to_update = discounts_to_update[0]
+ # Line should never have multiple catalogue discounts associated. Before
+ # introducing unique_type on discount models, there was such a possibility.
+ line_discounts_to_remove.extend(discounts_to_update[1:])
+
+ # manual line discount do not stack with other discounts
+ if [
+ discount
+ for discount in line_info.discounts
+ if discount.type == DiscountType.MANUAL
+ ]:
+ line_discounts_to_remove.extend(discounts_to_update)
+ continue
+
# discount_amount based on the difference between discounted_price and price
discount_amount = _get_discount_amount(line_info.channel_listing, line.quantity)
- # get the existing discounts for the line
- discounts_to_update = line_info.get_catalogue_discounts()
- rule_id_to_discount = {
- discount.promotion_rule_id: discount for discount in discounts_to_update
- }
-
# delete all existing discounts if the line is not discounted or it is a gift
if not discount_amount or line.is_gift:
- ids_to_remove = [discount.id for discount in discounts_to_update]
- if ids_to_remove:
- line_discount_ids_to_remove.extend(ids_to_remove)
- line_info.discounts = [
- discount
- for discount in line_info.discounts
- if discount.id not in ids_to_remove
- ]
+ line_discounts_to_remove.extend(discounts_to_update)
continue
- # delete the discount objects that are not valid anymore
- line_discount_ids_to_remove.extend(
- _get_discounts_that_are_not_valid_anymore(
- line_info.rules_info,
- rule_id_to_discount, # type: ignore[arg-type]
- line_info,
- )
- )
-
- for rule_info in line_info.rules_info:
+ if line_info.rules_info:
+ rule_info = line_info.rules_info[0]
rule = rule_info.rule
- discount_to_update = rule_id_to_discount.get(rule.id)
rule_discount_amount = _get_rule_discount_amount(
rule_info.variant_listing_promotion_rule, line.quantity
)
discount_name = get_discount_name(rule, rule_info.promotion)
translated_name = get_discount_translated_name(rule_info)
+ reason = _get_discount_reason(rule)
if not discount_to_update:
- line_discount = CheckoutLineDiscount(
- line=line,
- type=DiscountType.PROMOTION,
- value_type=rule.reward_value_type,
- value=rule.reward_value,
- amount_value=rule_discount_amount,
- currency=line.currency,
- name=discount_name,
- translated_name=translated_name,
- reason=None,
- promotion_rule=rule,
- )
- line_discounts_to_create.append(line_discount)
- line_info.discounts.append(line_discount)
+ line_discount_input = {
+ "line": line,
+ "type": DiscountType.PROMOTION,
+ "value_type": rule.reward_value_type,
+ "value": rule.reward_value,
+ "amount_value": rule_discount_amount,
+ "currency": line.currency,
+ "name": discount_name,
+ "translated_name": translated_name,
+ "reason": reason,
+ "promotion_rule": rule,
+ "unique_type": DiscountType.PROMOTION,
+ }
+ line_discounts_to_create_inputs.append(line_discount_input)
else:
_update_discount(
rule,
@@ -433,20 +484,17 @@ def create_discount_objects_for_catalogue_promotions(
discount_to_update,
updated_fields,
)
-
line_discounts_to_update.append(discount_to_update)
+ else:
+ # Fallback for unlike mismatch between discount_amount and rules_info
+ line_discounts_to_remove.extend(discounts_to_update)
- with allow_writer():
- if line_discounts_to_create:
- CheckoutLineDiscount.objects.bulk_create(line_discounts_to_create)
- if line_discounts_to_update and updated_fields:
- CheckoutLineDiscount.objects.bulk_update(
- line_discounts_to_update, updated_fields
- )
- if line_discount_ids_to_remove:
- CheckoutLineDiscount.objects.filter(
- id__in=line_discount_ids_to_remove
- ).delete()
+ return (
+ line_discounts_to_create_inputs,
+ line_discounts_to_update,
+ line_discounts_to_remove,
+ updated_fields,
+ )
def _get_discount_amount(
@@ -466,20 +514,6 @@ def _get_discount_amount(
return unit_discount * line_quantity
-def _get_discounts_that_are_not_valid_anymore(
- rules_info: list["VariantPromotionRuleInfo"],
- rule_id_to_discount: dict[int, "CheckoutLineDiscount"],
- line_info: "CheckoutLineInfo",
-):
- discount_ids = []
- rule_ids = {rule_info.rule.id for rule_info in rules_info}
- for rule_id, discount in rule_id_to_discount.items():
- if rule_id not in rule_ids:
- discount_ids.append(discount.id)
- line_info.discounts.remove(discount)
- return discount_ids
-
-
def _get_rule_discount_amount(
variant_listing_promotion_rule: Optional["VariantChannelListingPromotionRule"],
line_quantity: int,
@@ -496,6 +530,13 @@ def get_discount_name(rule: "PromotionRule", promotion: "Promotion"):
return rule.name or promotion.name
+def _get_discount_reason(rule: PromotionRule):
+ promotion = rule.promotion
+ if promotion.old_sale_id:
+ return f"Sale: {graphene.Node.to_global_id('Sale', promotion.old_sale_id)}"
+ return f"Promotion: {graphene.Node.to_global_id('Promotion', promotion.id)}"
+
+
def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):
promotion_translation = rule_info.promotion_translation
rule_translation = rule_info.rule_translation
@@ -512,7 +553,9 @@ def _update_discount(
rule: "PromotionRule",
rule_info: "VariantPromotionRuleInfo",
rule_discount_amount: Decimal,
- discount_to_update: Union["CheckoutLineDiscount", "CheckoutDiscount"],
+ discount_to_update: Union[
+ "CheckoutLineDiscount", "CheckoutDiscount", "OrderLineDiscount", "OrderDiscount"
+ ],
updated_fields: list[str],
):
if discount_to_update.promotion_rule_id != rule.id:
@@ -545,9 +588,33 @@ def _update_discount(
if discount_to_update.reason != reason:
discount_to_update.reason = reason
updated_fields.append("reason")
+ if hasattr(discount_to_update, "unique_type"):
+ if discount_to_update.unique_type is None:
+ discount_to_update.unique_type = DiscountType.PROMOTION
+ updated_fields.append("unique_type")
-def create_discount_objects_for_order_promotions(
+def _update_line_info_cached_discounts(
+ lines_info, new_line_discounts, updated_discounts, line_discount_ids_to_remove
+):
+ if not any([new_line_discounts, updated_discounts, line_discount_ids_to_remove]):
+ return
+
+ line_id_line_discounts_map = defaultdict(list)
+ for line_discount in new_line_discounts:
+ line_id_line_discounts_map[line_discount.line_id].append(line_discount)
+
+ for line_info in lines_info:
+ line_info.discounts = [
+ discount
+ for discount in line_info.discounts
+ if discount.id not in line_discount_ids_to_remove
+ ]
+ if discount := line_id_line_discounts_map.get(line_info.line.id):
+ line_info.discounts.extend(discount)
+
+
+def create_checkout_discount_objects_for_order_promotions(
checkout_info: "CheckoutInfo",
lines_info: Iterable["CheckoutLineInfo"],
*,
@@ -565,42 +632,77 @@ def create_discount_objects_for_order_promotions(
return
channel = checkout_info.channel
- rule_data = get_best_rule_for_checkout(
- checkout, channel, checkout_info.get_country(), database_connection_name
+ rules = fetch_promotion_rules_for_checkout_or_order(
+ checkout, database_connection_name
+ )
+ rule_data = get_best_rule(
+ rules=rules,
+ channel=channel,
+ country=checkout_info.get_country(),
+ subtotal=checkout.base_subtotal,
+ database_connection_name=database_connection_name,
)
if not rule_data:
_clear_checkout_discount(checkout_info, lines_info, save)
return
best_rule, best_discount_amount, gift_listing = rule_data
-
- _create_or_update_checkout_discount(
- checkout,
- checkout_info,
- lines_info,
- best_rule,
- best_discount_amount,
- gift_listing,
- channel.currency_code,
- best_rule.promotion,
- save,
+ promotion = best_rule.promotion
+ currency = channel.currency_code
+ translation_language_code = checkout.language_code
+ promotion_translation, rule_translation = get_rule_translations(
+ promotion, best_rule, translation_language_code
+ )
+ rule_info = VariantPromotionRuleInfo(
+ rule=best_rule,
+ variant_listing_promotion_rule=None,
+ promotion=promotion,
+ promotion_translation=promotion_translation,
+ rule_translation=rule_translation,
)
+ # gift rule has empty reward_value and reward_value_type
+ value_type = best_rule.reward_value_type or RewardValueType.FIXED
+ amount_value = gift_listing.price_amount if gift_listing else best_discount_amount
+ value = best_rule.reward_value or amount_value
+ discount_object_defaults = {
+ "promotion_rule": best_rule,
+ "value_type": value_type,
+ "value": value,
+ "amount_value": amount_value,
+ "currency": currency,
+ "name": get_discount_name(best_rule, promotion),
+ "translated_name": get_discount_translated_name(rule_info),
+ "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),
+ }
+ if gift_listing:
+ _handle_gift_reward_for_checkout(
+ checkout_info,
+ lines_info,
+ gift_listing,
+ discount_object_defaults,
+ rule_info,
+ save,
+ )
+ else:
+ _handle_order_promotion_for_checkout(
+ checkout_info,
+ lines_info,
+ discount_object_defaults,
+ rule_info,
+ save,
+ )
-def get_best_rule_for_checkout(
- checkout: "Checkout",
+def get_best_rule(
+ rules: Iterable["PromotionRule"],
channel: "Channel",
country: str,
+ subtotal: Money,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
RuleDiscount = namedtuple(
"RuleDiscount", ["rule", "discount_amount", "gift_listing"]
)
- subtotal = checkout.base_subtotal
- rules = fetch_promotion_rules_for_checkout(checkout, database_connection_name)
- if not rules:
- return
-
currency_code = channel.currency_code
rule_discounts: list[RuleDiscount] = []
gift_rules = [rule for rule in rules if rule.reward_type == RewardType.GIFT]
@@ -615,12 +717,14 @@ def get_best_rule_for_checkout(
rule_discounts.append(RuleDiscount(rule, discount_amount, None))
if gift_rules:
- rule, gift_listing = _get_best_gift_reward(
+ best_gift_rule, gift_listing = _get_best_gift_reward(
gift_rules, channel, country, database_connection_name
)
- if rule and gift_listing:
+ if best_gift_rule and gift_listing:
rule_discounts.append(
- RuleDiscount(rule, gift_listing.discounted_price_amount, gift_listing)
+ RuleDiscount(
+ best_gift_rule, gift_listing.discounted_price_amount, gift_listing
+ )
)
if not rule_discounts:
@@ -785,72 +889,14 @@ def _get_available_for_purchase_variant_ids(
return set(available_variant_ids)
-def _create_or_update_checkout_discount(
- checkout: "Checkout",
- checkout_info: "CheckoutInfo",
- lines_info: Iterable["CheckoutLineInfo"],
- best_rule: "PromotionRule",
- best_discount_amount: Decimal,
- gift_listing: Optional[ProductVariantChannelListing],
- currency_code: str,
- promotion: "Promotion",
- save: bool,
-):
- translation_language_code = checkout.language_code
- promotion_translation, rule_translation = get_rule_translations(
- promotion, best_rule, translation_language_code
- )
- rule_info = VariantPromotionRuleInfo(
- rule=best_rule,
- variant_listing_promotion_rule=None,
- promotion=promotion,
- promotion_translation=promotion_translation,
- rule_translation=rule_translation,
- )
- # gift rule has empty reward_value and reward_value_type
- value_type = best_rule.reward_value_type or RewardValueType.FIXED
- amount_value = gift_listing.price_amount if gift_listing else best_discount_amount
- value = best_rule.reward_value or amount_value
- discount_object_defaults = {
- "promotion_rule": best_rule,
- "value_type": value_type,
- "value": value,
- "amount_value": amount_value,
- "currency": currency_code,
- "name": get_discount_name(best_rule, promotion),
- "translated_name": get_discount_translated_name(rule_info),
- "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),
- }
- if gift_listing:
- _handle_gift_reward(
- checkout,
- checkout_info,
- lines_info,
- gift_listing,
- discount_object_defaults,
- rule_info,
- save,
- )
- else:
- _handle_order_promotion(
- checkout,
- checkout_info,
- lines_info,
- discount_object_defaults,
- rule_info,
- save,
- )
-
-
-@allow_writer()
-def _handle_order_promotion(
- checkout: "Checkout",
- checkout_info: "CheckoutInfo",
- lines_info: Iterable["CheckoutLineInfo"],
+def _handle_order_promotion_for_checkout(
+ checkout_info: CheckoutInfo,
+ lines_info: Iterable[CheckoutLineInfo],
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
- save: bool,
+ save: bool = False,
):
+ checkout = checkout_info.checkout
discount_object, created = checkout.discounts.get_or_create(
type=DiscountType.ORDER_PROMOTION,
defaults=discount_object_defaults,
@@ -870,6 +916,7 @@ def _handle_order_promotion(
discount_object.save(update_fields=fields_to_update)
checkout_info.discounts = [discount_object]
+ checkout = checkout_info.checkout
checkout.discount_amount = discount_amount
checkout.discount_name = discount_object.name
checkout.translated_discount_name = discount_object.translated_name
@@ -885,27 +932,29 @@ def _handle_order_promotion(
delete_gift_line(checkout, lines_info)
-def delete_gift_line(checkout: "Checkout", lines_info: Iterable["CheckoutLineInfo"]):
+def delete_gift_line(
+ order_or_checkout: Union[Checkout, Order],
+ lines_info: Iterable[Union["CheckoutLineInfo", "DraftOrderLineInfo"]],
+):
if gift_line_infos := [line for line in lines_info if line.line.is_gift]:
- CheckoutLine.objects.filter(checkout_id=checkout.pk, is_gift=True).delete()
+ order_or_checkout.lines.filter(is_gift=True).delete() # type: ignore[misc]
for gift_line_info in gift_line_infos:
lines_info.remove(gift_line_info) # type: ignore[attr-defined]
@allow_writer()
-def _handle_gift_reward(
- checkout: "Checkout",
- checkout_info: "CheckoutInfo",
- lines_info: Iterable["CheckoutLineInfo"],
+def _handle_gift_reward_for_checkout(
+ checkout_info: CheckoutInfo,
+ lines_info: Iterable[CheckoutLineInfo],
gift_listing: ProductVariantChannelListing,
discount_object_defaults: dict,
rule_info: VariantPromotionRuleInfo,
- save: bool,
+ save: bool = False,
):
with transaction.atomic():
- line, line_created = create_gift_line(checkout, gift_listing.variant_id)
- line_discount = None
- discount_created = False
+ line, line_created = create_gift_line(
+ checkout_info.checkout, gift_listing.variant_id
+ )
(
line_discount,
discount_created,
@@ -931,38 +980,38 @@ def _handle_gift_reward(
line_discount.save(update_fields=fields_to_update)
checkout_info.discounts = []
- checkout.discount_amount = Decimal("0")
+ checkout_info.checkout.discount_amount = Decimal("0")
if save:
- checkout.save(update_fields=["discount_amount"])
+ checkout_info.checkout.save(update_fields=["discount_amount"])
if line_created:
variant = gift_listing.variant
- gift_line_info = CheckoutLineInfo(
- line=line,
- variant=variant,
- channel_listing=gift_listing,
- product=variant.product,
- product_type=variant.product.product_type,
- collections=[],
- discounts=[line_discount],
- rules_info=[rule_info],
- channel=checkout_info.channel,
- )
+ init_values = {
+ "line": line,
+ "variant": variant,
+ "channel_listing": gift_listing,
+ "discounts": [line_discount],
+ "rules_info": [rule_info],
+ "channel": checkout_info.channel,
+ "product": variant.product,
+ "product_type": variant.product.product_type,
+ "collections": [],
+ }
+
+ gift_line_info = CheckoutLineInfo(**init_values)
lines_info.append(gift_line_info) # type: ignore[attr-defined]
else:
- line_info = find_checkout_line_info(lines_info, line.id)
+ line_info = next(
+ line_info for line_info in lines_info if line_info.line.pk == line.id
+ )
line_info.line = line
line_info.discounts = [line_discount]
-def create_gift_line(checkout: "Checkout", variant_id: int):
- defaults = {
- "variant_id": variant_id,
- "quantity": 1,
- "currency": checkout.currency,
- }
- line, created = CheckoutLine.objects.get_or_create(
- checkout=checkout, is_gift=True, defaults=defaults
+def create_gift_line(order_or_checkout: Union[Checkout, Order], variant_id: int):
+ defaults = _get_defaults_for_gift_line(order_or_checkout, variant_id)
+ line, created = order_or_checkout.lines.get_or_create(
+ is_gift=True, defaults=defaults
)
if not created:
fields_to_update = []
@@ -976,6 +1025,29 @@ def create_gift_line(checkout: "Checkout", variant_id: int):
return line, created
+def _get_defaults_for_gift_line(
+ order_or_checkout: Union[Checkout, Order], variant_id: int
+):
+ if isinstance(order_or_checkout, Checkout):
+ return {
+ "variant_id": variant_id,
+ "quantity": 1,
+ "currency": order_or_checkout.currency,
+ }
+ else:
+ return {
+ "variant_id": variant_id,
+ "quantity": 1,
+ "currency": order_or_checkout.currency,
+ "unit_price_net_amount": Decimal(0),
+ "unit_price_gross_amount": Decimal(0),
+ "total_price_net_amount": Decimal(0),
+ "total_price_gross_amount": Decimal(0),
+ "is_shipping_required": True,
+ "is_gift_card": False,
+ }
+
+
def get_variants_to_promotion_rules_map(
variant_qs: "ProductVariantQueryset",
) -> dict[int, list[PromotionRuleInfo]]:
@@ -1024,39 +1096,43 @@ def get_variants_to_promotion_rules_map(
return rules_info_per_variant
-def fetch_promotion_rules_for_checkout(
- checkout: Checkout,
+def fetch_promotion_rules_for_checkout_or_order(
+ instance: Union["Checkout", "Order"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
from ..graphql.discount.utils import PredicateObjectType, filter_qs_by_predicate
applicable_rules = []
promotions = Promotion.objects.active()
- checkout_channel_id = checkout.channel_id
- PromotionRuleChannels = PromotionRule.channels.through.objects.filter(
- channel_id=checkout_channel_id
- )
rules = (
PromotionRule.objects.using(database_connection_name)
- .filter(
- Exists(promotions.filter(id=OuterRef("promotion_id"))),
- Exists(PromotionRuleChannels.filter(promotionrule_id=OuterRef("id"))),
- )
+ .filter(Exists(promotions.filter(id=OuterRef("promotion_id"))))
.exclude(order_predicate={})
+ .prefetch_related("channels")
)
+ rule_to_channel_ids_map = _get_rule_to_channel_ids_map(rules)
- currency = checkout.currency
- checkout_qs = Checkout.objects.using(database_connection_name).filter(
- pk=checkout.pk
+ channel_id = instance.channel_id
+ currency = instance.channel.currency_code
+ qs = instance._meta.model.objects.using(database_connection_name).filter( # type: ignore[attr-defined] # noqa: E501
+ pk=instance.pk
)
for rule in rules.iterator():
- checkouts = filter_qs_by_predicate(
+ rule_channel_ids = rule_to_channel_ids_map.get(rule.id, [])
+ if channel_id not in rule_channel_ids:
+ continue
+ predicate_type = (
+ PredicateObjectType.CHECKOUT
+ if isinstance(instance, Checkout)
+ else PredicateObjectType.ORDER
+ )
+ objects = filter_qs_by_predicate(
rule.order_predicate,
- checkout_qs,
- PredicateObjectType.CHECKOUT,
+ qs,
+ predicate_type,
currency,
)
- if checkouts.exists():
+ if objects.exists():
applicable_rules.append(rule)
return applicable_rules
@@ -1132,6 +1208,299 @@ def update_rule_variant_relation(
)
+def create_or_update_discount_objects_from_promotion_for_order(
+ order: "Order",
+ lines_info: Iterable["DraftOrderLineInfo"],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+):
+ create_order_line_discount_objects_for_catalogue_promotions(lines_info)
+ create_order_discount_objects_for_order_promotions(
+ order, lines_info, database_connection_name=database_connection_name
+ )
+ _copy_unit_discount_data_to_order_line(lines_info)
+
+
+def create_order_line_discount_objects_for_catalogue_promotions(
+ lines_info: Iterable[DraftOrderLineInfo],
+):
+ discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)
+ if not discount_data or not lines_info:
+ return
+
+ (
+ discounts_to_create_inputs,
+ discounts_to_update,
+ discount_to_remove,
+ updated_fields,
+ ) = discount_data
+
+ new_line_discounts = []
+ with allow_writer():
+ with transaction.atomic():
+ # Protect against potential thread race. OrderLine object can have only
+ # single catalogue discount applied.
+ order_id = lines_info[0].line.order_id # type: ignore[index]
+ _order_lock = list(
+ Order.objects.filter(id=order_id).select_for_update(of=(["self"]))
+ )
+
+ if discount_ids_to_remove := [
+ discount.id for discount in discount_to_remove
+ ]:
+ OrderLineDiscount.objects.filter(id__in=discount_ids_to_remove).delete()
+
+ if discounts_to_create_inputs:
+ new_line_discounts = [
+ OrderLineDiscount(**input) for input in discounts_to_create_inputs
+ ]
+ OrderLineDiscount.objects.bulk_create(
+ new_line_discounts, ignore_conflicts=True
+ )
+
+ if discounts_to_update and updated_fields:
+ OrderLineDiscount.objects.bulk_update(
+ discounts_to_update, updated_fields
+ )
+
+ _update_line_info_cached_discounts(
+ lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove
+ )
+
+ affected_line_ids = [
+ discount_line.line.id
+ for discount_line in new_line_discounts
+ + discounts_to_update
+ + discount_to_remove
+ ]
+ modified_lines_info = [
+ line_info for line_info in lines_info if line_info.line.id in affected_line_ids
+ ]
+ # base unit price must reflect all actual catalogue discounts
+ _update_base_unit_price_amount(modified_lines_info)
+
+
+def _copy_unit_discount_data_to_order_line(lines_info: Iterable[DraftOrderLineInfo]):
+ for line_info in lines_info:
+ if discounts := line_info.discounts:
+ line = line_info.line
+ discount_amount = sum([discount.amount_value for discount in discounts])
+ unit_discount_amount = discount_amount / line.quantity
+ discount_reason = "; ".join(
+ [discount.reason for discount in discounts if discount.reason]
+ )
+ discount_type = (
+ discounts[0].value_type
+ if len(discounts) == 1
+ else DiscountValueType.FIXED
+ )
+ discount_value = (
+ discounts[0].value if len(discounts) == 1 else unit_discount_amount
+ )
+
+ line.unit_discount_amount = unit_discount_amount
+ line.unit_discount_reason = discount_reason
+ line.unit_discount_type = discount_type
+ line.unit_discount_value = discount_value
+
+
+def _update_base_unit_price_amount(lines_info: Iterable[DraftOrderLineInfo]):
+ for line_info in lines_info:
+ line = line_info.line
+ base_unit_price = line.undiscounted_base_unit_price_amount
+ for discount in line_info.discounts:
+ unit_discount = discount.amount_value / line.quantity
+ base_unit_price -= unit_discount
+ line.base_unit_price_amount = max(base_unit_price, Decimal(0))
+
+
+def create_order_discount_objects_for_order_promotions(
+ order: "Order",
+ lines_info: Iterable["DraftOrderLineInfo"],
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+):
+ from ..order.base_calculations import base_order_subtotal
+ from ..order.utils import get_order_country
+
+ # If voucher is set or manual discount applied, then skip order promotions
+ if order.voucher_code or order.discounts.filter(type=DiscountType.MANUAL):
+ _clear_order_discount(order, lines_info)
+ return
+
+ # The base prices are required for order promotion discount qualification.
+ _set_order_base_prices(order, lines_info)
+
+ lines = [line_info.line for line_info in lines_info]
+ subtotal = base_order_subtotal(order, lines)
+ channel = order.channel
+ rules = fetch_promotion_rules_for_checkout_or_order(order, database_connection_name)
+ rule_data = get_best_rule(
+ rules=rules,
+ channel=channel,
+ country=get_order_country(order),
+ subtotal=subtotal,
+ database_connection_name=database_connection_name,
+ )
+ if not rule_data:
+ _clear_order_discount(order, lines_info)
+ return
+
+ best_rule, best_discount_amount, gift_listing = rule_data
+ promotion = best_rule.promotion
+ currency = channel.currency_code
+ translation_language_code = order.language_code
+ promotion_translation, rule_translation = get_rule_translations(
+ promotion, best_rule, translation_language_code
+ )
+ rule_info = VariantPromotionRuleInfo(
+ rule=best_rule,
+ variant_listing_promotion_rule=None,
+ promotion=best_rule.promotion,
+ promotion_translation=promotion_translation,
+ rule_translation=rule_translation,
+ )
+ # gift rule has empty reward_value and reward_value_type
+ value_type = best_rule.reward_value_type or RewardValueType.FIXED
+ amount_value = gift_listing.price_amount if gift_listing else best_discount_amount
+ value = best_rule.reward_value or amount_value
+ discount_object_defaults = {
+ "promotion_rule": best_rule,
+ "value_type": value_type,
+ "value": value,
+ "amount_value": amount_value,
+ "currency": currency,
+ "name": get_discount_name(best_rule, promotion),
+ "translated_name": get_discount_translated_name(rule_info),
+ "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),
+ }
+ if gift_listing:
+ _handle_gift_reward_for_order(
+ order,
+ lines_info,
+ gift_listing,
+ discount_object_defaults,
+ rule_info,
+ )
+ else:
+ _handle_order_promotion_for_order(
+ order,
+ lines_info,
+ discount_object_defaults,
+ rule_info,
+ )
+
+
+def _clear_order_discount(
+ order_or_checkout: Union[Checkout, Order],
+ lines_info: Iterable[DraftOrderLineInfo],
+):
+ with transaction.atomic():
+ delete_gift_line(order_or_checkout, lines_info)
+ order_or_checkout.discounts.filter(type=DiscountType.ORDER_PROMOTION).delete()
+
+
+def _set_order_base_prices(order: Order, lines_info: Iterable[DraftOrderLineInfo]):
+ """Set base order prices that includes only catalogue discounts."""
+ from ..order.base_calculations import base_order_subtotal
+
+ lines = [line_info.line for line_info in lines_info]
+ subtotal = base_order_subtotal(order, lines)
+ shipping_price = order.base_shipping_price
+ total = subtotal + shipping_price
+
+ update_fields = []
+ if order.subtotal != TaxedMoney(net=subtotal, gross=subtotal):
+ order.subtotal = TaxedMoney(net=subtotal, gross=subtotal)
+ update_fields.extend(["subtotal_net_amount", "subtotal_gross_amount"])
+ if order.total != TaxedMoney(net=total, gross=total):
+ order.total = TaxedMoney(net=total, gross=total)
+ update_fields.extend(["total_net_amount", "total_gross_amount"])
+
+ if update_fields:
+ with allow_writer():
+ order.save(update_fields=update_fields)
+
+
+def _handle_order_promotion_for_order(
+ order: Order,
+ lines_info: Iterable[DraftOrderLineInfo],
+ discount_object_defaults: dict,
+ rule_info: VariantPromotionRuleInfo,
+):
+ discount_object, created = order.discounts.get_or_create(
+ type=DiscountType.ORDER_PROMOTION,
+ defaults=discount_object_defaults,
+ )
+ discount_amount = discount_object_defaults["amount_value"]
+
+ if not created:
+ fields_to_update: list[str] = []
+ _update_discount(
+ discount_object_defaults["promotion_rule"],
+ rule_info,
+ discount_amount,
+ discount_object,
+ fields_to_update,
+ )
+ if fields_to_update:
+ discount_object.save(update_fields=fields_to_update)
+
+ delete_gift_line(order, lines_info)
+
+
+@allow_writer()
+def _handle_gift_reward_for_order(
+ order: Order,
+ lines_info: Iterable[DraftOrderLineInfo],
+ gift_listing: ProductVariantChannelListing,
+ discount_object_defaults: dict,
+ rule_info: VariantPromotionRuleInfo,
+):
+ with transaction.atomic():
+ line, line_created = create_gift_line(order, gift_listing.variant_id)
+ (
+ line_discount,
+ discount_created,
+ ) = OrderLineDiscount.objects.get_or_create(
+ type=DiscountType.ORDER_PROMOTION,
+ line=line,
+ defaults=discount_object_defaults,
+ )
+
+ if not discount_created:
+ fields_to_update = []
+ if line_discount.line_id != line.id:
+ line_discount.line = line
+ fields_to_update.append("line_id")
+ _update_discount(
+ discount_object_defaults["promotion_rule"],
+ rule_info,
+ discount_object_defaults["amount_value"],
+ line_discount,
+ fields_to_update,
+ )
+ if fields_to_update:
+ line_discount.save(update_fields=fields_to_update)
+
+ if line_created:
+ variant = gift_listing.variant
+ init_values = {
+ "line": line,
+ "variant": variant,
+ "channel_listing": gift_listing,
+ "discounts": [line_discount],
+ "rules_info": [rule_info],
+ "channel": order.channel_id,
+ }
+ gift_line_info = DraftOrderLineInfo(**init_values)
+ lines_info.append(gift_line_info) # type: ignore[attr-defined]
+ else:
+ line_info = next(
+ line_info for line_info in lines_info if line_info.line.pk == line.id
+ )
+ line_info.line = line
+ line_info.discounts = [line_discount]
+
+
def get_active_catalogue_promotion_rules(
allow_replica: bool = False,
) -> "QuerySet[PromotionRule]":
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index c80c36cfb6..c39a3a2d83 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -33,7 +33,11 @@ from ....checkout.utils import (
from ....core.exceptions import InsufficientStock, PermissionDenied
from ....discount import DiscountType, DiscountValueType
from ....discount.models import CheckoutLineDiscount, PromotionRule
-from ....discount.utils import create_gift_line, get_best_rule_for_checkout
+from ....discount.utils import (
+ create_gift_line,
+ fetch_promotion_rules_for_checkout_or_order,
+ get_best_rule,
+)
from ....permission.enums import CheckoutPermissions
from ....product import models as product_models
from ....product.models import ProductChannelListing, ProductVariant
@@ -442,6 +446,7 @@ def group_lines_input_data_on_update(
variant_id = cast(str, line.get("variant_id"))
line_id = cast(str, line.get("line_id"))
+ line_db_id, variant_db_id = None, None
if line_id:
_, line_db_id = graphene.Node.from_global_id(line_id)
@@ -452,7 +457,7 @@ def group_lines_input_data_on_update(
)
if not line_db_id:
- line_data = checkout_lines_data_map[variant_db_id]
+ line_data = checkout_lines_data_map[variant_db_id] # type: ignore[index]
line_data.variant_id = variant_db_id
else:
line_data = checkout_lines_data_map[line_db_id]
@@ -532,7 +537,7 @@ def find_variant_id_when_line_parameter_used(
def apply_gift_reward_if_applicable_on_checkout_creation(
- checkout: "Checkout",
+ checkout: "models.Checkout",
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> None:
"""Apply gift reward if applicable on newly created checkout.
@@ -549,9 +554,13 @@ def apply_gift_reward_if_applicable_on_checkout_creation(
return
_set_checkout_base_subtotal_and_total_on_checkout_creation(checkout)
-
- best_rule_data = get_best_rule_for_checkout(
- checkout, checkout.channel, checkout.get_country(), database_connection_name
+ rules = fetch_promotion_rules_for_checkout_or_order(checkout)
+ best_rule_data = get_best_rule(
+ rules,
+ checkout.channel,
+ checkout.get_country(),
+ checkout.base_subtotal,
+ database_connection_name,
)
if not best_rule_data:
return
@@ -560,22 +569,21 @@ def apply_gift_reward_if_applicable_on_checkout_creation(
if not gift_listing:
return
- amount_value = gift_listing.price_amount
with transaction.atomic():
line, _line_created = create_gift_line(checkout, gift_listing.variant_id)
CheckoutLineDiscount.objects.create(
type=DiscountType.ORDER_PROMOTION,
line=line,
- amount_value=amount_value,
+ amount_value=best_discount_amount,
value_type=DiscountValueType.FIXED,
- value=amount_value,
+ value=best_discount_amount,
promotion_rule=best_rule,
currency=checkout.currency,
)
def _set_checkout_base_subtotal_and_total_on_checkout_creation(
- checkout: "Checkout",
+ checkout: "models.Checkout",
):
"""Calculate and set base subtotal and total for newly created checkout."""
variants_id = [line.variant_id for line in checkout.lines.all()]
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 802fbe36d7..e0cba93fdc 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -9,8 +9,12 @@ from .....checkout import calculations
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
from .....checkout.utils import add_variants_to_checkout, set_external_shipping_id
+from .....discount import RewardValueType
+from .....discount.models import CheckoutLineDiscount, PromotionRule
from .....plugins.manager import get_plugins_manager
-from .....product.models import ProductVariant, ProductVariantChannelListing
+from .....product.models import Product, ProductVariant, ProductVariantChannelListing
+from .....product.utils.variant_prices import update_discounted_prices_for_promotion
+from .....product.utils.variants import fetch_variants_for_promotion_rules
from .....warehouse.models import Stock
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -413,7 +417,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(66):
+ with django_assert_num_queries(71):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -431,7 +435,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(66):
+ with django_assert_num_queries(71):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -562,7 +566,7 @@ def test_create_checkout_with_order_promotion(
}
# when
- with django_assert_num_queries(71):
+ with django_assert_num_queries(76):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -817,7 +821,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(81):
+ with django_assert_num_queries(90):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -831,7 +835,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(81):
+ with django_assert_num_queries(90):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -1076,7 +1080,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(80):
+ with django_assert_num_queries(89):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1089,7 +1093,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(80):
+ with django_assert_num_queries(89):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1101,6 +1105,140 @@ def test_add_checkout_lines_with_reservations(
assert not data["errors"]
[email protected]_queries(autouse=False)
+def test_add_checkout_lines_catalogue_discount_applies(
+ user_api_client,
+ catalogue_promotion_without_rules,
+ checkout,
+ channel_USD,
+ django_assert_num_queries,
+ count_queries,
+ variant_with_many_stocks,
+):
+ # given
+ Stock.objects.update(quantity=100)
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ # prepare promotion with 50% discount
+ promotion = catalogue_promotion_without_rules
+ catalogue_predicate = {"variantPredicate": {"ids": [variant_id]}}
+ rule = promotion.rules.create(
+ name="Catalogue rule percentage 50",
+ catalogue_predicate=catalogue_predicate,
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal(50),
+ )
+ rule.channels.add(channel_USD)
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # update prices
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 3}],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ with django_assert_num_queries(81):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ assert checkout.lines.count() == 1
+ assert CheckoutLineDiscount.objects.count() == 1
+
+
[email protected]_queries(autouse=False)
+def test_add_checkout_lines_multiple_catalogue_discount_applies(
+ user_api_client,
+ catalogue_promotion_without_rules,
+ checkout,
+ channel_USD,
+ django_assert_num_queries,
+ count_queries,
+ product_variant_list,
+ warehouse,
+):
+ # given
+ variants = product_variant_list
+ variant_global_ids = [variant.get_global_id() for variant in variants]
+
+ channel_listing = variants[2].channel_listings.first()
+ channel_listing.channel = channel_USD
+ channel_listing.currency = channel_USD.currency_code
+ channel_listing.save(update_fields=["channel_id", "currency"])
+
+ Stock.objects.bulk_create(
+ [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=1000)
+ for variant in variants
+ ]
+ )
+
+ # create many rules
+ promotion = catalogue_promotion_without_rules
+ rules = []
+ catalogue_predicate = {"variantPredicate": {"ids": variant_global_ids}}
+ for idx in range(5):
+ reward_value = 2 + idx
+ rules.append(
+ PromotionRule(
+ name=f"Catalogue rule fixed {reward_value}",
+ promotion=promotion,
+ catalogue_predicate=catalogue_predicate,
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal(reward_value),
+ )
+ )
+ for idx in range(5):
+ reward_value = idx * 10 + 25
+ rules.append(
+ PromotionRule(
+ name=f"Catalogue rule percentage {reward_value}",
+ promotion=promotion,
+ catalogue_predicate=catalogue_predicate,
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal(reward_value),
+ )
+ )
+ rules = PromotionRule.objects.bulk_create(rules)
+ for rule in rules:
+ rule.channels.add(channel_USD)
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # update prices
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {"variantId": variant_global_ids[0], "quantity": 4},
+ {"variantId": variant_global_ids[1], "quantity": 5},
+ {"variantId": variant_global_ids[2], "quantity": 6},
+ {"variantId": variant_global_ids[3], "quantity": 7},
+ ],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ with django_assert_num_queries(81):
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ assert not data["errors"]
+ assert checkout.lines.count() == 4
+ assert CheckoutLineDiscount.objects.count() == 4
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_add_checkout_lines_order_discount_applies(
@@ -1125,7 +1263,7 @@ def test_add_checkout_lines_order_discount_applies(
}
# when
- with django_assert_num_queries(75):
+ with django_assert_num_queries(84):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1159,7 +1297,7 @@ def test_add_checkout_lines_gift_discount_applies(
}
# when
- with django_assert_num_queries(101):
+ with django_assert_num_queries(111):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
index 901904b478..c772786682 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py
@@ -19,7 +19,7 @@ from .....checkout.models import Checkout, CheckoutLine
from .....core.exceptions import InsufficientStock, InsufficientStockData
from .....core.taxes import TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
-from .....discount.models import CheckoutLineDiscount, PromotionRule
+from .....discount.models import CheckoutLineDiscount
from .....giftcard import GiftCardEvents
from .....giftcard.models import GiftCard, GiftCardEvent
from .....order import OrderOrigin, OrderStatus
@@ -29,7 +29,6 @@ from .....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPING
from .....payment.interface import GatewayResponse
from .....payment.model_helpers import get_subtotal
from .....plugins.manager import PluginsManager, get_plugins_manager
-from .....product.models import VariantChannelListingPromotionRule
from .....tests.utils import flush_post_commit_hooks
from .....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOption
from .....warehouse.tests.utils import get_available_quantity_for_stock
@@ -1679,186 +1678,6 @@ def test_checkout_complete_product_on_old_sale(
).exists(), "Checkout should have been deleted"
-def test_checkout_complete_multiple_rules_applied(
- user_api_client,
- checkout_with_item,
- catalogue_promotion_without_rules,
- payment_dummy,
- address,
- shipping_method,
-):
- # given
- checkout = checkout_with_item
- checkout.shipping_address = address
- checkout.shipping_method = shipping_method
- checkout.billing_address = address
- checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
- checkout.metadata_storage.store_value_in_private_metadata(
- items={"accepted": "false"}
- )
- checkout.save()
- checkout.metadata_storage.save()
-
- checkout_line = checkout.lines.first()
- checkout_line_quantity = checkout_line.quantity
- checkout_line_variant = checkout_line.variant
-
- channel = checkout.channel
-
- reward_value_1 = Decimal("2")
- reward_value_2 = Decimal("10")
- rule_1, rule_2 = PromotionRule.objects.bulk_create(
- [
- PromotionRule(
- name="Percentage promotion rule 1",
- promotion=catalogue_promotion_without_rules,
- reward_value_type=RewardValueType.FIXED,
- reward_value=reward_value_1,
- catalogue_predicate={
- "productPredicate": {
- "ids": [
- graphene.Node.to_global_id(
- "Product", checkout_line_variant.product_id
- )
- ]
- }
- },
- ),
- PromotionRule(
- name="Percentage promotion rule 2",
- promotion=catalogue_promotion_without_rules,
- reward_value_type=RewardValueType.PERCENTAGE,
- reward_value=reward_value_2,
- catalogue_predicate={
- "variantPredicate": {
- "ids": [
- graphene.Node.to_global_id(
- "ProductVariant", checkout_line_variant.id
- )
- ]
- }
- },
- ),
- ]
- )
-
- rule_1.channels.add(channel)
- rule_2.channels.add(channel)
-
- variant_channel_listing = checkout_line_variant.channel_listings.get(
- channel=channel
- )
- discount_amount_2 = reward_value_2 / 100 * variant_channel_listing.price.amount
- discounted_price = (
- variant_channel_listing.price.amount - reward_value_1 - discount_amount_2
- )
- variant_channel_listing.discounted_price_amount = discounted_price
- variant_channel_listing.save(update_fields=["discounted_price_amount"])
-
- VariantChannelListingPromotionRule.objects.bulk_create(
- [
- VariantChannelListingPromotionRule(
- variant_channel_listing=variant_channel_listing,
- promotion_rule=rule_1,
- discount_amount=reward_value_1,
- currency=channel.currency_code,
- ),
- VariantChannelListingPromotionRule(
- variant_channel_listing=variant_channel_listing,
- promotion_rule=rule_2,
- discount_amount=discount_amount_2,
- currency=channel.currency_code,
- ),
- ]
- )
-
- CheckoutLineDiscount.objects.bulk_create(
- [
- CheckoutLineDiscount(
- line=checkout_line,
- type=DiscountType.PROMOTION,
- value_type=DiscountValueType.FIXED,
- amount_value=reward_value_1,
- currency=channel.currency_code,
- promotion_rule=rule_1,
- ),
- CheckoutLineDiscount(
- line=checkout_line,
- type=DiscountType.PROMOTION,
- value_type=DiscountValueType.FIXED,
- amount_value=discount_amount_2,
- currency=channel.currency_code,
- promotion_rule=rule_2,
- ),
- ]
- )
-
- manager = get_plugins_manager(allow_replica=False)
- lines, _ = fetch_checkout_lines(checkout)
- checkout_info = fetch_checkout_info(checkout, lines, manager)
-
- total = calculations.checkout_total(
- manager=manager,
- checkout_info=checkout_info,
- lines=lines,
- address=address,
- )
- payment = payment_dummy
- payment.is_active = True
- payment.order = None
- payment.total = total.gross.amount
- payment.currency = total.gross.currency
- payment.checkout = checkout
- payment.save()
- assert not payment.transactions.exists()
-
- orders_count = Order.objects.count()
- variables = {
- "id": to_global_id_or_none(checkout),
- "redirectUrl": "https://www.example.com",
- }
-
- # when
- response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["checkoutComplete"]
- assert not data["errors"]
-
- order_token = data["order"]["token"]
- order_id = data["order"]["id"]
- assert Order.objects.count() == orders_count + 1
- order = Order.objects.first()
- assert str(order.id) == order_token
- assert order_id == graphene.Node.to_global_id("Order", order.id)
- assert order.metadata == checkout.metadata_storage.metadata
- assert order.private_metadata == checkout.metadata_storage.private_metadata
-
- order_line = order.lines.first()
- subtotal = get_subtotal(order.lines.all(), order.currency)
- assert order.subtotal == subtotal
- assert data["order"]["subtotal"]["gross"]["amount"] == subtotal.gross.amount
- assert order.total == total
- assert order.undiscounted_total == total + (
- order_line.undiscounted_total_price - order_line.total_price
- )
- assert order_line.discounts.count() == 2
-
- assert checkout_line_quantity == order_line.quantity
- assert checkout_line_variant == order_line.variant
- assert order.shipping_address == address
- assert order.shipping_method == checkout.shipping_method
- assert order.payments.exists()
- order_payment = order.payments.first()
- assert order_payment == payment
- assert payment.transactions.count() == 1
-
- assert not Checkout.objects.filter(
- pk=checkout.pk
- ).exists(), "Checkout should have been deleted"
-
-
def test_checkout_with_voucher_on_specific_product_complete_with_product_on_promotion(
user_api_client,
checkout_with_item_and_voucher_specific_products,
diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
index a74f429ad2..c2b3dccc05 100644
--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py
@@ -15,7 +15,7 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
from .....core.taxes import TaxError, zero_money, zero_taxed_money
from .....discount import DiscountType, DiscountValueType, RewardValueType
-from .....discount.models import CheckoutLineDiscount, Promotion
+from .....discount.models import CheckoutLineDiscount
from .....giftcard import GiftCardEvents
from .....giftcard.models import GiftCard, GiftCardEvent
from .....order import OrderOrigin, OrderStatus
@@ -966,11 +966,54 @@ def test_order_from_checkout_voucher_not_increase_uses_on_preprocess_creation_fa
assert code.used == 0
+MUTATION_ORDER_CREATE_FROM_CHECKOUT_PROMOTIONS = """
+mutation orderCreateFromCheckout($id: ID!){
+ orderCreateFromCheckout(id: $id){
+ order{
+ id
+ total {
+ currency
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
+ lines {
+ unitDiscount {
+ amount
+ }
+ unitDiscountType
+ unitDiscountValue
+ isGift
+ quantity
+ }
+ discounts {
+ amount {
+ amount
+ }
+ valueType
+ type
+ }
+ }
+ errors{
+ field
+ message
+ code
+ variants
+ }
+ }
+}
+"""
+
+
def test_order_from_checkout_on_catalogue_promotion(
app_api_client,
checkout_with_item_on_promotion,
permission_handle_checkouts,
permission_manage_checkouts,
+ permission_manage_orders,
address,
shipping_method,
):
@@ -987,9 +1030,13 @@ def test_order_from_checkout_on_catalogue_promotion(
# when
response = app_api_client.post_graphql(
- MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT_PROMOTIONS,
variables,
- permissions=[permission_handle_checkouts, permission_manage_checkouts],
+ permissions=[
+ permission_handle_checkouts,
+ permission_manage_checkouts,
+ permission_manage_orders,
+ ],
)
# then
@@ -997,22 +1044,30 @@ def test_order_from_checkout_on_catalogue_promotion(
data = content["data"]["orderCreateFromCheckout"]
assert not data["errors"]
- order = Order.objects.first()
- assert order.status == OrderStatus.UNCONFIRMED
- assert order.origin == OrderOrigin.CHECKOUT
- assert not order.original
-
- assert order.lines.count() == 1
- line = order.lines.first()
- assert line.sale_id
- assert line.unit_discount_reason
- assert line.discounts.count() == 1
- discount = line.discounts.first()
+ order_db = Order.objects.first()
+ assert order_db.status == OrderStatus.UNCONFIRMED
+ assert order_db.origin == OrderOrigin.CHECKOUT
+ assert not order_db.original
+
+ assert order_db.lines.count() == 1
+ line_db = order_db.lines.first()
+ assert line_db.sale_id
+ assert line_db.unit_discount_reason
+ assert line_db.discounts.count() == 1
+ discount = line_db.discounts.first()
assert discount.promotion_rule
assert (
- discount.amount_value == (order.undiscounted_total - order.total).gross.amount
+ discount.amount_value
+ == (order_db.undiscounted_total - order_db.total).gross.amount
)
- assert not order.discounts.first()
+ assert not order_db.discounts.first()
+
+ assert not data["order"]["discounts"]
+ assert len(data["order"]["lines"]) == 1
+ line = data["order"]["lines"][0]
+ assert line["unitDiscount"]["amount"] == discount.amount_value / line["quantity"]
+ assert line["unitDiscountType"] == RewardValueType.FIXED.upper()
+ assert line["unitDiscountValue"] == discount.amount_value / line["quantity"]
def test_order_from_checkout_on_order_promotion(
@@ -1020,6 +1075,7 @@ def test_order_from_checkout_on_order_promotion(
checkout_with_item_and_order_discount,
permission_handle_checkouts,
permission_manage_checkouts,
+ permission_manage_orders,
address,
shipping_method,
):
@@ -1036,9 +1092,13 @@ def test_order_from_checkout_on_order_promotion(
# when
response = app_api_client.post_graphql(
- MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT_PROMOTIONS,
variables,
- permissions=[permission_handle_checkouts, permission_manage_checkouts],
+ permissions=[
+ permission_handle_checkouts,
+ permission_manage_checkouts,
+ permission_manage_orders,
+ ],
)
# then
@@ -1059,6 +1119,12 @@ def test_order_from_checkout_on_order_promotion(
)
assert order_discount.type == DiscountType.ORDER_PROMOTION
+ discounts = data["order"]["discounts"]
+ assert len(discounts) == 1
+ assert discounts[0]["amount"]["amount"] == order_discount.amount_value
+ assert discounts[0]["type"] == DiscountType.ORDER_PROMOTION.upper()
+ assert discounts[0]["valueType"] == DiscountValueType.FIXED.upper()
+
def test_order_from_checkout_on_gift_promotion(
app_api_client,
@@ -1066,6 +1132,7 @@ def test_order_from_checkout_on_gift_promotion(
gift_promotion_rule,
permission_handle_checkouts,
permission_manage_checkouts,
+ permission_manage_orders,
address,
shipping_method,
):
@@ -1083,9 +1150,13 @@ def test_order_from_checkout_on_gift_promotion(
# when
response = app_api_client.post_graphql(
- MUTATION_ORDER_CREATE_FROM_CHECKOUT,
+ MUTATION_ORDER_CREATE_FROM_CHECKOUT_PROMOTIONS,
variables,
- permissions=[permission_handle_checkouts, permission_manage_checkouts],
+ permissions=[
+ permission_handle_checkouts,
+ permission_manage_checkouts,
+ permission_manage_orders,
+ ],
)
# then
@@ -1101,10 +1172,23 @@ def test_order_from_checkout_on_gift_promotion(
assert not order.discounts.all()
assert order.lines.count() == line_count
gift_line = order.lines.get(is_gift=True)
+ gift_price = gift_line.variant.channel_listings.get(
+ channel=checkout.channel
+ ).discounted_price_amount
assert gift_line.discounts.count() == 1
line_discount = gift_line.discounts.first()
assert line_discount.promotion_rule == gift_promotion_rule
assert line_discount.type == DiscountType.ORDER_PROMOTION
+ assert line_discount.amount_value == gift_price
+ assert line_discount.value == gift_price
+
+ assert not data["order"]["discounts"]
+ lines = data["order"]["lines"]
+ assert len(lines) == 2
+ gift_line_api = [line for line in lines if line["isGift"]][0]
+ assert gift_line_api["unitDiscount"]["amount"] == gift_price
+ assert gift_line_api["unitDiscountValue"] == gift_price
+ assert gift_line_api["unitDiscountType"] == RewardValueType.FIXED.upper()
def test_order_from_checkout_on_catalogue_and_gift_promotion(
@@ -1197,91 +1281,6 @@ def test_order_from_checkout_on_catalogue_and_gift_promotion(
).gross.amount == top_price + line_discount.amount_value
-def test_order_from_checkout_multiple_rules_applied(
- app_api_client,
- checkout_with_item_on_promotion,
- permission_handle_checkouts,
- permission_manage_checkouts,
- address,
- shipping_method,
-):
- # given
- checkout = checkout_with_item_on_promotion
- checkout.shipping_address = address
- checkout.shipping_method = shipping_method
- checkout.billing_address = address
- checkout.save()
-
- channel = checkout.channel
-
- line = checkout.lines.first()
- variant = line.variant
- variant_channel_listing = variant.channel_listings.get(channel=channel)
-
- reward_value_2 = Decimal("10.00")
- promotion = Promotion.objects.first()
- rule_2 = promotion.rules.create(
- name="Percentage promotion rule 2",
- reward_value_type=RewardValueType.PERCENTAGE,
- reward_value=reward_value_2,
- catalogue_predicate={
- "variantPredicate": {
- "ids": [graphene.Node.to_global_id("ProductVariant", line.variant_id)]
- }
- },
- )
- rule_2.channels.add(channel)
-
- discount_amount_2 = reward_value_2 / 100 * variant_channel_listing.price.amount
-
- variant_channel_listing.variantlistingpromotionrule.create(
- promotion_rule=rule_2,
- discount_amount=discount_amount_2,
- currency=channel.currency_code,
- )
- CheckoutLineDiscount.objects.create(
- line=line,
- type=DiscountType.PROMOTION,
- value_type=DiscountValueType.PERCENTAGE,
- amount_value=discount_amount_2,
- currency=channel.currency_code,
- promotion_rule=rule_2,
- )
-
- variant_channel_listing.discounted_price_amount = (
- variant_channel_listing.discounted_price_amount - discount_amount_2
- )
- variant_channel_listing.save(update_fields=["discounted_price_amount"])
-
- variables = {
- "id": graphene.Node.to_global_id("Checkout", checkout.pk),
- }
-
- # when
- response = app_api_client.post_graphql(
- MUTATION_ORDER_CREATE_FROM_CHECKOUT,
- variables,
- permissions=[permission_handle_checkouts, permission_manage_checkouts],
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["orderCreateFromCheckout"]
- assert not data["errors"]
-
- order = Order.objects.first()
-
- assert order.status == OrderStatus.UNCONFIRMED
- assert order.origin == OrderOrigin.CHECKOUT
- assert not order.original
-
- assert order.lines.count() == 1
- line = order.lines.first()
- assert line.sale_id == graphene.Node.to_global_id("Promotion", promotion.pk)
- assert line.unit_discount_reason
- assert line.discounts.count() == 2
-
-
@pytest.mark.integration
def test_order_from_checkout_without_inventory_tracking(
app_api_client,
diff --git a/saleor/graphql/discount/utils.py b/saleor/graphql/discount/utils.py
index a40740bc52..6bac0d3b23 100644
--- a/saleor/graphql/discount/utils.py
+++ b/saleor/graphql/discount/utils.py
@@ -10,6 +10,7 @@ from graphene.utils.str_converters import to_snake_case
from ...checkout.models import Checkout
from ...discount.models import Promotion, PromotionRule
from ...discount.utils import update_rule_variant_relation
+from ...order.models import Order
from ...product.managers import ProductsQueryset, ProductVariantQueryset
from ...product.models import (
Category,
@@ -20,6 +21,7 @@ from ...product.models import (
)
from ..checkout.filters import CheckoutDiscountedObjectWhere
from ..core.connection import where_filter_qs
+from ..order.filters import OrderDiscountedObjectWhere
from ..product.filters import (
CategoryWhere,
CollectionWhere,
@@ -283,6 +285,10 @@ def _handle_predicate(
return _handle_checkout_predicate(
result_qs, base_qs, predicate_data, operator, currency
)
+ elif predicate_type == PredicateObjectType.ORDER:
+ return _handle_order_predicate(
+ result_qs, base_qs, predicate_data, operator, currency
+ )
def _handle_catalogue_predicate(
@@ -327,6 +333,32 @@ def _handle_checkout_predicate(
return result_qs
+def _handle_order_predicate(
+ result_qs: QuerySet,
+ base_qs: QuerySet,
+ predicate_data: dict[str, Union[dict, str, list, bool]],
+ operator,
+ currency: Optional[str] = None,
+):
+ predicate_data = _predicate_to_snake_case(predicate_data)
+ if predicate := predicate_data.get("discounted_object_predicate"):
+ if currency:
+ predicate["currency"] = currency
+
+ orders = where_filter_qs(
+ Order.objects.filter(pk__in=base_qs.values("pk")),
+ {},
+ OrderDiscountedObjectWhere,
+ predicate,
+ None,
+ )
+ if operator == Operators.AND:
+ result_qs &= orders
+ else:
+ result_qs |= orders
+ return result_qs
+
+
def _predicate_to_snake_case(obj: Any) -> Any:
if isinstance(obj, dict):
data = {}
diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.py
index aeb1fffe94..aa6056ae40 100644
--- a/saleor/graphql/order/filters.py
+++ b/saleor/graphql/order/filters.py
@@ -2,6 +2,7 @@ from uuid import UUID
import django_filters
import graphene
+from django.core.exceptions import ValidationError
from django.db.models import Exists, OuterRef, Q
from django.utils import timezone
from graphql.error import GraphQLError
@@ -12,6 +13,7 @@ from ...order.models import Order, OrderLine
from ...order.search import search_orders
from ...payment import ChargeStatus
from ...product.models import ProductVariant
+from ..channel.filters import get_currency_from_filter_data
from ..core.filters import (
GlobalIDMultipleChoiceFilter,
ListObjectTypeFilter,
@@ -20,9 +22,10 @@ from ..core.filters import (
)
from ..core.types import DateRangeInput, DateTimeRangeInput
from ..core.utils import from_global_id_or_error
+from ..discount.filters import DiscountedObjectWhere
from ..payment.enums import PaymentChargeStatusEnum
from ..utils import resolve_global_ids_to_primary_keys
-from ..utils.filters import filter_range_field
+from ..utils.filters import filter_range_field, filter_where_by_numeric_field
from .enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnum, OrderStatusFilter
@@ -230,3 +233,28 @@ class OrderFilter(DraftOrderFilter):
message="'ids' and 'numbers` are not allowed to use together in filter."
)
return super().is_valid()
+
+
+class OrderDiscountedObjectWhere(DiscountedObjectWhere):
+ class Meta:
+ model = Order
+ fields = ["subtotal_net_amount", "total_net_amount"]
+
+ def filter_base_subtotal_price(self, queryset, name, value):
+ currency = get_currency_from_filter_data(self.data)
+ return _filter_price(queryset, name, "subtotal_net_amount", value, currency)
+
+ def filter_base_total_price(self, queryset, name, value):
+ currency = get_currency_from_filter_data(self.data)
+ return _filter_price(queryset, name, "total_net_amount", value, currency)
+
+
+def _filter_price(qs, _, field_name, value, currency):
+ # We will have single channel/currency as the rule can be applied only
+ # on channels with the same currencies
+ if not currency:
+ raise ValidationError(
+ "You must provide a currency to filter by price field.", code="required"
+ )
+ qs = qs.filter(currency=currency)
+ return filter_where_by_numeric_field(qs, field_name, value)
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 6dfe4c639b..4e61972b67 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -481,7 +481,7 @@ class DraftOrderCreate(
)
@classmethod
- def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
+ def should_invalidate_prices(cls, cleaned_input, is_new_instance) -> bool:
# Force price recalculation for all new instances
return is_new_instance
@@ -565,7 +565,7 @@ class DraftOrderCreate(
"display_gross_prices",
]
)
- if cls.should_invalidate_prices(instance, cleaned_input, is_new_instance):
+ if cls.should_invalidate_prices(cleaned_input, is_new_instance):
invalidate_order_prices(instance)
updated_fields.extend(["should_refresh_prices"])
recalculate_order_weight(instance)
diff --git a/saleor/graphql/order/mutations/draft_order_update.py b/saleor/graphql/order/mutations/draft_order_update.py
index d835ff6599..83cf777f57 100644
--- a/saleor/graphql/order/mutations/draft_order_update.py
+++ b/saleor/graphql/order/mutations/draft_order_update.py
@@ -51,14 +51,13 @@ class DraftOrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
return instance
@classmethod
- def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
+ def should_invalidate_prices(cls, cleaned_input, *args) -> bool:
return any(
field in cleaned_input
for field in [
"shipping_address",
"billing_address",
"shipping_method",
- "lines",
"voucher",
]
)
diff --git a/saleor/graphql/order/mutations/order_update.py b/saleor/graphql/order/mutations/order_update.py
index ec5e8dee2d..06012422d5 100644
--- a/saleor/graphql/order/mutations/order_update.py
+++ b/saleor/graphql/order/mutations/order_update.py
@@ -84,7 +84,7 @@ class OrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
return instance
@classmethod
- def should_invalidate_prices(cls, instance, cleaned_input, is_new_instance) -> bool:
+ def should_invalidate_prices(cls, cleaned_input, *args) -> bool:
return any(
cleaned_input.get(field) is not None
for field in ["shipping_address", "billing_address"]
@@ -101,7 +101,7 @@ class OrderUpdate(DraftOrderCreate, ModelWithExtRefMutation):
*prepare_order_search_vector_value(instance)
)
manager = get_plugin_manager_promise(info.context).get()
- if cls.should_invalidate_prices(instance, cleaned_input, False):
+ if cls.should_invalidate_prices(cleaned_input):
invalidate_order_prices(instance)
instance.save()
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index e568f56cf2..82267764ad 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -1,4 +1,5 @@
from datetime import datetime, timedelta
+from decimal import Decimal
from unittest.mock import patch
import graphene
@@ -10,10 +11,13 @@ from prices import Money, TaxedMoney
from .....core import EventDeliveryStatus
from .....core.models import EventDelivery
+from .....core.prices import quantize_price
from .....core.taxes import zero_taxed_money
+from .....discount import DiscountValueType
from .....discount.models import VoucherCustomer
from .....order import OrderOrigin, OrderStatus
from .....order import events as order_events
+from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....order.interface import OrderTaxedPricesData
from .....order.models import OrderEvent
@@ -1193,3 +1197,212 @@ def test_draft_order_complete_calls_failing_plugin(
order.refresh_from_db()
assert not order.should_refresh_prices
assert order.tax_error == "Empty tax data."
+
+
+DRAFT_ORDER_COMPLETE_WITH_DISCOUNTS_MUTATION = """
+ mutation draftComplete($id: ID!) {
+ draftOrderComplete(id: $id) {
+ errors {
+ field
+ code
+ message
+ }
+ order {
+ id
+ total {
+ net {
+ amount
+ }
+ }
+ discounts {
+ amount {
+ amount
+ }
+ valueType
+ type
+ reason
+ }
+ lines {
+ id
+ quantity
+ totalPrice {
+ net {
+ amount
+ }
+ }
+ unitDiscount {
+ amount
+ }
+ unitDiscountValue
+ unitDiscountReason
+ unitDiscountType
+ isGift
+ }
+ }
+ }
+ }
+ """
+
+
+def test_draft_order_complete_with_catalogue_and_order_discount(
+ staff_api_client,
+ permission_group_manage_orders,
+ staff_user,
+ draft_order_and_promotions,
+ plugins_manager,
+):
+ # given
+ Allocation.objects.all().delete()
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ order, rule_catalogue, rule_total, _ = draft_order_and_promotions
+ catalogue_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_catalogue.promotion_id
+ )
+ order_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_total.promotion_id
+ )
+ rule_catalogue_value = rule_catalogue.reward_value
+ rule_total_value = rule_total.reward_value
+
+ currency = order.currency
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ fetch_order_prices_if_expired(order, plugins_manager, force_update=True)
+
+ # when
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_COMPLETE_WITH_DISCOUNTS_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ order_data = content["data"]["draftOrderComplete"]["order"]
+
+ assert len(order_data["discounts"]) == 1
+
+ order_discount = order_data["discounts"][0]
+ assert order_discount["amount"]["amount"] == 25.00 == rule_total_value
+ assert order_discount["reason"] == f"Promotion: {order_promotion_id}"
+ assert order_discount["amount"]["amount"] == 25.00 == rule_total_value
+ assert order_discount["valueType"] == DiscountValueType.FIXED.upper()
+
+ lines_db = order.lines.all()
+ line_1_db = [line for line in lines_db if line.quantity == 3][0]
+ line_2_db = [line for line in lines_db if line.quantity == 2][0]
+ line_1_base_total = line_1_db.quantity * line_1_db.base_unit_price_amount
+ line_2_base_total = line_2_db.quantity * line_2_db.base_unit_price_amount
+ base_total = line_1_base_total + line_2_base_total
+ line_1_order_discount_portion = rule_total_value * line_1_base_total / base_total
+ line_2_order_discount_portion = rule_total_value - line_1_order_discount_portion
+
+ lines = order_data["lines"]
+ line_1 = [line for line in lines if line["quantity"] == 3][0]
+ line_2 = [line for line in lines if line["quantity"] == 2][0]
+ line_1_total = quantize_price(
+ line_1_db.undiscounted_total_price_net_amount - line_1_order_discount_portion,
+ currency,
+ )
+ assert line_1["totalPrice"]["net"]["amount"] == float(line_1_total)
+ assert line_1["unitDiscount"]["amount"] == 0.00
+ assert line_1["unitDiscountReason"] is None
+ assert line_1["unitDiscountValue"] == 0.00
+
+ line_2_total = quantize_price(
+ line_2_db.undiscounted_total_price_net_amount
+ - rule_catalogue_value * line_2_db.quantity
+ - line_2_order_discount_portion,
+ currency,
+ )
+ assert line_2["totalPrice"]["net"]["amount"] == float(line_2_total)
+ assert line_2["unitDiscount"]["amount"] == rule_catalogue_value
+ assert line_2["unitDiscountReason"] == f"Promotion: {catalogue_promotion_id}"
+ assert line_2["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert line_2["unitDiscountValue"] == rule_catalogue_value
+
+ total = (
+ order.undiscounted_total_net_amount
+ - line_2["quantity"] * rule_catalogue_value
+ - rule_total_value
+ )
+ assert order_data["total"]["net"]["amount"] == total
+ assert total == line_2_total + line_1_total + order.base_shipping_price_amount
+
+
+def test_draft_order_complete_with_catalogue_and_gift_discount(
+ staff_api_client,
+ permission_group_manage_orders,
+ staff_user,
+ draft_order_and_promotions,
+ plugins_manager,
+):
+ # given
+ Allocation.objects.all().delete()
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ rule_total.reward_value = Decimal(0)
+ rule_total.save(update_fields=["reward_value"])
+ catalogue_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_catalogue.promotion_id
+ )
+ gift_promotion_id = graphene.Node.to_global_id("Promotion", rule_gift.promotion_id)
+ rule_catalogue_value = rule_catalogue.reward_value
+
+ currency = order.currency
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ fetch_order_prices_if_expired(order, plugins_manager, force_update=True)
+
+ # when
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_COMPLETE_WITH_DISCOUNTS_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ order_data = content["data"]["draftOrderComplete"]["order"]
+ assert not order_data["discounts"]
+
+ lines_db = order.lines.all()
+ line_1_db = [line for line in lines_db if line.quantity == 3][0]
+ line_2_db = [line for line in lines_db if line.quantity == 2][0]
+ gift_line_db = [line for line in lines_db if line.is_gift][0]
+ gift_price = gift_line_db.variant.channel_listings.get(
+ channel=order.channel
+ ).price_amount
+
+ lines = order_data["lines"]
+ assert len(lines) == 3
+ line_1 = [line for line in lines if line["quantity"] == 3][0]
+ line_2 = [line for line in lines if line["quantity"] == 2][0]
+ gift_line = [line for line in lines if line["isGift"] is True][0]
+
+ line_1_total = line_1_db.undiscounted_total_price_net_amount
+ assert line_1["totalPrice"]["net"]["amount"] == line_1_total
+ assert line_1["unitDiscount"]["amount"] == 0.00
+ assert line_1["unitDiscountReason"] is None
+ assert line_1["unitDiscountValue"] == 0.00
+
+ line_2_total = quantize_price(
+ line_2_db.undiscounted_total_price_net_amount
+ - rule_catalogue_value * line_2_db.quantity,
+ currency,
+ )
+ assert line_2["totalPrice"]["net"]["amount"] == line_2_total
+ assert line_2["unitDiscount"]["amount"] == rule_catalogue_value
+ assert line_2["unitDiscountReason"] == f"Promotion: {catalogue_promotion_id}"
+ assert line_2["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert line_2["unitDiscountValue"] == rule_catalogue_value
+
+ assert gift_line["totalPrice"]["net"]["amount"] == 0.00
+ assert gift_line["unitDiscount"]["amount"] == gift_price
+ assert gift_line["unitDiscountReason"] == f"Promotion: {gift_promotion_id}"
+ assert gift_line["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert gift_line["unitDiscountValue"] == gift_price
+
+ total = (
+ order.undiscounted_total_net_amount - rule_catalogue_value * line_2_db.quantity
+ )
+ assert order_data["total"]["net"]["amount"] == total
+ assert total == line_2_total + line_1_total + order.base_shipping_price_amount
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 bb5d8d14d3..9f6c74c85f 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -8,8 +8,9 @@ import pytz
from prices import Money
from .....checkout import AddressType
+from .....core.prices import quantize_price
from .....core.taxes import TaxError, zero_taxed_money
-from .....discount import DiscountType, DiscountValueType
+from .....discount import DiscountType, DiscountValueType, RewardType, RewardValueType
from .....discount.models import VoucherChannelListing, VoucherCustomer
from .....order import OrderStatus
from .....order import events as order_events
@@ -18,6 +19,7 @@ from .....order.models import Order, OrderEvent
from .....payment.model_helpers import get_subtotal
from .....product.models import ProductVariant
from .....tax import TaxCalculationStrategy
+from .....tests.utils import round_up
from ....tests.utils import assert_no_permission, get_graphql_content
DRAFT_ORDER_CREATE_MUTATION = """
@@ -40,6 +42,14 @@ DRAFT_ORDER_CREATE_MUTATION = """
amount
}
discountName
+ discounts {
+ amount {
+ amount
+ }
+ valueType
+ type
+ reason
+ }
redirectUrl
lines {
productName
@@ -116,6 +126,7 @@ DRAFT_ORDER_CREATE_MUTATION = """
unitDiscountReason
unitDiscountType
unitDiscountValue
+ isGift
}
}
}
@@ -2289,7 +2300,7 @@ def test_draft_order_create_with_custom_price_in_order_line(
assert order_line_1.undiscounted_base_unit_price_amount == expected_price_variant_1
-def test_draft_order_create_product_on_promotion(
+def test_draft_order_create_product_catalogue_promotion(
staff_api_client,
permission_group_manage_orders,
staff_user,
@@ -2415,7 +2426,7 @@ def test_draft_order_create_product_on_promotion(
assert event_parameters["lines"][0]["quantity"] == quantity
-def test_draft_order_create_product_on_promotion_flat_taxes(
+def test_draft_order_create_product_catalogue_promotion_flat_taxes(
staff_api_client,
permission_group_manage_orders,
staff_user,
@@ -2544,3 +2555,247 @@ def test_draft_order_create_product_on_promotion_flat_taxes(
assert event_parameters["lines"][0]["item"] == str(order_lines[0])
assert event_parameters["lines"][0]["line_pk"] == str(order_lines[0].pk)
assert event_parameters["lines"][0]["quantity"] == quantity
+
+
+def test_draft_order_create_order_promotion_flat_rates(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ graphql_address_data,
+ order_promotion_rule,
+ variant_with_many_stocks,
+ channel_USD,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ currency = channel_USD.currency_code
+
+ tc = channel_USD.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.prices_entered_with_tax = False
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ rule = order_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ assert rule.reward_value_type == RewardValueType.PERCENTAGE
+ reward_value = rule.reward_value
+ assert rule.reward_value == Decimal("25")
+
+ variant = variant_with_many_stocks
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ quantity = 4
+ variant_list = [
+ {"variantId": variant_id, "quantity": quantity},
+ ]
+
+ # calculate expected values
+ variant_price = variant.channel_listings.get(
+ channel=channel_USD
+ ).discounted_price_amount
+ undiscounted_subtotal_net = Decimal(quantity * variant_price)
+ discount_amount = quantize_price(
+ reward_value / 100 * undiscounted_subtotal_net, currency
+ )
+ subtotal_net = undiscounted_subtotal_net - discount_amount
+ subtotal_gross = quantize_price(tax_rate * subtotal_net, currency)
+ shipping_price_net = shipping_method.channel_listings.get(
+ channel=channel_USD
+ ).price_amount
+ shipping_price_gross = quantize_price(tax_rate * shipping_price_net, currency)
+ total_gross = quantize_price(subtotal_gross + shipping_price_gross, currency)
+
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ order = content["data"]["draftOrderCreate"]["order"]
+ assert order["status"] == OrderStatus.DRAFT.upper()
+ assert order["subtotal"]["gross"]["amount"] == float(subtotal_gross)
+ assert order["total"]["gross"]["amount"] == float(total_gross)
+ assert order["shippingPrice"]["gross"]["amount"] == float(shipping_price_gross)
+
+ assert len(order["discounts"]) == 1
+ assert order["discounts"][0]["amount"]["amount"] == discount_amount
+ assert order["discounts"][0]["reason"] == f"Promotion: {promotion_id}"
+ assert order["discounts"][0]["type"] == DiscountType.ORDER_PROMOTION.upper()
+ assert order["discounts"][0]["valueType"] == RewardValueType.PERCENTAGE.upper()
+
+ assert len(order["lines"]) == 1
+ assert order["lines"][0]["quantity"] == quantity
+ assert order["lines"][0]["totalPrice"]["gross"]["amount"] == float(subtotal_gross)
+ assert order["lines"][0]["undiscountedUnitPrice"]["gross"]["amount"] == float(
+ quantize_price(undiscounted_subtotal_net * tax_rate / quantity, currency)
+ )
+ assert order["lines"][0]["unitPrice"]["gross"]["amount"] == float(
+ round_up(subtotal_gross / quantity)
+ )
+
+ order_db = Order.objects.get()
+ assert order_db.total_gross_amount == total_gross
+ assert order_db.subtotal_gross_amount == subtotal_gross
+ assert order_db.shipping_price_gross_amount == shipping_price_gross
+
+ line_db = order_db.lines.get()
+ assert line_db.total_price_gross_amount == subtotal_gross
+ assert line_db.undiscounted_unit_price_gross_amount == quantize_price(
+ undiscounted_subtotal_net * tax_rate / quantity, currency
+ )
+ assert line_db.unit_price_net_amount == quantize_price(
+ subtotal_net / quantity, currency
+ )
+ assert line_db.unit_price_gross_amount == round_up(subtotal_gross / quantity)
+
+ discount_db = order_db.discounts.get()
+ assert discount_db.amount_value == discount_amount
+ assert discount_db.reason == f"Promotion: {promotion_id}"
+ assert discount_db.value == reward_value
+ assert discount_db.value_type == RewardValueType.PERCENTAGE
+
+
+def test_draft_order_create_gift_promotion_flat_rates(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ graphql_address_data,
+ gift_promotion_rule,
+ variant_with_many_stocks,
+ channel_USD,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ currency = channel_USD.currency_code
+
+ tc = channel_USD.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.prices_entered_with_tax = False
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ rule = gift_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ assert rule.reward_type == RewardType.GIFT
+
+ variant = variant_with_many_stocks
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ quantity = 4
+ variant_list = [
+ {"variantId": variant_id, "quantity": quantity},
+ ]
+
+ # calculate expected values
+ variant_price = variant.channel_listings.get(
+ channel=channel_USD
+ ).discounted_price_amount
+ subtotal_net = quantity * variant_price
+ subtotal_gross = quantize_price(tax_rate * subtotal_net, currency)
+ shipping_price_net = shipping_method.channel_listings.get(
+ channel=channel_USD
+ ).price_amount
+ shipping_price_gross = quantize_price(tax_rate * shipping_price_net, currency)
+ total_gross = quantize_price(subtotal_gross + shipping_price_gross, currency)
+
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "channelId": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ order = content["data"]["draftOrderCreate"]["order"]
+
+ assert order["status"] == OrderStatus.DRAFT.upper()
+ assert order["subtotal"]["gross"]["amount"] == float(subtotal_gross)
+ assert Decimal(order["total"]["gross"]["amount"]) == float(total_gross)
+ assert Decimal(order["shippingPrice"]["gross"]["amount"]) == float(
+ shipping_price_gross
+ )
+
+ assert not order["discounts"]
+
+ assert len(order["lines"]) == 2
+ line = [line for line in order["lines"] if line["quantity"] == 4][0]
+ gift_line = [line for line in order["lines"] if line["isGift"]][0]
+
+ assert line["totalPrice"]["gross"]["amount"] == float(subtotal_gross)
+ assert line["undiscountedUnitPrice"]["gross"]["amount"] == float(
+ subtotal_gross / quantity
+ )
+ assert line["unitPrice"]["gross"]["amount"] == float(subtotal_gross / quantity)
+ assert line["unitDiscount"]["amount"] == 0.00
+
+ order_db = Order.objects.get()
+ assert order_db.total_gross_amount == total_gross
+ assert order_db.subtotal_gross_amount == subtotal_gross
+ assert order_db.shipping_price_gross_amount == shipping_price_gross
+
+ lines_db = order_db.lines.all()
+ assert len(lines_db) == 2
+ gift_line_db = [line for line in lines_db if line.is_gift][0]
+ gift_price = gift_line_db.variant.channel_listings.get(
+ channel=channel_USD
+ ).price_amount
+
+ assert gift_line_db.total_price_gross_amount == Decimal(0)
+ assert gift_line_db.undiscounted_unit_price_gross_amount == Decimal(0)
+ assert gift_line_db.unit_price_gross_amount == Decimal(0)
+ assert gift_line_db.base_unit_price_amount == Decimal(0)
+ assert gift_line_db.unit_discount_value == gift_price
+
+ assert gift_line["totalPrice"]["gross"]["amount"] == 0.00
+ assert gift_line["undiscountedUnitPrice"]["gross"]["amount"] == 0.00
+ assert gift_line["unitPrice"]["gross"]["amount"] == 0.00
+ assert gift_line["unitDiscount"]["amount"] == gift_price
+ assert gift_line["unitDiscountReason"] == f"Promotion: {promotion_id}"
+ assert gift_line["unitDiscountType"] == RewardValueType.FIXED.upper()
+ assert gift_line["unitDiscountValue"] == gift_price
+
+ discount_db = gift_line_db.discounts.get()
+ assert discount_db.amount_value == gift_price
+ assert discount_db.reason == f"Promotion: {promotion_id}"
+ assert discount_db.type == DiscountType.ORDER_PROMOTION
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 e568cc5c84..3670562fb3 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -1,9 +1,10 @@
import graphene
+import pytest
from prices import TaxedMoney
from .....core.prices import quantize_price
from .....core.taxes import zero_money
-from .....discount import DiscountType, DiscountValueType
+from .....discount import DiscountType, DiscountValueType, RewardValueType
from .....order import OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
@@ -66,16 +67,58 @@ DRAFT_ORDER_UPDATE_MUTATION = """
gross {
amount
}
+ net {
+ amount
+ }
}
subtotal {
gross {
amount
}
+ net {
+ amount
+ }
}
undiscountedTotal {
gross {
amount
}
+ net {
+ amount
+ }
+ }
+ discounts {
+ amount {
+ amount
+ }
+ valueType
+ type
+ reason
+ }
+ lines {
+ quantity
+ unitDiscount {
+ amount
+ }
+ undiscountedUnitPrice {
+ net {
+ amount
+ }
+ }
+ unitPrice {
+ net {
+ amount
+ }
+ }
+ totalPrice {
+ net {
+ amount
+ }
+ }
+ unitDiscountReason
+ unitDiscountType
+ unitDiscountValue
+ isGift
}
}
}
@@ -537,6 +580,234 @@ def test_draft_order_update_voucher_including_drafts_in_voucher_usage_invalid_co
assert error["field"] == "voucher"
+def test_draft_order_update_add_voucher_code_remove_order_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines_and_order_promotion,
+ voucher,
+):
+ # given
+ order = order_with_lines_and_order_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ order_discount = order.discounts.get()
+ assert order_discount.type == DiscountType.ORDER_PROMOTION
+
+ discount_amount = voucher.channel_listings.get(channel=order.channel).discount_value
+
+ 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)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": voucher.codes.first().code,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ with pytest.raises(order_discount._meta.model.DoesNotExist):
+ order_discount.refresh_from_db()
+
+ order.refresh_from_db()
+ voucher_discount = order.discounts.get()
+ assert voucher_discount.amount_value == discount_amount
+ assert voucher_discount.value == discount_amount
+ assert voucher_discount.type == DiscountType.VOUCHER
+
+ assert (
+ order.total_net_amount == order.undiscounted_total_net_amount - discount_amount
+ )
+
+
+def test_draft_order_update_add_voucher_code_remove_gift_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines_and_gift_promotion,
+ voucher,
+):
+ # given
+ order = order_with_lines_and_gift_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ assert order.lines.count() == 3
+ gift_line = order.lines.get(is_gift=True)
+ gift_discount = gift_line.discounts.get()
+
+ discount_amount = voucher.channel_listings.get(channel=order.channel).discount_value
+
+ 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)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": voucher.codes.first().code,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ with pytest.raises(gift_line._meta.model.DoesNotExist):
+ gift_line.refresh_from_db()
+
+ with pytest.raises(gift_discount._meta.model.DoesNotExist):
+ gift_discount.refresh_from_db()
+
+ order.refresh_from_db()
+ assert order.lines.count() == 2
+ voucher_discount = order.discounts.get()
+ assert voucher_discount.amount_value == discount_amount
+ assert voucher_discount.value == discount_amount
+ assert voucher_discount.type == DiscountType.VOUCHER
+
+ assert (
+ order.total_net_amount == order.undiscounted_total_net_amount - discount_amount
+ )
+
+
+def test_draft_order_update_remove_voucher_code_add_order_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+ order_promotion_rule,
+):
+ # 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
+ voucher_discount = 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)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": None,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ with pytest.raises(voucher_discount._meta.model.DoesNotExist):
+ voucher_discount.refresh_from_db()
+
+ order.refresh_from_db()
+ order_discount = order.discounts.get()
+ reward_value = order_promotion_rule.reward_value
+ assert order_discount.value == reward_value
+ assert order_discount.value_type == order_promotion_rule.reward_value_type
+
+ undiscounted_subtotal = (
+ order.undiscounted_total_net_amount - order.base_shipping_price_amount
+ )
+ assert order_discount.amount.amount == reward_value / 100 * undiscounted_subtotal
+ assert (
+ order.total_net_amount
+ == order.undiscounted_total_net_amount - order_discount.amount.amount
+ )
+
+
+def test_draft_order_update_remove_voucher_code_add_gift_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ voucher,
+ gift_promotion_rule,
+):
+ # given
+ order = draft_order
+ order.voucher = voucher
+ order.save(update_fields=["voucher"])
+ assert order.lines.count() == 2
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = voucher_listing.discount_value
+ voucher_discount = 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)
+
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": None,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ with pytest.raises(voucher_discount._meta.model.DoesNotExist):
+ voucher_discount.refresh_from_db()
+
+ order.refresh_from_db()
+ assert order.lines.count() == 3
+ assert not order.discounts.exists()
+
+ gift_line = order.lines.filter(is_gift=True).first()
+ gift_discount = gift_line.discounts.get()
+ gift_price = gift_line.variant.channel_listings.get(
+ channel=order.channel
+ ).price_amount
+
+ assert gift_discount.value == gift_price
+ assert gift_discount.amount.amount == gift_price
+ assert gift_discount.value_type == DiscountValueType.FIXED
+
+ assert order.total_net_amount == order.undiscounted_total_net_amount
+
+
def test_draft_order_update_with_non_draft_order(
staff_api_client, permission_group_manage_orders, order_with_lines, voucher
):
@@ -1163,3 +1434,115 @@ def test_draft_order_update_no_shipping_method_channel_listings(
assert len(errors) == 1
assert errors[0]["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name
assert errors[0]["field"] == "shippingMethod"
+
+
+def test_draft_order_update_order_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ graphql_address_data,
+ variant_with_many_stocks,
+ channel_USD,
+ draft_order,
+ order_promotion_rule,
+):
+ # given
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ rule = order_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ assert rule.reward_value_type == RewardValueType.PERCENTAGE
+ reward_value = rule.reward_value
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", draft_order.pk),
+ "input": {
+ "billingAddress": graphql_address_data,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderUpdate"]["errors"]
+ draft_order.refresh_from_db()
+ undiscounted_total = draft_order.undiscounted_total_net_amount
+ shipping_price = draft_order.base_shipping_price_amount
+ order = content["data"]["draftOrderUpdate"]["order"]
+ assert len(order["discounts"]) == 1
+ discount_amount = reward_value / 100 * (undiscounted_total - shipping_price)
+ assert order["discounts"][0]["amount"]["amount"] == discount_amount
+ assert order["discounts"][0]["reason"] == f"Promotion: {promotion_id}"
+ assert order["discounts"][0]["type"] == DiscountType.ORDER_PROMOTION.upper()
+ assert order["discounts"][0]["valueType"] == RewardValueType.PERCENTAGE.upper()
+
+ assert (
+ order["subtotal"]["net"]["amount"]
+ == undiscounted_total - discount_amount - shipping_price
+ )
+ assert order["total"]["net"]["amount"] == undiscounted_total - discount_amount
+ assert order["undiscountedTotal"]["net"]["amount"] == undiscounted_total
+
+
+def test_draft_order_update_gift_promotion(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ graphql_address_data,
+ variant_with_many_stocks,
+ channel_USD,
+ draft_order,
+ gift_promotion_rule,
+):
+ # given
+ query = DRAFT_ORDER_UPDATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ rule = gift_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", draft_order.pk),
+ "input": {
+ "billingAddress": graphql_address_data,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderUpdate"]["errors"]
+
+ gift_line_db = [line for line in draft_order.lines.all() if line.is_gift][0]
+ gift_price = gift_line_db.variant.channel_listings.get(
+ channel=draft_order.channel
+ ).price_amount
+
+ order = content["data"]["draftOrderUpdate"]["order"]
+ lines = order["lines"]
+ assert len(lines) == 3
+ gift_line = [line for line in lines if line["isGift"]][0]
+
+ assert gift_line["totalPrice"]["net"]["amount"] == 0.00
+ assert gift_line["unitDiscount"]["amount"] == gift_price
+ assert gift_line["unitDiscountReason"] == f"Promotion: {promotion_id}"
+ assert gift_line["unitDiscountType"] == RewardValueType.FIXED.upper()
+ assert gift_line["unitDiscountValue"] == gift_price
+
+ assert (
+ order["subtotal"]["net"]["amount"]
+ == draft_order.undiscounted_total_net_amount
+ - draft_order.base_shipping_price_amount
+ )
+ assert order["total"]["net"]["amount"] == draft_order.undiscounted_total_net_amount
+ assert (
+ order["undiscountedTotal"]["net"]["amount"]
+ == draft_order.undiscounted_total_net_amount
+ )
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index 9ac84ea929..e33cdcbca4 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -7,7 +7,7 @@ import pytest
from prices import Money, TaxedMoney, fixed_discount, percentage_discount
from .....core.prices import quantize_price
-from .....discount import DiscountValueType
+from .....discount import DiscountType, DiscountValueType
from .....order import OrderEvents, OrderStatus
from .....order.error_codes import OrderErrorCode
from .....order.interface import OrderTaxedPricesData
@@ -280,6 +280,116 @@ def test_add_fixed_order_discount_to_order_by_app(
assert discount_data["amount_value"] == str(order_discount.amount.amount)
+def test_add_manual_discount_to_order_with_order_discount(
+ order_with_lines_and_order_promotion,
+ staff_api_client,
+ permission_group_manage_orders,
+):
+ """Order discount should be deleted in a favour of manual discount."""
+ # given
+ order = order_with_lines_and_order_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ order_discount = order.discounts.get()
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ discount_value = Decimal("10.00")
+
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": discount_value,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderDiscountAdd"]
+ order.refresh_from_db()
+ assert not data["errors"]
+
+ with pytest.raises(order_discount._meta.model.DoesNotExist):
+ order_discount.refresh_from_db()
+
+ assert order.discounts.count() == 1
+ manual_discount = order.discounts.get()
+
+ assert manual_discount.value == discount_value
+ assert manual_discount.value_type == DiscountValueType.FIXED
+ assert manual_discount.amount.amount == discount_value
+
+ assert (
+ order.total_net_amount == order.undiscounted_total_net_amount - discount_value
+ )
+ assert (
+ order.shipping_price_net_amount + order.subtotal_net_amount
+ == order.total_net_amount
+ )
+
+
+def test_add_manual_discount_to_order_with_gift_discount(
+ order_with_lines_and_gift_promotion,
+ staff_api_client,
+ permission_group_manage_orders,
+):
+ """Order discount should be deleted in a favour of manual discount."""
+ # given
+ order = order_with_lines_and_gift_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ assert order.lines.count() == 3
+ gift_line = order.lines.filter(is_gift=True).first()
+ gift_discount = gift_line.discounts.get()
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ discount_value = Decimal("10.00")
+
+ variables = {
+ "orderId": graphene.Node.to_global_id("Order", order.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": discount_value,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_ADD, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderDiscountAdd"]
+ order.refresh_from_db()
+ assert not data["errors"]
+
+ assert order.lines.count() == 2
+
+ with pytest.raises(gift_line._meta.model.DoesNotExist):
+ gift_line.refresh_from_db()
+
+ with pytest.raises(gift_discount._meta.model.DoesNotExist):
+ gift_discount.refresh_from_db()
+
+ assert order.discounts.count() == 1
+ manual_discount = order.discounts.get()
+
+ assert manual_discount.value == discount_value
+ assert manual_discount.value_type == DiscountValueType.FIXED
+ assert manual_discount.amount.amount == discount_value
+
+ assert (
+ order.total_net_amount == order.undiscounted_total_net_amount - discount_value
+ )
+ assert (
+ order.shipping_price_net_amount + order.subtotal_net_amount
+ == order.total_net_amount
+ )
+
+
ORDER_DISCOUNT_UPDATE = """
mutation OrderDiscountUpdate($discountId: ID!, $input: OrderDiscountCommonInput!){
orderDiscountUpdate(discountId:$discountId, input: $input){
@@ -598,6 +708,9 @@ mutation OrderDiscountDelete($discountId: ID!){
orderDiscountDelete(discountId: $discountId){
order{
id
+ discounts {
+ id
+ }
}
errors{
field
@@ -642,8 +755,8 @@ def test_delete_order_discount_from_order(
errors = data["errors"]
assert len(errors) == 0
- assert order.undiscounted_total == current_undiscounted_total
- assert order.total == current_undiscounted_total
+ assert order.undiscounted_total.net == current_undiscounted_total.net
+ assert order.total.net == current_undiscounted_total.net
event = order.events.get()
assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
@@ -747,8 +860,8 @@ def test_delete_order_discount_from_order_by_app(
errors = data["errors"]
assert len(errors) == 0
- assert order.undiscounted_total == current_undiscounted_total
- assert order.total == current_undiscounted_total
+ assert order.undiscounted_total.net == current_undiscounted_total.net
+ assert order.total.net == current_undiscounted_total.net
event = order.events.get()
assert event.type == OrderEvents.ORDER_DISCOUNT_DELETED
@@ -756,6 +869,92 @@ def test_delete_order_discount_from_order_by_app(
assert order.search_vector
+def test_delete_manual_discount_from_order_with_subtotal_promotion(
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_promotion_rule,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ manual_discount = draft_order_with_fixed_discount_order.discounts.get()
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", manual_discount.pk),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderDiscountDelete"]
+ assert not data["errors"]
+
+ with pytest.raises(manual_discount._meta.model.DoesNotExist):
+ manual_discount.refresh_from_db()
+
+ order.refresh_from_db()
+ order_discount = order.discounts.get()
+ reward_value = order_promotion_rule.reward_value
+ assert order_discount.value == reward_value
+ assert order_discount.value_type == order_promotion_rule.reward_value_type
+
+ undiscounted_subtotal = (
+ order.undiscounted_total_net_amount - order.base_shipping_price_amount
+ )
+ assert order_discount.amount.amount == reward_value / 100 * undiscounted_subtotal
+ assert (
+ order.total_net_amount
+ == order.undiscounted_total_net_amount - order_discount.amount.amount
+ )
+
+
+def test_delete_manual_discount_from_order_with_gift_promotion(
+ draft_order_with_fixed_discount_order,
+ staff_api_client,
+ permission_group_manage_orders,
+ gift_promotion_rule,
+):
+ # given
+ order = draft_order_with_fixed_discount_order
+ manual_discount = draft_order_with_fixed_discount_order.discounts.get()
+ assert order.lines.count() == 2
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variables = {
+ "discountId": graphene.Node.to_global_id("OrderDiscount", manual_discount.pk),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_DISCOUNT_DELETE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderDiscountDelete"]
+ assert not data["errors"]
+
+ with pytest.raises(manual_discount._meta.model.DoesNotExist):
+ manual_discount.refresh_from_db()
+
+ order.refresh_from_db()
+ assert order.lines.count() == 3
+ assert not order.discounts.exists()
+
+ gift_line = order.lines.filter(is_gift=True).first()
+ gift_discount = gift_line.discounts.get()
+ gift_price = gift_line.variant.channel_listings.get(
+ channel=order.channel
+ ).price_amount
+
+ assert gift_discount.value == gift_price
+ assert gift_discount.amount.amount == gift_price
+ assert gift_discount.value_type == DiscountValueType.FIXED
+
+ assert order.total_net_amount == order.undiscounted_total_net_amount
+
+
ORDER_LINE_DISCOUNT_UPDATE = """
mutation OrderLineDiscountUpdate($input: OrderDiscountCommonInput!, $orderLineId: ID!){
orderLineDiscountUpdate(orderLineId: $orderLineId, input: $input){
@@ -798,14 +997,23 @@ def test_update_order_line_discount(
line_to_discount.undiscounted_total_price = total_price
line_to_discount.save()
+ line_to_discount.discounts.create(
+ value_type="fixed",
+ value=0,
+ amount_value=0,
+ name="Manual line discount",
+ type="manual",
+ )
+
line_price_before_discount = line_to_discount.unit_price
value = Decimal("5")
+ value_type = DiscountValueTypeEnum.FIXED
reason = "New reason for unit discount"
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),
"input": {
- "valueType": DiscountValueTypeEnum.FIXED.name,
+ "valueType": value_type.name,
"value": value,
"reason": reason,
},
@@ -866,9 +1074,16 @@ def test_update_order_line_discount(
discount_data = line_data.get("discount")
assert discount_data["value"] == str(value)
- assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
+ assert discount_data["value_type"] == value_type.value
assert discount_data["amount_value"] == str(unit_discount.amount)
+ line_discount = line_to_discount.discounts.get()
+ assert line_discount.type == DiscountType.MANUAL
+ assert line_discount.value == value
+ assert line_discount.value_type == value_type.value
+ assert line_discount.reason == reason
+ assert line_discount.amount_value == value * line_to_discount.quantity
+
def test_update_order_line_discount_by_user_no_channel_access(
draft_order_with_fixed_discount_order,
@@ -916,11 +1131,12 @@ def test_update_order_line_discount_by_app(
line_to_discount = order.lines.first()
value = Decimal("5")
+ value_type = DiscountValueTypeEnum.FIXED
reason = "New reason for unit discount"
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),
"input": {
- "valueType": DiscountValueTypeEnum.FIXED.name,
+ "valueType": value_type.name,
"value": value,
"reason": reason,
},
@@ -953,9 +1169,16 @@ def test_update_order_line_discount_by_app(
discount_data = line_data.get("discount")
assert discount_data["value"] == str(value)
- assert discount_data["value_type"] == DiscountValueTypeEnum.FIXED.value
+ assert discount_data["value_type"] == value_type.value
assert discount_data["amount_value"] == str(unit_discount.amount)
+ line_discount = line_to_discount.discounts.get()
+ assert line_discount.type == DiscountType.MANUAL
+ assert line_discount.value == value
+ assert line_discount.value_type == value_type.value
+ assert line_discount.reason == reason
+ assert line_discount.amount_value == value * line_to_discount.quantity
+
@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
def test_update_order_line_discount_line_with_discount(
@@ -1002,11 +1225,12 @@ def test_update_order_line_discount_line_with_discount(
line_undiscounted_price = line_to_discount.undiscounted_unit_price
value = Decimal("50")
+ value_type = DiscountValueTypeEnum.PERCENTAGE
reason = "New reason for unit discount"
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line_to_discount.pk),
"input": {
- "valueType": DiscountValueTypeEnum.PERCENTAGE.name,
+ "valueType": value_type.name,
"value": value,
"reason": reason,
},
@@ -1022,7 +1246,6 @@ def test_update_order_line_discount_line_with_discount(
data = content["data"]["orderLineDiscountUpdate"]
line_to_discount.refresh_from_db()
-
errors = data["errors"]
assert not errors
@@ -1047,13 +1270,64 @@ def test_update_order_line_discount_line_with_discount(
discount_data = line_data.get("discount")
assert discount_data["value"] == str(value)
- assert discount_data["value_type"] == DiscountValueTypeEnum.PERCENTAGE.value
+ assert discount_data["value_type"] == value_type.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)
+ line_discount = line_to_discount.discounts.get()
+ assert line_discount.type == DiscountType.MANUAL
+ assert line_discount.value == value
+ assert line_discount.value_type == value_type.value
+ assert line_discount.reason == reason
+ assert (
+ line_discount.amount_value
+ == line_to_discount.unit_discount_amount * line_to_discount.quantity
+ )
+
+
+def test_update_order_line_discount_line_with_catalogue_promotion(
+ order_with_lines_and_catalogue_promotion,
+ staff_api_client,
+ permission_group_manage_orders,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ line = order.lines.get(quantity=3)
+ assert line.discounts.filter(type=DiscountType.PROMOTION).exists()
+
+ value = Decimal("5")
+ value_type = DiscountValueTypeEnum.FIXED
+ reason = "Manual fixed line discount"
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
+ "input": {
+ "valueType": value_type.name,
+ "value": value,
+ "reason": reason,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDiscountUpdate"]
+ assert not data["errors"]
+
+ line_discount = line.discounts.get()
+ assert line_discount.type == DiscountType.MANUAL
+ assert line_discount.value == value
+ assert line_discount.value_type == value_type.value
+ assert line_discount.reason == reason
+ assert line_discount.amount_value == value * line.quantity
+
def test_update_order_line_discount_order_is_not_draft(
draft_order_with_fixed_discount_order,
@@ -1141,6 +1415,13 @@ def test_delete_discount_from_order_line(
line.unit_discount_value = Decimal("2.5")
line.save()
+ line.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=Decimal("2.5"),
+ currency=order.currency,
+ )
+
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
}
@@ -1169,6 +1450,8 @@ def test_delete_discount_from_order_line(
line_data = lines[0]
assert line_data.get("line_pk") == str(line.pk)
+ assert not line.discounts.exists()
+
@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_unit")
@patch("saleor.plugins.manager.PluginsManager.calculate_order_line_total")
@@ -1254,6 +1537,13 @@ def test_delete_discount_from_order_line_by_app(
line.unit_discount_value = Decimal("2.5")
line.save()
+ line.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=Decimal("2.5"),
+ currency=order.currency,
+ )
+
variables = {
"orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
}
@@ -1287,6 +1577,8 @@ def test_delete_discount_from_order_line_by_app(
line_data = lines[0]
assert line_data.get("line_pk") == str(line.pk)
+ assert not line.discounts.exists()
+
def test_delete_order_line_discount_order_is_not_draft(
draft_order_with_fixed_discount_order,
@@ -1321,3 +1613,42 @@ def test_delete_order_line_discount_order_is_not_draft(
assert error["code"] == OrderErrorCode.CANNOT_DISCOUNT.name
assert line.unit_discount_amount == Decimal("2.5")
+
+
+def test_delete_order_line_discount_line_with_catalogue_promotion(
+ order_with_lines,
+ staff_api_client,
+ permission_group_manage_orders,
+ catalogue_promotion,
+):
+ # given
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ line = order.lines.get(quantity=3)
+
+ manual_reward_value = Decimal(1)
+ line.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.FIXED,
+ value=manual_reward_value,
+ amount_value=manual_reward_value * line.quantity,
+ currency=order.currency,
+ reason="Manual line discount",
+ )
+
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", line.pk),
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_REMOVE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineDiscountRemove"]
+ assert not data["errors"]
+ # Deleting manual discount should result in creating catalogue discount in this case
+ # https://github.com/saleor/saleor/issues/15517
+ # assert line.discounts.filter(type=DiscountType.PROMOTION).exists()
diff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.py
index 9a9e09697c..19ad0526f9 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py
@@ -1,8 +1,10 @@
+from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
+from .....discount import DiscountType, RewardValueType
from .....order import OrderStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
@@ -24,6 +26,12 @@ ORDER_LINE_UPDATE_MUTATION = """
orderLine {
id
quantity
+ unitDiscount {
+ amount
+ }
+ unitDiscountType
+ unitDiscountValue
+ isGift
}
order {
total {
@@ -31,6 +39,11 @@ ORDER_LINE_UPDATE_MUTATION = """
amount
}
}
+ discounts {
+ amount {
+ amount
+ }
+ }
}
}
}
@@ -417,3 +430,97 @@ def test_order_line_update_quantity_gift(
assert len(errors) == 1
assert errors[0]["field"] == "id"
assert errors[0]["code"] == OrderErrorCode.NON_EDITABLE_GIFT_LINE.name
+
+
+def test_order_line_update_order_promotion(
+ draft_order,
+ staff_api_client,
+ permission_group_manage_orders,
+ order_promotion_rule,
+):
+ # given
+ query = ORDER_LINE_UPDATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+
+ rule = order_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ reward_value = Decimal("25")
+ assert rule.reward_value == reward_value
+ assert rule.reward_value_type == RewardValueType.PERCENTAGE
+
+ order.lines.last().delete()
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variant = line.variant
+ variant_channel_listing = variant.channel_listings.get(channel=order.channel)
+ quantity = 4
+ undiscounted_subtotal = quantity * variant_channel_listing.discounted_price_amount
+ expected_discount = round(reward_value / 100 * undiscounted_subtotal, 2)
+
+ variables = {"lineId": line_id, "quantity": quantity}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineUpdate"]
+
+ discounts = data["order"]["discounts"]
+ assert len(discounts) == 1
+ assert discounts[0]["amount"]["amount"] == expected_discount
+
+ discount_db = order.discounts.get()
+ assert discount_db.promotion_rule == rule
+ assert discount_db.amount_value == expected_discount
+ assert discount_db.type == DiscountType.ORDER_PROMOTION
+ assert discount_db.reason == f"Promotion: {promotion_id}"
+
+
+def test_order_line_update_gift_promotion(
+ draft_order,
+ staff_api_client,
+ permission_group_manage_orders,
+ gift_promotion_rule,
+):
+ # given
+ query = ORDER_LINE_UPDATE_MUTATION
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+ rule = gift_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+
+ order.lines.last().delete()
+ line = order.lines.first()
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ quantity = 4
+
+ variables = {"lineId": line_id, "quantity": quantity}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderLineUpdate"]
+
+ line = data["orderLine"]
+ assert line["quantity"] == quantity
+ assert line["unitDiscount"]["amount"] == 0
+ assert line["unitDiscountValue"] == 0
+
+ gift_line_db = order.lines.get(is_gift=True)
+ gift_price = gift_line_db.variant.channel_listings.get(
+ channel=order.channel
+ ).price_amount
+ assert gift_line_db.unit_discount_amount == gift_price
+ assert gift_line_db.unit_price_gross_amount == Decimal(0)
+
+ assert not data["order"]["discounts"]
+
+ discount = gift_line_db.discounts.get()
+ assert discount.promotion_rule == rule
+ assert discount.amount_value == gift_price
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.reason == f"Promotion: {promotion_id}"
diff --git a/saleor/graphql/order/tests/mutations/test_order_lines_create.py b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
index da5680b589..9c320976a7 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -57,6 +57,12 @@ ORDER_LINES_CREATE_MUTATION = """
currency
}
}
+ unitDiscount {
+ amount
+ }
+ unitDiscountType
+ unitDiscountValue
+ isGift
}
order {
total {
@@ -64,6 +70,11 @@ ORDER_LINES_CREATE_MUTATION = """
amount
}
}
+ discounts {
+ amount {
+ amount
+ }
+ }
}
}
}
@@ -611,7 +622,6 @@ def test_order_lines_create_variant_on_promotion(
line_data = data["orderLines"][0]
assert line_data["productSku"] == variant.sku
assert line_data["quantity"] == quantity
- assert line_data["quantity"] == quantity
assert (
line_data["unitPrice"]["gross"]["amount"]
@@ -644,6 +654,152 @@ def test_order_lines_create_variant_on_promotion(
)
[email protected]("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_lines_create_order_promotion(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ status,
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ variant_with_many_stocks,
+ order_promotion_rule,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ order.lines.all().delete()
+
+ rule = order_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ assert rule.reward_value_type == RewardValueType.PERCENTAGE
+ assert rule.reward_value == Decimal("25")
+
+ variant = variant_with_many_stocks
+ quantity = 5
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variant_channel_listing = variant.channel_listings.get(channel=order.channel)
+ expected_discount = round(
+ quantity * variant_channel_listing.discounted_price.amount * Decimal(0.25), 2
+ )
+ expected_unit_discount = round(expected_discount / quantity, 2)
+
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_proper_webhook_called_once(
+ order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ )
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+
+ line_data = data["orderLines"][0]
+ assert line_data["productSku"] == variant.sku
+ assert line_data["quantity"] == quantity
+ assert line_data["unitDiscount"]["amount"] == 0.00
+ assert (
+ line_data["unitPrice"]["gross"]["amount"]
+ == variant_channel_listing.price_amount - expected_unit_discount
+ )
+ assert (
+ line_data["unitPrice"]["net"]["amount"]
+ == variant_channel_listing.price_amount - expected_unit_discount
+ )
+
+ line = order.lines.get(product_sku=variant.sku)
+ assert line.unit_discount_amount == 0
+ assert (
+ line.unit_price_gross_amount
+ == variant_channel_listing.discounted_price.amount - expected_unit_discount
+ )
+
+ assert len(data["order"]["discounts"]) == 1
+ discount = data["order"]["discounts"][0]
+ assert discount["amount"]["amount"] == expected_discount
+
+ discount = order.discounts.get()
+ assert discount.promotion_rule == rule
+ assert discount.amount_value == expected_discount
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+
[email protected]("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_lines_create_gift_promotion(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ status,
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ variant_with_many_stocks,
+ gift_promotion_rule,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ order.lines.all().delete()
+
+ rule = gift_promotion_rule
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+
+ variant = variant_with_many_stocks
+ quantity = 5
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": quantity}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ assert_proper_webhook_called_once(
+ order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ )
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+
+ lines = data["orderLines"]
+ # gift line is not returned
+ assert len(lines) == 1
+
+ gift_line_db = order.lines.get(is_gift=True)
+ gift_price = gift_line_db.variant.channel_listings.get(
+ channel=order.channel
+ ).price_amount
+ assert gift_line_db.unit_discount_amount == gift_price
+ assert gift_line_db.unit_price_gross_amount == Decimal(0)
+
+ assert not data["order"]["discounts"]
+
+ discount = gift_line_db.discounts.get()
+ assert discount.promotion_rule == rule
+ assert discount.amount_value == gift_price
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+
@pytest.mark.parametrize("status", [OrderStatus.DRAFT, OrderStatus.UNCONFIRMED])
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
diff --git a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
index d7c15b56ac..de79b9412f 100644
--- a/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
+++ b/saleor/graphql/order/tests/queries/test_draft_order_with_filter.py
@@ -3,6 +3,7 @@ from decimal import Decimal
import graphene
import pytest
+from django.core.exceptions import ValidationError
from freezegun import freeze_time
from .....core.postgres import FlatConcatSearchVector
@@ -13,7 +14,9 @@ from .....order.search import (
prepare_order_search_vector_value,
update_order_search_vector,
)
+from ....core.connection import where_filter_qs
from ....tests.utils import get_graphql_content
+from ...filters import OrderDiscountedObjectWhere
@pytest.fixture
@@ -218,3 +221,243 @@ def test_draft_orders_query_with_filter_search(
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
content = get_graphql_content(response)
assert content["data"]["draftOrders"]["totalCount"] == count
+
+
[email protected](("gte", "count"), [(20, 1), (0, 1), (500, 0), (20.01, 0)])
+def test_draft_orders_query_with_filter_base_total_price_range(draft_order, gte, count):
+ # given
+ order = draft_order
+ currency = order.currency
+ order.total_net_amount = Decimal("20")
+ order.save(update_fields=["total_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "currency": currency,
+ "base_total_price": {
+ "range": {
+ "gte": gte,
+ }
+ },
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == count
+ if count:
+ assert result.first() == order
+
+
[email protected](("gte", "count"), [(20, 1), (0, 1), (500, 0), (20.01, 0)])
+def test_draft_orders_query_with_filter_base_subtotal_price_range(
+ draft_order, gte, count
+):
+ # given
+ order = draft_order
+ currency = order.currency
+ order.subtotal_net_amount = Decimal("20")
+ order.save(update_fields=["subtotal_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "currency": currency,
+ "base_subtotal_price": {
+ "range": {
+ "gte": gte,
+ }
+ },
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == count
+ if count:
+ assert result.first() == order
+
+
+ ("one_of", "count"), [([1, 20, 70], 1), ([3, 20.1], 0), ([-3, 0], 0)]
+)
+def test_draft_orders_query_with_filter_base_total_price_one_of(
+ draft_order, one_of, count
+):
+ # given
+ order = draft_order
+ currency = order.currency
+ order.total_net_amount = Decimal("20")
+ order.save(update_fields=["total_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "currency": currency,
+ "base_total_price": {"one_of": one_of},
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == count
+ if count:
+ assert result.first() == order
+
+
+ ("one_of", "count"), [([1, 20, 70], 1), ([3, 20.1], 0), ([-3, 0], 0)]
+)
+def test_draft_orders_query_with_filter_base_subtotal_price_one_of(
+ draft_order, one_of, count
+):
+ # given
+ order = draft_order
+ currency = order.currency
+ order.subtotal_net_amount = Decimal("20")
+ order.save(update_fields=["subtotal_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "currency": currency,
+ "base_subtotal_price": {"one_of": one_of},
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == count
+ if count:
+ assert result.first() == order
+
+
+def test_draft_orders_query_with_filter_base_total_price_missing_currency(draft_order):
+ # given
+ order = draft_order
+ order.total_net_amount = Decimal("20")
+ order.save(update_fields=["total_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "base_total_price": {
+ "range": {
+ "gte": 20,
+ }
+ },
+ }
+
+ # when
+ with pytest.raises(ValidationError) as validation_error:
+ where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert validation_error.value.code == "required"
+
+
+def test_draft_orders_query_with_filter_base_subtotal_price_missing_currency(
+ draft_order,
+):
+ # given
+ order = draft_order
+ order.subtotal_net_amount = Decimal("20")
+ order.save(update_fields=["subtotal_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "base_subtotal_price": {
+ "range": {
+ "gte": 20,
+ }
+ },
+ }
+
+ # when
+ with pytest.raises(ValidationError) as validation_error:
+ where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert validation_error.value.code == "required"
+
+
+def test_draft_orders_query_with_filter_price_with_and_or(draft_order):
+ # given
+ order = draft_order
+ currency = order.currency
+ order.total_net_amount = Decimal("20")
+ order.save(update_fields=["total_net_amount"])
+
+ qs = Order.objects.all()
+ predicate_data = {
+ "AND": [
+ {
+ "OR": [
+ {
+ "currency": currency,
+ "base_total_price": {
+ "range": {
+ "gte": 20,
+ }
+ },
+ },
+ {
+ "currency": currency,
+ "base_total_price": {
+ "range": {
+ "gte": 10,
+ }
+ },
+ },
+ ]
+ }
+ ],
+ }
+
+ # when
+ result = where_filter_qs(
+ qs,
+ {},
+ OrderDiscountedObjectWhere,
+ predicate_data,
+ None,
+ )
+
+ # then
+ assert result.count() == 1
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index d581bc2853..57154d85fa 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -25,6 +25,7 @@ from ...graphql.order.resolvers import resolve_orders
from ...graphql.utils import get_user_or_app_from_context
from ...graphql.warehouse.dataloaders import StockByIdLoader, WarehouseByIdLoader
from ...order import OrderStatus, calculations, models
+from ...order.calculations import fetch_order_prices_if_expired
from ...order.models import FulfillmentStatus
from ...order.utils import (
get_order_country,
@@ -1526,7 +1527,11 @@ class Order(ModelObjectType[models.Order]):
@staticmethod
def resolve_discounts(root: models.Order, info):
- return OrderDiscountsByOrderIDLoader(info.context).load(root.id)
+ def with_manager(manager):
+ fetch_order_prices_if_expired(root, manager)
+ return OrderDiscountsByOrderIDLoader(info.context).load(root.id)
+
+ return get_plugin_manager_promise(info.context).then(with_manager)
@staticmethod
@traced_resolver
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index 219b77f2c8..e5848c04eb 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -109,6 +109,13 @@ def propagate_order_discount_on_order_prices(
currency=currency,
price_to_discount=subtotal,
)
+ elif order_discount.type == DiscountType.ORDER_PROMOTION:
+ subtotal = apply_discount_to_value(
+ value=order_discount.value,
+ value_type=order_discount.value_type,
+ currency=currency,
+ price_to_discount=subtotal,
+ )
elif order_discount.type == DiscountType.MANUAL:
if order_discount.value_type == DiscountValueType.PERCENTAGE:
subtotal = apply_discount_to_value(
@@ -123,7 +130,7 @@ def propagate_order_discount_on_order_prices(
currency=currency,
price_to_discount=shipping_price,
)
- else:
+ elif order_discount.value_type == DiscountValueType.FIXED:
temporary_undiscounted_total = subtotal + shipping_price
if temporary_undiscounted_total.amount > 0:
temporary_total = apply_discount_to_value(
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index bc23505a2d..4ac30e918f 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -11,6 +11,7 @@ from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.taxes import TaxData, TaxEmptyData, TaxError, zero_taxed_money
from ..discount import DiscountType
+from ..discount.utils import create_or_update_discount_objects_from_promotion_for_order
from ..payment.model_helpers import get_subtotal
from ..plugins import PLUGIN_IDENTIFIER_PREFIX
from ..plugins.manager import PluginsManager
@@ -25,6 +26,7 @@ from ..tax.utils import (
)
from . import ORDER_EDITABLE_STATUS
from .base_calculations import apply_order_discounts, base_order_line_total
+from .fetch import DraftOrderLineInfo, fetch_draft_order_lines_info
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
@@ -49,18 +51,18 @@ def fetch_order_prices_if_expired(
if not force_update and not order.should_refresh_prices:
return order, lines
- if lines is None:
- lines = list(
- order.lines.using(database_connection_name).select_related(
- "variant__product__product_type"
- )
- )
- else:
- prefetch_related_objects(lines, "variant__product__product_type")
+ # handle promotions
+ lines_info: list[DraftOrderLineInfo] = fetch_draft_order_lines_info(order, lines)
+ create_or_update_discount_objects_from_promotion_for_order(
+ order, lines_info, database_connection_name
+ )
+ lines = [line_info.line for line_info in lines_info]
+ _update_order_discount_for_voucher(order)
- order.should_refresh_prices = False
+ _clear_prefetched_discounts(order, lines)
+ prefetch_related_objects([order], "discounts")
- _update_order_discount_for_voucher(order)
+ # handle taxes
_recalculate_prices(
order,
manager,
@@ -68,7 +70,7 @@ def fetch_order_prices_if_expired(
database_connection_name=database_connection_name,
)
- order.subtotal = get_subtotal(lines, order.currency)
+ order.should_refresh_prices = False
with transaction.atomic(savepoint=False):
with allow_writer():
order.save(
@@ -98,6 +100,11 @@ def fetch_order_prices_if_expired(
"undiscounted_total_price_net_amount",
"undiscounted_total_price_gross_amount",
"tax_rate",
+ "unit_discount_amount",
+ "unit_discount_reason",
+ "unit_discount_type",
+ "unit_discount_value",
+ "base_unit_price_amount",
],
)
@@ -128,14 +135,14 @@ def _update_order_discount_for_voucher(order: Order):
voucher_code=order.voucher_code,
)
- # 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 _clear_prefetched_discounts(order, lines):
+ if hasattr(order, "_prefetched_objects_cache"):
+ order._prefetched_objects_cache.pop("discounts", None)
+
+ for line in lines:
+ if hasattr(line, "_prefetched_objects_cache"):
+ line._prefetched_objects_cache.pop("discounts", None)
def _recalculate_prices(
@@ -338,6 +345,7 @@ def _recalculate_with_plugins(
order.undiscounted_total = undiscounted_subtotal + TaxedMoney(
net=order.base_shipping_price, gross=order.base_shipping_price
)
+ order.subtotal = get_subtotal(lines, order.currency)
order.total = manager.calculate_order_total(order, lines, plugin_ids=plugin_ids)
@@ -387,12 +395,14 @@ def _apply_tax_data(
order_line.tax_rate = normalize_tax_rate_for_db(tax_line.tax_rate)
subtotal += line_total_price
+ order.subtotal = subtotal
order.total = shipping_price + subtotal
def _remove_tax(order, lines):
order.total_gross_amount = order.total_net_amount
order.undiscounted_total_gross_amount = order.undiscounted_total_net_amount
+ order.subtotal_gross_amount = order.subtotal_net_amount
order.shipping_price_gross_amount = order.shipping_price_net_amount
order.shipping_tax_rate = Decimal("0.00")
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 9d1b364e4a..5bab6e8ab9 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -1,14 +1,21 @@
from collections.abc import Iterable
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Optional
+from typing import Optional, cast
from uuid import UUID
-if TYPE_CHECKING:
- from ..channel.models import Channel
- from ..discount.models import OrderLineDiscount
- from ..payment.models import Payment
- from ..product.models import DigitalContent, ProductVariant
- from .models import Order, OrderLine
+from django.db.models import prefetch_related_objects
+
+from ..channel.models import Channel
+from ..discount import DiscountType
+from ..discount.interface import VariantPromotionRuleInfo, fetch_variant_rules_info
+from ..discount.models import OrderLineDiscount, Voucher
+from ..payment.models import Payment
+from ..product.models import (
+ DigitalContent,
+ ProductVariant,
+ ProductVariantChannelListing,
+)
+from .models import Order, OrderLine
@dataclass
@@ -63,3 +70,78 @@ def fetch_order_lines(order: "Order") -> list[OrderLineInfo]:
)
return lines_info
+
+
+@dataclass
+class DraftOrderLineInfo:
+ line: "OrderLine"
+ variant: "ProductVariant"
+ channel_listing: "ProductVariantChannelListing"
+ discounts: list["OrderLineDiscount"]
+ rules_info: list["VariantPromotionRuleInfo"]
+ channel: "Channel"
+ voucher: Optional["Voucher"] = None
+
+ def get_promotion_discounts(self) -> list["OrderLineDiscount"]:
+ return [
+ discount
+ for discount in self.discounts
+ if discount.type in [DiscountType.PROMOTION, DiscountType.ORDER_PROMOTION]
+ ]
+
+ def get_catalogue_discounts(self) -> list["OrderLineDiscount"]:
+ return [
+ discount
+ for discount in self.discounts
+ if discount.type == DiscountType.PROMOTION
+ ]
+
+
+def fetch_draft_order_lines_info(
+ order: "Order", lines: Optional[Iterable["OrderLine"]] = None
+) -> list[DraftOrderLineInfo]:
+ prefetch_related_fields = [
+ "discounts__promotion_rule__promotion",
+ "variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations",
+ "variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations",
+ ]
+ if lines is None:
+ lines = list(order.lines.prefetch_related(*prefetch_related_fields))
+ else:
+ prefetch_related_objects(lines, *prefetch_related_fields)
+
+ lines_info = []
+ channel = order.channel
+ for line in lines:
+ variant = cast(ProductVariant, line.variant)
+ variant_channel_listing = get_prefetched_variant_listing(variant, channel.id)
+ if not variant_channel_listing:
+ continue
+
+ rules_info = (
+ fetch_variant_rules_info(variant_channel_listing, order.language_code)
+ if not line.is_gift
+ else []
+ )
+ lines_info.append(
+ DraftOrderLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ discounts=list(line.discounts.all()),
+ rules_info=rules_info,
+ channel=channel,
+ )
+ )
+ return lines_info
+
+
+def get_prefetched_variant_listing(
+ variant: Optional[ProductVariant], channel_id: int
+) -> Optional[ProductVariantChannelListing]:
+ if not variant:
+ return None
+ for channel_listing in variant.channel_listings.all():
+ if channel_listing.channel_id == channel_id:
+ return channel_listing
+ return None
diff --git a/saleor/order/tests/benchmark/__init__.py b/saleor/order/tests/benchmark/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.py
new file mode 100644
index 0000000000..3a2a866ad8
--- /dev/null
+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py
@@ -0,0 +1,144 @@
+from decimal import Decimal
+
+import pytest
+from prices import Money, TaxedMoney
+
+from ....discount import RewardValueType
+from ....discount.models import OrderDiscount, OrderLineDiscount, PromotionRule
+from ....product.models import Product
+from ....product.utils.variant_prices import update_discounted_prices_for_promotion
+from ....product.utils.variants import fetch_variants_for_promotion_rules
+from ....tax import TaxCalculationStrategy
+from ....warehouse.models import Stock
+from ... import OrderStatus
+from ...calculations import fetch_order_prices_if_expired
+from ...models import OrderLine
+
+
+def order_with_lines(order_with_lines):
+ order_with_lines.status = OrderStatus.UNCONFIRMED
+ return order_with_lines
+
+
[email protected]_queries(autouse=False)
+def test_fetch_order_prices_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+ django_assert_num_queries,
+ count_queries,
+):
+ # given
+ OrderLineDiscount.objects.all().delete()
+ order = order_with_lines_and_catalogue_promotion
+ channel = order.channel
+
+ tc = channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+
+ # when
+ with django_assert_num_queries(38):
+ fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+
+
[email protected]_queries(autouse=False)
+def test_fetch_order_prices_multiple_catalogue_discounts(
+ order_with_lines,
+ catalogue_promotion_without_rules,
+ plugins_manager,
+ product_variant_list,
+ django_assert_num_queries,
+ count_queries,
+):
+ # given
+ Stock.objects.update(quantity=100)
+ order = order_with_lines
+ channel = order.channel
+
+ variants = product_variant_list
+ variants.extend(line.variant for line in order.lines.all())
+ variant_global_ids = [variant.get_global_id() for variant in variants]
+
+ # create many rules
+ promotion = catalogue_promotion_without_rules
+ rules = []
+ catalogue_predicate = {"variantPredicate": {"ids": variant_global_ids}}
+ for idx in range(5):
+ reward_value = 2 + idx
+ rules.append(
+ PromotionRule(
+ name=f"Catalogue rule fixed {reward_value}",
+ promotion=promotion,
+ catalogue_predicate=catalogue_predicate,
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal(reward_value),
+ )
+ )
+ for idx in range(5):
+ reward_value = idx * 10 + 25
+ rules.append(
+ PromotionRule(
+ name=f"Catalogue rule percentage {reward_value}",
+ promotion=promotion,
+ catalogue_predicate=catalogue_predicate,
+ reward_value_type=RewardValueType.PERCENTAGE,
+ reward_value=Decimal(reward_value),
+ )
+ )
+ rules = PromotionRule.objects.bulk_create(rules)
+ for rule in rules:
+ rule.channels.add(channel)
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+
+ # update prices
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ # create lines
+ new_order_lines = []
+ for idx, variant in enumerate(product_variant_list):
+ base_price = variant.channel_listings.first().discounted_price
+ currency = base_price.currency
+ gross = Money(amount=base_price.amount * Decimal(1.23), currency=currency)
+ quantity = 4 + idx
+ unit_price = TaxedMoney(net=base_price, gross=gross)
+ new_order_lines.append(
+ OrderLine(
+ order=order,
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=quantity,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * quantity,
+ tax_rate=Decimal("0.23"),
+ )
+ )
+ OrderLine.objects.bulk_create(new_order_lines)
+
+ tc = channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+
+ # when
+ with django_assert_num_queries(38):
+ fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 7
+ assert not OrderDiscount.objects.exists()
diff --git a/saleor/order/tests/test_discount_calculations.py b/saleor/order/tests/test_apply_order_discount.py
similarity index 94%
rename from saleor/order/tests/test_discount_calculations.py
rename to saleor/order/tests/test_apply_order_discount.py
index 66767e5d09..f22c5dc56f 100644
--- a/saleor/order/tests/test_discount_calculations.py
+++ b/saleor/order/tests/test_apply_order_discount.py
@@ -1,7 +1,7 @@
from decimal import Decimal
import pytest
-from prices import Money, TaxedMoney
+from prices import Money
from ...core.prices import quantize_price
from ...core.taxes import zero_money
@@ -9,51 +9,7 @@ from ...discount import DiscountType, DiscountValueType
from ...order.base_calculations import (
apply_order_discounts,
apply_subtotal_discount_to_order_lines,
- base_order_line_total,
- base_order_total,
)
-from ...order.interface import OrderTaxedPricesData
-
-
-def test_base_order_total(order_with_lines):
- # given
- order = order_with_lines
- lines = order.lines.all()
- shipping_price = order.shipping_price.net
- subtotal = zero_money(order.currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
- undiscounted_total = subtotal + shipping_price
-
- # when
- order_total = base_order_total(order, lines)
-
- # then
- assert order_total == undiscounted_total
-
-
-def test_base_order_line_total(order_with_lines):
- # given
- line = order_with_lines.lines.all().first()
-
- # when
- order_total = base_order_line_total(line)
-
- # then
- base_line_unit_price = line.base_unit_price
- quantity = line.quantity
- expected_price_with_discount = (
- TaxedMoney(base_line_unit_price, base_line_unit_price) * quantity
- )
- base_line_undiscounted_unit_price = line.undiscounted_base_unit_price
- expected_undiscounted_price = (
- TaxedMoney(base_line_undiscounted_unit_price, base_line_undiscounted_unit_price)
- * quantity
- )
- assert order_total == OrderTaxedPricesData(
- price_with_discounts=expected_price_with_discount,
- undiscounted_price=expected_undiscounted_price,
- )
def test_apply_order_discounts_voucher_entire_order(order_with_lines, voucher):
diff --git a/saleor/order/tests/test_fetch.py b/saleor/order/tests/test_fetch.py
new file mode 100644
index 0000000000..684d97115d
--- /dev/null
+++ b/saleor/order/tests/test_fetch.py
@@ -0,0 +1,73 @@
+from decimal import Decimal
+
+import pytest
+
+from ...product.models import ProductVariantChannelListing
+from ..fetch import fetch_draft_order_lines_info
+
+
[email protected]_queries(autouse=False)
+def test_fetch_draft_order_lines_info(
+ draft_order_and_promotions, django_assert_num_queries, count_queries
+):
+ # given
+ order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ channel = order.channel
+ lines = order.lines.all()
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+
+ manual_discount = line_1.discounts.create(
+ value=Decimal(1),
+ amount_value=Decimal(1),
+ currency=channel.currency_code,
+ name="Manual line discount",
+ )
+ rule_translation = "Rule translation"
+ rule_catalogue.translations.create(
+ language_code=order.language_code, name=rule_translation
+ )
+ promotion_translation = "Promotion"
+ rule_catalogue.promotion.translations.create(
+ language_code=order.language_code, name=promotion_translation
+ )
+
+ # when
+ with django_assert_num_queries(9):
+ lines_info = fetch_draft_order_lines_info(order)
+
+ # then
+ line_info_1 = [line_info for line_info in lines_info if line_info.line == line_1][0]
+ line_info_2 = [line_info for line_info in lines_info if line_info.line == line_2][0]
+
+ variant_1 = line_1.variant
+ assert line_info_1.variant == variant_1
+ assert (
+ line_info_1.channel_listing
+ == ProductVariantChannelListing.objects.filter(
+ channel=channel, variant=variant_1
+ ).first()
+ )
+ assert line_info_1.discounts == [manual_discount]
+ assert line_info_1.channel == channel
+ assert line_info_1.voucher is None
+ assert line_info_1.rules_info == []
+
+ variant_2 = line_2.variant
+ assert line_info_2.variant == variant_2
+ assert (
+ line_info_2.channel_listing
+ == ProductVariantChannelListing.objects.filter(
+ channel=channel, variant=variant_2
+ ).first()
+ )
+ assert line_info_2.discounts == []
+ assert line_info_2.channel == channel
+ assert line_info_2.voucher is None
+ rule_info_2 = line_info_2.rules_info[0]
+ assert rule_info_2.rule == rule_catalogue
+ assert rule_info_2.variant_listing_promotion_rule
+ assert rule_info_2.promotion == rule_catalogue.promotion
+ assert rule_info_2.promotion_translation.name == promotion_translation
+ assert rule_info_2.rule_translation.name == rule_translation
diff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.py
new file mode 100644
index 0000000000..5ccf22d535
--- /dev/null
+++ b/saleor/order/tests/test_fetch_order_prices.py
@@ -0,0 +1,1394 @@
+from decimal import Decimal
+
+import before_after
+import graphene
+import pytest
+
+from ...core.prices import quantize_price
+from ...discount import DiscountType, DiscountValueType
+from ...discount.models import (
+ OrderDiscount,
+ OrderLineDiscount,
+ PromotionRule,
+)
+from ...tax import TaxCalculationStrategy
+from ...tests.utils import round_down, round_up
+from .. import OrderStatus, calculations
+
+
+def order_with_lines(order_with_lines):
+ order_with_lines.status = OrderStatus.UNCONFIRMED
+ return order_with_lines
+
+
[email protected]("create_new_discounts", [True, False])
+def test_fetch_order_prices_catalogue_discount_flat_rates(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+ create_new_discounts,
+):
+ # given
+ if create_new_discounts:
+ OrderLineDiscount.objects.all().delete()
+
+ order = order_with_lines_and_catalogue_promotion
+ channel = order.channel
+ rule = PromotionRule.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ reward_value = rule.reward_value
+
+ tc = channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+
+ discount = line_1.discounts.get()
+ reward_amount = reward_value * line_1.quantity
+ assert discount.amount_value == reward_amount
+ assert discount.value == reward_value
+ assert discount.value_type == DiscountValueType.FIXED
+ assert discount.type == DiscountType.PROMOTION
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=channel)
+ variant_1_unit_price = variant_1_listing.discounted_price_amount
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ assert variant_1_undiscounted_unit_price - variant_1_unit_price == reward_value
+
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert (
+ line_1.base_unit_price_amount
+ == variant_1_undiscounted_unit_price - reward_value
+ )
+ assert (
+ line_1.unit_price_net_amount == variant_1_undiscounted_unit_price - reward_value
+ )
+ assert line_1.unit_price_gross_amount == line_1.unit_price_net_amount * tax_rate
+ assert (
+ line_1.total_price_net_amount == line_1.unit_price_net_amount * line_1.quantity
+ )
+ assert line_1.total_price_gross_amount == line_1.total_price_net_amount * tax_rate
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.unit_price_net_amount == variant_2_undiscounted_unit_price
+ assert (
+ line_2.unit_price_gross_amount == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.total_price_net_amount == line_2.undiscounted_total_price_net_amount
+ assert (
+ line_2.total_price_gross_amount == line_2.undiscounted_total_price_gross_amount
+ )
+
+ shipping_net_price = order.shipping_price_net_amount
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + shipping_net_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == order.undiscounted_total_net_amount - reward_amount
+ assert order.total_gross_amount == order.total_net_amount * tax_rate
+ assert order.subtotal_net_amount == order.total_net_amount - shipping_net_price
+ assert order.subtotal_gross_amount == order.subtotal_net_amount * tax_rate
+
+ assert line_1.unit_discount_amount == reward_value
+ assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
+ assert line_1.unit_discount_type == DiscountValueType.FIXED
+ assert line_1.unit_discount_value == reward_value
+
+
[email protected]("create_new_discounts", [True, False])
+def test_fetch_order_prices_order_discount_flat_rates(
+ order_with_lines_and_order_promotion,
+ plugins_manager,
+ create_new_discounts,
+):
+ # given
+ if create_new_discounts:
+ OrderDiscount.objects.all().delete()
+
+ order = order_with_lines_and_order_promotion
+ currency = order.currency
+ rule = PromotionRule.objects.get()
+ reward_amount = rule.reward_value
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert not OrderLineDiscount.objects.exists()
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ discount = OrderDiscount.objects.get()
+
+ line_1_base_total = line_1.quantity * line_1.base_unit_price_amount
+ line_2_base_total = line_2.quantity * line_2.base_unit_price_amount
+ base_total = line_1_base_total + line_2_base_total
+ line_1_order_discount_portion = reward_amount * line_1_base_total / base_total
+ line_2_order_discount_portion = reward_amount - line_1_order_discount_portion
+
+ assert discount.order == order
+ assert discount.amount_value == reward_amount
+ assert discount.value == reward_amount
+ assert discount.value_type == DiscountValueType.FIXED
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_total_net_amount = quantize_price(
+ line_1.undiscounted_total_price_net_amount - line_1_order_discount_portion,
+ currency,
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ assert line_1.total_price_gross_amount == round_down(
+ line_1_total_net_amount * tax_rate
+ )
+ assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
+ assert line_1.unit_price_net_amount == line_1_total_net_amount / line_1.quantity
+ assert line_1.unit_price_gross_amount == quantize_price(
+ line_1.unit_price_net_amount * tax_rate, currency
+ )
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ line_2_total_net_amount = quantize_price(
+ line_2.undiscounted_total_price_net_amount - line_2_order_discount_portion,
+ currency,
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.total_price_gross_amount == round_up(
+ line_2_total_net_amount * tax_rate
+ )
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.unit_price_net_amount == quantize_price(
+ line_2_total_net_amount / line_2.quantity, currency
+ )
+ assert line_2.unit_price_gross_amount == round_down(
+ line_2.unit_price_net_amount * tax_rate
+ )
+
+ shipping_price = order.shipping_price_net_amount
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == line_1_total_net_amount + line_2_total_net_amount + shipping_price
+ )
+ assert order.total_gross_amount == order.total_net_amount * tax_rate
+ assert (
+ order.subtotal_net_amount == line_1_total_net_amount + line_2_total_net_amount
+ )
+ assert order.subtotal_gross_amount == order.subtotal_net_amount * tax_rate
+
+
[email protected]("create_new_discounts", [True, False])
+def test_fetch_order_prices_gift_discount_flat_rates(
+ order_with_lines_and_gift_promotion,
+ plugins_manager,
+ create_new_discounts,
+):
+ # given
+ if create_new_discounts:
+ OrderLineDiscount.objects.all().delete()
+
+ order = order_with_lines_and_gift_promotion
+ rule = PromotionRule.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert len(lines) == 3
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ gift_line = [line for line in lines if line.is_gift][0]
+ assert not line_1.discounts.exists()
+ assert not line_2.discounts.exists()
+ discount = OrderLineDiscount.objects.get()
+
+ variant_gift = gift_line.variant
+ variant_gift_listing = variant_gift.channel_listings.get(channel=order.channel)
+ variant_gift_undiscounted_unit_price = variant_gift_listing.price_amount
+
+ assert discount.line == gift_line
+ assert discount.amount_value == variant_gift_undiscounted_unit_price
+ assert discount.value == variant_gift_undiscounted_unit_price
+ assert discount.value_type == DiscountValueType.FIXED
+ assert discount.type == DiscountType.ORDER_PROMOTION
+ assert discount.reason == f"Promotion: {promotion_id}"
+
+ assert gift_line.unit_discount_amount == variant_gift_undiscounted_unit_price
+ assert gift_line.unit_discount_reason == f"Promotion: {promotion_id}"
+ assert gift_line.unit_discount_type == DiscountValueType.FIXED
+ assert gift_line.unit_discount_value == variant_gift_undiscounted_unit_price
+ assert gift_line.undiscounted_total_price_net_amount == Decimal(0)
+ assert gift_line.undiscounted_total_price_gross_amount == Decimal(0)
+ assert gift_line.undiscounted_unit_price_net_amount == Decimal(0)
+ assert gift_line.undiscounted_unit_price_gross_amount == Decimal(0)
+ assert gift_line.total_price_net_amount == Decimal(0)
+ assert gift_line.total_price_gross_amount == Decimal(0)
+ assert gift_line.base_unit_price_amount == Decimal(0)
+ assert gift_line.unit_price_net_amount == Decimal(0)
+ assert gift_line.unit_price_gross_amount == Decimal(0)
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.total_price_net_amount == line_1.undiscounted_total_price_net_amount
+ assert (
+ line_1.total_price_gross_amount == line_1.undiscounted_total_price_gross_amount
+ )
+ assert line_1.base_unit_price_amount == line_1.undiscounted_unit_price_net_amount
+ assert line_1.unit_price_net_amount == line_1.undiscounted_unit_price_net_amount
+ assert line_1.unit_price_gross_amount == line_1.undiscounted_unit_price_gross_amount
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.total_price_net_amount == line_2.undiscounted_total_price_net_amount
+ assert (
+ line_2.total_price_gross_amount == line_2.undiscounted_total_price_gross_amount
+ )
+ assert line_2.base_unit_price_amount == line_2.undiscounted_unit_price_net_amount
+ assert line_2.unit_price_net_amount == line_2.undiscounted_unit_price_net_amount
+ assert line_2.unit_price_gross_amount == line_2.undiscounted_unit_price_gross_amount
+
+ shipping_price = order.shipping_price_net_amount
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == order.undiscounted_total_net_amount
+ assert order.total_gross_amount == order.undiscounted_total_gross_amount
+ assert (
+ order.subtotal_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ )
+ assert order.subtotal_gross_amount == order.subtotal_net_amount * tax_rate
+
+
+def test_fetch_order_prices_catalogue_and_order_discounts_flat_rates(
+ draft_order_and_promotions,
+ plugins_manager,
+):
+ # given
+ order, rule_catalogue, rule_total, _ = draft_order_and_promotions
+ catalogue_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_catalogue.promotion_id
+ )
+ order_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_total.promotion_id
+ )
+ rule_catalogue_reward = rule_catalogue.reward_value
+ rule_total_reward = rule_total.reward_value
+ currency = order.currency
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ catalogue_discount = OrderLineDiscount.objects.get()
+ order_discount = OrderDiscount.objects.get()
+
+ line_1_base_total = line_1.quantity * line_1.base_unit_price_amount
+ line_2_base_total = line_2.quantity * line_2.base_unit_price_amount
+ base_total = line_1_base_total + line_2_base_total
+ line_1_order_discount_portion = rule_total_reward * line_1_base_total / base_total
+ line_2_order_discount_portion = rule_total_reward - line_1_order_discount_portion
+
+ assert order_discount.order == order
+ assert order_discount.amount_value == rule_total_reward
+ assert order_discount.value == rule_total_reward
+ assert order_discount.value_type == DiscountValueType.FIXED
+ assert order_discount.type == DiscountType.ORDER_PROMOTION
+ assert order_discount.reason == f"Promotion: {order_promotion_id}"
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_total_net_amount = quantize_price(
+ line_1.undiscounted_total_price_net_amount - line_1_order_discount_portion,
+ currency,
+ )
+ assert not line_1.discounts.exists()
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ assert line_1.total_price_gross_amount == round_up(
+ line_1_total_net_amount * tax_rate
+ )
+ assert line_1.unit_price_net_amount == quantize_price(
+ line_1_total_net_amount / line_1.quantity, currency
+ )
+ assert line_1.unit_price_gross_amount == round_up(
+ line_1.unit_price_net_amount * tax_rate
+ )
+
+ assert catalogue_discount.line == line_2
+ assert catalogue_discount.amount_value == rule_catalogue_reward * line_2.quantity
+ assert catalogue_discount.value == rule_catalogue_reward
+ assert catalogue_discount.value_type == DiscountValueType.FIXED
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.reason == f"Promotion: {catalogue_promotion_id}"
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ line_2_total_net_amount = quantize_price(
+ line_2.undiscounted_total_price_net_amount
+ - line_2_order_discount_portion
+ - catalogue_discount.amount_value,
+ currency,
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert (
+ line_2.base_unit_price_amount
+ == variant_2_undiscounted_unit_price - rule_catalogue_reward
+ )
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.total_price_gross_amount == round_down(
+ line_2_total_net_amount * tax_rate
+ )
+ assert line_2.unit_price_net_amount == quantize_price(
+ line_2_total_net_amount / line_2.quantity, currency
+ )
+ assert line_2.unit_price_gross_amount == quantize_price(
+ line_2.unit_price_net_amount * tax_rate, currency
+ )
+
+ shipping_price = order.shipping_price_net_amount
+ total_net_amount = quantize_price(
+ order.undiscounted_total_net_amount
+ - order_discount.amount_value
+ - catalogue_discount.amount_value,
+ currency,
+ )
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == total_net_amount
+ assert order.total_gross_amount == quantize_price(
+ total_net_amount * tax_rate, currency
+ )
+ assert (
+ order.subtotal_net_amount == line_1_total_net_amount + line_2_total_net_amount
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_catalogue_and_gift_discounts_flat_rates(
+ draft_order_and_promotions,
+ plugins_manager,
+):
+ # given
+ order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ rule_total.reward_value = Decimal(0)
+ rule_total.save(update_fields=["reward_value"])
+
+ catalogue_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_catalogue.promotion_id
+ )
+ gift_promotion_id = graphene.Node.to_global_id("Promotion", rule_gift.promotion_id)
+ rule_catalogue_reward = rule_catalogue.reward_value
+ currency = order.currency
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert len(lines) == 3
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ gift_line = [line for line in lines if line.is_gift][0]
+
+ assert OrderLineDiscount.objects.count() == 2
+ gift_discount = gift_line.discounts.get()
+ catalogue_discount = line_2.discounts.get()
+
+ variant_gift = gift_line.variant
+ variant_gift_listing = variant_gift.channel_listings.get(channel=order.channel)
+ variant_gift_undiscounted_unit_price = variant_gift_listing.price_amount
+
+ assert gift_discount.line == gift_line
+ assert gift_discount.amount_value == variant_gift_undiscounted_unit_price
+ assert gift_discount.value == variant_gift_undiscounted_unit_price
+ assert gift_discount.value_type == DiscountValueType.FIXED
+ assert gift_discount.type == DiscountType.ORDER_PROMOTION
+ assert gift_discount.reason == f"Promotion: {gift_promotion_id}"
+
+ assert gift_line.unit_discount_amount == variant_gift_undiscounted_unit_price
+ assert gift_line.unit_discount_reason == f"Promotion: {gift_promotion_id}"
+ assert gift_line.unit_discount_type == DiscountValueType.FIXED
+ assert gift_line.unit_discount_value == variant_gift_undiscounted_unit_price
+ assert gift_line.undiscounted_total_price_net_amount == Decimal(0)
+ assert gift_line.undiscounted_total_price_gross_amount == Decimal(0)
+ assert gift_line.undiscounted_unit_price_net_amount == Decimal(0)
+ assert gift_line.undiscounted_unit_price_gross_amount == Decimal(0)
+ assert gift_line.total_price_net_amount == Decimal(0)
+ assert gift_line.total_price_gross_amount == Decimal(0)
+ assert gift_line.base_unit_price_amount == Decimal(0)
+ assert gift_line.unit_price_net_amount == Decimal(0)
+ assert gift_line.unit_price_gross_amount == Decimal(0)
+
+ assert not line_1.discounts.exists()
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_total_net_amount = line_1.undiscounted_total_price_net_amount
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.total_price_net_amount == line_1.undiscounted_total_price_net_amount
+ assert (
+ line_1.total_price_gross_amount == line_1.undiscounted_total_price_gross_amount
+ )
+ assert line_1.base_unit_price_amount == line_1.undiscounted_unit_price_net_amount
+ assert line_1.unit_price_net_amount == line_1.undiscounted_unit_price_net_amount
+ assert line_1.unit_price_gross_amount == line_1.undiscounted_unit_price_gross_amount
+
+ assert catalogue_discount.line == line_2
+ assert catalogue_discount.amount_value == rule_catalogue_reward * line_2.quantity
+ assert catalogue_discount.value == rule_catalogue_reward
+ assert catalogue_discount.value_type == DiscountValueType.FIXED
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.reason == f"Promotion: {catalogue_promotion_id}"
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ line_2_total_net_amount = quantize_price(
+ line_2.undiscounted_total_price_net_amount - catalogue_discount.amount_value,
+ currency,
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert (
+ line_2.base_unit_price_amount
+ == variant_2_undiscounted_unit_price - rule_catalogue_reward
+ )
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2_total_net_amount * tax_rate, currency
+ )
+ assert (
+ line_2.unit_price_net_amount
+ == variant_2_undiscounted_unit_price - rule_catalogue_reward
+ )
+ assert line_2.unit_price_gross_amount == quantize_price(
+ line_2.unit_price_net_amount * tax_rate, currency
+ )
+
+ shipping_price = order.shipping_price_net_amount
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ total_net_amount = quantize_price(
+ order.undiscounted_total_net_amount - catalogue_discount.amount_value,
+ currency,
+ )
+ assert order.total_net_amount == total_net_amount
+ assert order.total_gross_amount == quantize_price(
+ total_net_amount * tax_rate, currency
+ )
+ assert (
+ order.subtotal_net_amount == line_1_total_net_amount + line_2_total_net_amount
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_catalogue_and_order_discounts_exceed_total_flat_rates(
+ draft_order_and_promotions,
+ plugins_manager,
+):
+ # given
+ order, rule_catalogue, rule_total, _ = draft_order_and_promotions
+ rule_total.reward_value = Decimal(100000)
+ rule_total.save(update_fields=["reward_value"])
+ catalogue_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_catalogue.promotion_id
+ )
+ order_promotion_id = graphene.Node.to_global_id(
+ "Promotion", rule_total.promotion_id
+ )
+ rule_catalogue_reward = rule_catalogue.reward_value
+ currency = order.currency
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ catalogue_discount = OrderLineDiscount.objects.get()
+ order_discount = OrderDiscount.objects.get()
+
+ shipping_price = order.shipping_price_net_amount
+ rule_total_reward = quantize_price(
+ order.undiscounted_total_net_amount
+ - shipping_price
+ - rule_catalogue_reward * line_2.quantity,
+ currency,
+ )
+ assert order_discount.order == order
+ assert order_discount.amount_value == rule_total_reward
+ assert order_discount.value == rule_total.reward_value
+ assert order_discount.value_type == DiscountValueType.FIXED
+ assert order_discount.type == DiscountType.ORDER_PROMOTION
+ assert order_discount.reason == f"Promotion: {order_promotion_id}"
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ assert not line_1.discounts.exists()
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
+ assert line_1.total_price_net_amount == Decimal(0)
+ assert line_1.total_price_gross_amount == Decimal(0)
+ assert line_1.unit_price_net_amount == Decimal(0)
+ assert line_1.unit_price_gross_amount == Decimal(0)
+
+ assert catalogue_discount.line == line_2
+ assert catalogue_discount.amount_value == rule_catalogue_reward * line_2.quantity
+ assert catalogue_discount.value == rule_catalogue_reward
+ assert catalogue_discount.value_type == DiscountValueType.FIXED
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.reason == f"Promotion: {catalogue_promotion_id}"
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert (
+ line_2.base_unit_price_amount
+ == variant_2_undiscounted_unit_price - rule_catalogue_reward
+ )
+ assert line_2.total_price_net_amount == Decimal(0)
+ assert line_2.total_price_gross_amount == Decimal(0)
+ assert line_2.unit_price_net_amount == Decimal(0)
+ assert line_2.unit_price_gross_amount == Decimal(0)
+
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == shipping_price
+ assert order.total_gross_amount == shipping_price * tax_rate
+ assert order.subtotal_net_amount == Decimal(0)
+ assert order.subtotal_gross_amount == Decimal(0)
+
+
+def test_fetch_order_prices_manual_discount_and_order_discount_flat_rates(
+ order_with_lines_and_order_promotion,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines_and_order_promotion
+ assert OrderDiscount.objects.exists()
+ currency = order.currency
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ discount_value = Decimal("50")
+ manual_discount = order.discounts.create(
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_value,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ )
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert not OrderLineDiscount.objects.exists()
+ assert OrderDiscount.objects.count() == 1
+ manual_discount.refresh_from_db()
+
+ assert manual_discount.order == order
+ assert manual_discount.amount_value == Decimal(
+ order.undiscounted_total_net_amount / 2
+ )
+ assert manual_discount.value == discount_value
+ assert manual_discount.value_type == DiscountValueType.PERCENTAGE
+ assert manual_discount.type == DiscountType.MANUAL
+ assert not manual_discount.reason
+
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_total_net_amount = quantize_price(
+ line_1.undiscounted_total_price_net_amount * discount_value / 100, currency
+ )
+
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1_total_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_price_net_amount == quantize_price(
+ line_1_total_net_amount / line_1.quantity, currency
+ )
+ assert line_1.unit_price_gross_amount == quantize_price(
+ line_1.unit_price_net_amount * tax_rate, currency
+ )
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ line_2_total_net_amount = quantize_price(
+ line_2.undiscounted_total_price_net_amount * discount_value / 100, currency
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2_total_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_price_net_amount == quantize_price(
+ line_2_total_net_amount / line_2.quantity, currency
+ )
+ assert line_2.unit_price_gross_amount == quantize_price(
+ line_2.unit_price_net_amount * tax_rate, currency
+ )
+
+ undiscounted_shipping_price = order.base_shipping_price_amount
+ total_net_amount = quantize_price(
+ order.undiscounted_total_net_amount * discount_value / 100, currency
+ )
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == total_net_amount
+ assert order.total_gross_amount == quantize_price(
+ total_net_amount * tax_rate, currency
+ )
+ assert (
+ order.subtotal_net_amount == line_1_total_net_amount + line_2_total_net_amount
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_manual_discount_and_gift_discount_flat_rates(
+ order_with_lines_and_gift_promotion,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines_and_gift_promotion
+ assert OrderLineDiscount.objects.exists()
+ currency = order.currency
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ discount_value = Decimal("50")
+ manual_discount = order.discounts.create(
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_value,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ )
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert not OrderLineDiscount.objects.exists()
+ assert OrderDiscount.objects.count() == 1
+ assert len(lines) == 2
+ manual_discount.refresh_from_db()
+
+ assert manual_discount.order == order
+ assert manual_discount.amount_value == Decimal(
+ order.undiscounted_total_net_amount / 2
+ )
+ assert manual_discount.value == discount_value
+ assert manual_discount.value_type == DiscountValueType.PERCENTAGE
+ assert manual_discount.type == DiscountType.MANUAL
+ assert not manual_discount.reason
+
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+ assert not [line for line in lines if line.is_gift]
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_total_net_amount = quantize_price(
+ line_1.undiscounted_total_price_net_amount * discount_value / 100, currency
+ )
+
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert line_1.base_unit_price_amount == variant_1_undiscounted_unit_price
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1_total_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_price_net_amount == quantize_price(
+ line_1_total_net_amount / line_1.quantity, currency
+ )
+ assert line_1.unit_price_gross_amount == quantize_price(
+ line_1.unit_price_net_amount * tax_rate, currency
+ )
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ line_2_total_net_amount = quantize_price(
+ line_2.undiscounted_total_price_net_amount * discount_value / 100, currency
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2_total_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_price_net_amount == quantize_price(
+ line_2_total_net_amount / line_2.quantity, currency
+ )
+ assert line_2.unit_price_gross_amount == quantize_price(
+ line_2.unit_price_net_amount * tax_rate, currency
+ )
+
+ undiscounted_shipping_price = order.base_shipping_price_amount
+ total_net_amount = quantize_price(
+ order.undiscounted_total_net_amount * discount_value / 100, currency
+ )
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == total_net_amount
+ assert order.total_gross_amount == quantize_price(
+ total_net_amount * tax_rate, currency
+ )
+ assert (
+ order.subtotal_net_amount == line_1_total_net_amount + line_2_total_net_amount
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.shipping_price_net_amount
+ == undiscounted_shipping_price * discount_value / 100
+ )
+ assert order.shipping_price_gross_amount == quantize_price(
+ order.shipping_price_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_manual_discount_and_catalogue_discount_flat_rates(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ currency = order.currency
+ rule = PromotionRule.objects.get()
+ rule_catalogue_reward = rule.reward_value
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+ tax_rate = Decimal("1.23")
+
+ manual_discount_value = Decimal("50")
+ manual_discount = order.discounts.create(
+ value_type=DiscountValueType.PERCENTAGE,
+ value=manual_discount_value,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ )
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ catalogue_discount = OrderLineDiscount.objects.get()
+ assert OrderDiscount.objects.count() == 1
+
+ manual_discount.refresh_from_db()
+ manual_discount_amount = Decimal(
+ (order.undiscounted_total_net_amount - catalogue_discount.amount_value)
+ * manual_discount_value
+ / 100
+ )
+ assert manual_discount.order == order
+ assert manual_discount.amount_value == manual_discount_amount
+ assert manual_discount.value == manual_discount_value
+ assert manual_discount.value_type == DiscountValueType.PERCENTAGE
+ assert manual_discount.type == DiscountType.MANUAL
+ assert not manual_discount.reason
+
+ line_1 = [line for line in lines if line.quantity == 3][0]
+ line_2 = [line for line in lines if line.quantity == 2][0]
+
+ assert catalogue_discount.line == line_1
+ assert catalogue_discount.amount_value == rule_catalogue_reward * line_1.quantity
+ assert catalogue_discount.value == rule_catalogue_reward
+ assert catalogue_discount.value_type == DiscountValueType.FIXED
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.reason == f"Promotion: {promotion_id}"
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_total_net_amount = quantize_price(
+ (variant_1_undiscounted_unit_price - rule_catalogue_reward)
+ * line_1.quantity
+ * manual_discount_value
+ / 100,
+ currency,
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert (
+ line_1.undiscounted_unit_price_gross_amount
+ == variant_1_undiscounted_unit_price * tax_rate
+ )
+ assert (
+ line_1.base_unit_price_amount
+ == variant_1_undiscounted_unit_price - rule_catalogue_reward
+ )
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1_total_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_price_net_amount == quantize_price(
+ line_1_total_net_amount / line_1.quantity, currency
+ )
+ assert line_1.unit_price_gross_amount == round_up(
+ line_1.unit_price_net_amount * tax_rate
+ )
+ assert line_1.unit_discount_amount == rule_catalogue_reward
+ assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
+ assert line_1.unit_discount_value == rule_catalogue_reward
+ assert line_1.unit_discount_type == DiscountValueType.FIXED
+
+ variant_2 = line_2.variant
+ variant_2_listing = variant_2.channel_listings.get(channel=order.channel)
+ variant_2_undiscounted_unit_price = variant_2_listing.price_amount
+ line_2_total_net_amount = quantize_price(
+ line_2.undiscounted_total_price_net_amount * manual_discount_value / 100,
+ currency,
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert (
+ line_2.undiscounted_unit_price_gross_amount
+ == variant_2_undiscounted_unit_price * tax_rate
+ )
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2_total_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_price_net_amount == quantize_price(
+ line_2_total_net_amount / line_2.quantity, currency
+ )
+ assert line_2.unit_price_gross_amount == quantize_price(
+ line_2.unit_price_net_amount * tax_rate, currency
+ )
+
+ undiscounted_shipping_price = order.base_shipping_price_amount
+ total_net_amount = quantize_price(
+ (order.undiscounted_total_net_amount - catalogue_discount.amount_value)
+ * manual_discount_value
+ / 100,
+ currency,
+ )
+ assert (
+ order.undiscounted_total_net_amount
+ == line_1.undiscounted_total_price_net_amount
+ + line_2.undiscounted_total_price_net_amount
+ + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == order.undiscounted_total_net_amount * tax_rate
+ )
+ assert order.total_net_amount == total_net_amount
+ assert order.total_gross_amount == round_up(total_net_amount * tax_rate)
+ assert (
+ order.subtotal_net_amount == line_1_total_net_amount + line_2_total_net_amount
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.shipping_price_net_amount
+ == undiscounted_shipping_price * manual_discount_value / 100
+ )
+ assert order.shipping_price_gross_amount == quantize_price(
+ order.shipping_price_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_manual_line_discount_and_catalogue_discount_flat_rates(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+
+ tc = order.channel.tax_configuration
+ tc.country_exceptions.all().delete()
+ tc.prices_entered_with_tax = False
+ tc.tax_calculation_strategy = TaxCalculationStrategy.FLAT_RATES
+ tc.save()
+
+ line_1 = order.lines.get(quantity=3)
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=order.channel)
+
+ manual_discount_value = Decimal("5")
+ manual_discount_value_type = DiscountValueType.FIXED
+ manual_discount_reason = "Manual line discount"
+ manual_discount = line_1.discounts.create(
+ value_type=manual_discount_value_type,
+ value=manual_discount_value,
+ name="Manual order line discount",
+ type=DiscountType.MANUAL,
+ reason=manual_discount_reason,
+ )
+
+ # when
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+ manual_discount.refresh_from_db()
+
+ line_1 = [line for line in lines if line.quantity == 3][0]
+
+ assert line_1.base_unit_price_amount == variant_1_listing.price_amount
+ assert manual_discount.line == line_1
+ assert manual_discount.value == manual_discount_value
+ assert manual_discount.value_type == manual_discount_value_type
+ assert manual_discount.type == DiscountType.MANUAL
+ assert manual_discount.reason == manual_discount_reason
+
+ # TODO https://github.com/saleor/saleor/issues/15517
+ # line_1_total_net_amount = quantize_price(
+ # (variant_1_listing.price_amount - manual_discount_value) * line_1.quantity,
+ # order.currency
+ # )
+ # assert line_1.total_price_net_amount == line_1_total_net_amount
+
+
+def test_fetch_order_prices_catalogue_discount_race_condition(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ OrderLineDiscount.objects.all().delete()
+
+ # when
+ def call_before_creating_catalogue_line_discount(*args, **kwargs):
+ calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ with before_after.before(
+ "saleor.discount.utils.prepare_line_discount_objects_for_catalogue_promotions",
+ call_before_creating_catalogue_line_discount,
+ ):
+ calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 1
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 9e88fa5f8e..f159dc5b1e 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -841,6 +841,9 @@ def update_discount_for_order_line(
value: Optional[Decimal],
):
"""Update discount fields for order line. Apply discount to the price."""
+ # TODO: Move price calculation to fetch_order_prices_if_expired function.
+ # Here we should only create order line discount object
+ # https://github.com/saleor/saleor/issues/15517
current_value = order_line.unit_discount_value
current_value_type = order_line.unit_discount_type
value = value or current_value
@@ -893,6 +896,52 @@ def update_discount_for_order_line(
# from db
order_line.save(update_fields=fields_to_update)
+ _update_manual_order_line_discount_object(
+ value, value_type, reason, order_line, order.currency
+ )
+
+
+def _update_manual_order_line_discount_object(
+ value, value_type, reason, order_line, currency
+):
+ discount_to_update = None
+ discount_to_delete_ids = []
+ discounts = order_line.discounts.all()
+ for discount in discounts:
+ if discount.type == DiscountType.MANUAL and not discount_to_update:
+ discount_to_update = discount
+ else:
+ discount_to_delete_ids.append(discount.pk)
+
+ if discount_to_delete_ids:
+ OrderLineDiscount.objects.filter(id__in=discount_to_delete_ids).delete()
+
+ amount_value = quantize_price(
+ order_line.unit_discount.amount * order_line.quantity, currency
+ )
+ if not discount_to_update:
+ order_line.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=value_type,
+ value=value,
+ amount_value=amount_value,
+ currency=currency,
+ reason=reason,
+ )
+ else:
+ update_fields = []
+ if discount_to_update.value_type != value_type:
+ discount_to_update.value_type = value_type
+ update_fields.append("value_type")
+ if discount_to_update.value != value:
+ discount_to_update.value = value
+ discount_to_update.amount_value = amount_value
+ update_fields.extend(["value", "amount_value"])
+ if discount_to_update.reason != reason:
+ discount_to_update.reason = reason
+ update_fields.append("reason")
+ discount_to_update.save(update_fields=update_fields)
+
def remove_discount_from_order_line(order_line: OrderLine, order: "Order"):
"""Drop discount applied to order line. Restore undiscounted price."""
@@ -922,6 +971,7 @@ def remove_discount_from_order_line(order_line: OrderLine, order: "Order"):
"tax_rate",
]
)
+ order_line.discounts.all().delete()
def update_order_charge_status(order: Order, granted_refund_amount: Decimal):
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total_gift_promotion.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total_gift_promotion.yaml
new file mode 100644
index 0000000000..a4a6bf4fe7
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total_gift_promotion.yaml
@@ -0,0 +1,81 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
+ "lines": [{"quantity": 3, "amount": "30.000", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "SKU_AA", "discounted": false, "description": "Test product"},
+ {"quantity": 2, "amount": "40.000", "taxCode": "O9999999", "taxIncluded": true,
+ "itemCode": "SKU_B", "discounted": false, "description": "Test product 2"},
+ {"quantity": 1, "amount": "0.000", "taxCode": "O9999999", "taxIncluded": true,
+ "itemCode": "SKU_A", "discounted": false, "description": "Test product"}, {"quantity":
+ 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode":
+ "Shipping", "discounted": false, "description": null}], "code": "368cf947-7561-44f7-b39a-32a8dcc8482e",
+ "date": "2024-02-26", "customerCode": 0, "discount": null, "addresses": {"shipFrom":
+ {"line1": "Teczowa 7", "line2": "", "city": "Wroclaw", "region": "", "country":
+ "PL", "postalCode": "53-601"}, "shipTo": {"line1": "T\u0119czowa 7", "line2":
+ "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-601"}},
+ "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '1145'
+ User-Agent:
+ - Saleor/3.20
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":85050296660452,"code":"368cf947-7561-44f7-b39a-32a8dcc8482e","companyId":7799660,"date":"2024-02-26","status":"Saved","type":"SalesInvoice","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","taxOverrideType":"None","taxOverrideAmount":0.0,"taxOverrideReason":"","totalAmount":65.04,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":14.96,"totalTaxable":65.04,"totalTaxCalculated":14.96,"adjustmentReason":"NotAdjusted","adjustmentDescription":"","locked":false,"region":"","country":"PL","version":1,"softwareVersion":"24.2.0.0","originAddressId":85050296660454,"destinationAddressId":85050296660453,"exchangeRateEffectiveDate":"2024-02-26","exchangeRate":1.0,"description":"","email":"[email protected]","businessIdentificationNo":"","modifiedDate":"2024-02-26T18:58:42.8269135Z","modifiedUserId":6479978,"taxDate":"2024-02-26","lines":[{"id":85050296660458,"transactionId":85050296660452,"lineNumber":"1","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product","destinationAddressId":85050296660453,"originAddressId":85050296660454,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"SKU_AA","lineAmount":24.3900,"quantity":3.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":5.61,"taxableAmount":24.39,"taxCalculated":5.61,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296660482,"transactionLineId":85050296660458,"transactionId":85050296660452,"addressId":85050296660453,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":5.6100,"taxableAmount":24.3900,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":5.6100,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":24.3900,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":24.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":5.61,"reportingTaxCalculated":5.61,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296660463,"documentLineId":85050296660458,"documentAddressId":85050296660454,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296660464,"documentLineId":85050296660458,"documentAddressId":85050296660453,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":85050296660459,"transactionId":85050296660452,"lineNumber":"2","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product 2","destinationAddressId":85050296660453,"originAddressId":85050296660454,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"SKU_B","lineAmount":32.5200,"quantity":2.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":7.48,"taxableAmount":32.52,"taxCalculated":7.48,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296660503,"transactionLineId":85050296660459,"transactionId":85050296660452,"addressId":85050296660453,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":7.4800,"taxableAmount":32.5200,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":7.4800,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":32.5200,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":32.52,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":7.48,"reportingTaxCalculated":7.48,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296660484,"documentLineId":85050296660459,"documentAddressId":85050296660454,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296660485,"documentLineId":85050296660459,"documentAddressId":85050296660453,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":85050296660460,"transactionId":85050296660452,"lineNumber":"3","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product","destinationAddressId":85050296660453,"originAddressId":85050296660454,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":false,"isSSTP":false,"itemCode":"SKU_A","lineAmount":0.0,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":0.0,"taxableAmount":0.0,"taxCalculated":0.0,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296660524,"transactionLineId":85050296660460,"transactionId":85050296660452,"addressId":85050296660453,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":0.0000,"taxableAmount":0.0000,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":0.0000,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":0.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":0.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":0.0,"reportingTaxCalculated":0.0,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296660505,"documentLineId":85050296660460,"documentAddressId":85050296660454,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296660506,"documentLineId":85050296660460,"documentAddressId":85050296660453,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":85050296660461,"transactionId":85050296660452,"lineNumber":"4","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"","destinationAddressId":85050296660453,"originAddressId":85050296660454,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296660545,"transactionLineId":85050296660461,"transactionId":85050296660452,"addressId":85050296660453,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":1.8700,"taxableAmount":8.1300,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":1.8700,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296660526,"documentLineId":85050296660461,"documentAddressId":85050296660454,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296660527,"documentLineId":85050296660461,"documentAddressId":85050296660453,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":85050296660453,"transactionId":85050296660452,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102},{"id":85050296660454,"transactionId":85050296660452,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102}],"locationTypes":[{"documentLocationTypeId":85050296660456,"documentId":85050296660452,"documentAddressId":85050296660454,"locationTypeCode":"ShipFrom"},{"documentLocationTypeId":85050296660457,"documentId":85050296660452,"documentAddressId":85050296660453,"locationTypeCode":"ShipTo"}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":65.04,"rate":0.230000,"tax":14.96,"taxCalculated":14.96,"nonTaxable":0.00,"exemption":0.00}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 26 Feb 2024 18:58:42 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/85050296660452
+ ServerDuration:
+ - '00:00:00.0815874'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - df8331af-ab28-4015-9bee-4d945f48634c
+ x-correlation-id:
+ - df8331af-ab28-4015-9bee-4d945f48634c
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total_order_promotion.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total_order_promotion.yaml
new file mode 100644
index 0000000000..0ff21af4c2
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_order_total_order_promotion.yaml
@@ -0,0 +1,77 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
+ "lines": [{"quantity": 3, "amount": "30.000", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "SKU_AA", "discounted": true, "description": "Test product"},
+ {"quantity": 2, "amount": "40.000", "taxCode": "O9999999", "taxIncluded": true,
+ "itemCode": "SKU_B", "discounted": true, "description": "Test product 2"}, {"quantity":
+ 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode":
+ "Shipping", "discounted": false, "description": null}], "code": "a01b5217-42b3-48dc-889f-954154d1c3f6",
+ "date": "2024-02-26", "customerCode": 0, "discount": "25.000", "addresses":
+ {"shipFrom": {"line1": "Teczowa 7", "line2": "", "city": "Wroclaw", "region":
+ "", "country": "PL", "postalCode": "53-601"}, "shipTo": {"line1": "T\u0119czowa
+ 7", "line2": "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode":
+ "53-601"}}, "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '994'
+ User-Agent:
+ - Saleor/3.20
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":85050296358456,"code":"a01b5217-42b3-48dc-889f-954154d1c3f6","companyId":7799660,"date":"2024-02-26","status":"Saved","type":"SalesInvoice","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","taxOverrideType":"None","taxOverrideAmount":0.0,"taxOverrideReason":"","totalAmount":69.71,"totalExempt":0.0,"totalDiscount":25.0,"totalTax":10.29,"totalTaxable":44.71,"totalTaxCalculated":10.29,"adjustmentReason":"NotAdjusted","adjustmentDescription":"","locked":false,"region":"","country":"PL","version":1,"softwareVersion":"24.2.0.0","originAddressId":85050296358458,"destinationAddressId":85050296358457,"exchangeRateEffectiveDate":"2024-02-26","exchangeRate":1.0,"description":"","email":"[email protected]","businessIdentificationNo":"","modifiedDate":"2024-02-26T18:49:50.8851355Z","modifiedUserId":6479978,"taxDate":"2024-02-26","lines":[{"id":85050296358462,"transactionId":85050296358456,"lineNumber":"1","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product","destinationAddressId":85050296358457,"originAddressId":85050296358458,"discountAmount":10.71,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"SKU_AA","lineAmount":26.3900,"quantity":3.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":3.61,"taxableAmount":15.68,"taxCalculated":3.61,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296358485,"transactionLineId":85050296358462,"transactionId":85050296358456,"addressId":85050296358457,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":3.6100,"taxableAmount":15.6800,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":3.6100,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":15.6800,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":15.68,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":3.61,"reportingTaxCalculated":3.61,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296358466,"documentLineId":85050296358462,"documentAddressId":85050296358458,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296358467,"documentLineId":85050296358462,"documentAddressId":85050296358457,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":85050296358463,"transactionId":85050296358456,"lineNumber":"2","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product 2","destinationAddressId":85050296358457,"originAddressId":85050296358458,"discountAmount":14.29,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"SKU_B","lineAmount":35.1900,"quantity":2.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":4.81,"taxableAmount":20.9,"taxCalculated":4.81,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296358506,"transactionLineId":85050296358463,"transactionId":85050296358456,"addressId":85050296358457,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":4.8100,"taxableAmount":20.9000,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":4.8100,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":20.9000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":20.9,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":4.81,"reportingTaxCalculated":4.81,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296358487,"documentLineId":85050296358463,"documentAddressId":85050296358458,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296358488,"documentLineId":85050296358463,"documentAddressId":85050296358457,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":85050296358464,"transactionId":85050296358456,"lineNumber":"3","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"","destinationAddressId":85050296358457,"originAddressId":85050296358458,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-02-26","revAccount":"","sourcing":"Destination","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-02-26","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85050296358527,"transactionLineId":85050296358464,"transactionId":85050296358456,"addressId":85050296358457,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"PL","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":1.8700,"taxableAmount":8.1300,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":1.8700,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85050296358508,"documentLineId":85050296358464,"documentAddressId":85050296358458,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85050296358509,"documentLineId":85050296358464,"documentAddressId":85050296358457,"locationTypeCode":"ShipTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":85050296358457,"transactionId":85050296358456,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102},{"id":85050296358458,"transactionId":85050296358456,"boundaryLevel":"Zip5","line1":"Teczowa
+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102}],"locationTypes":[{"documentLocationTypeId":85050296358460,"documentId":85050296358456,"documentAddressId":85050296358458,"locationTypeCode":"ShipFrom"},{"documentLocationTypeId":85050296358461,"documentId":85050296358456,"documentAddressId":85050296358457,"locationTypeCode":"ShipTo"}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":44.71,"rate":0.230000,"tax":10.29,"taxCalculated":10.29,"nonTaxable":0.00,"exemption":0.00}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Mon, 26 Feb 2024 18:49:50 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/85050296358456
+ ServerDuration:
+ - '00:00:00.0712472'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 33c0538c-1f94-4fad-b391-ed49bb1ad281
+ x-correlation-id:
+ - 33c0538c-1f94-4fad-b391-ed49bb1ad281
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index d81b293880..32275c3878 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -2465,6 +2465,56 @@ def test_calculate_order_total_for_JPY(
assert price == TaxedMoney(net=Money("3496", "JPY"), gross=Money("4300", "JPY"))
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_order_total_order_promotion(
+ order_with_lines_and_order_promotion,
+ shipping_zone,
+ site_settings,
+ address,
+ plugin_configuration,
+):
+ plugin_configuration()
+ manager = get_plugins_manager(allow_replica=False)
+ order = order_with_lines_and_order_promotion
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = order.billing_address.get_copy()
+ order_set_shipping_method(order, method)
+ order.save()
+
+ site_settings.company_address = address
+ site_settings.save()
+
+ price = manager.calculate_order_total(order, order.lines.all())
+ price = quantize_price(price, price.currency)
+ assert price == TaxedMoney(net=Money("44.71", "USD"), gross=Money("55.00", "USD"))
+
+
+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
+def test_calculate_order_total_gift_promotion(
+ order_with_lines_and_gift_promotion,
+ shipping_zone,
+ site_settings,
+ address,
+ plugin_configuration,
+):
+ plugin_configuration()
+ manager = get_plugins_manager(allow_replica=False)
+ order = order_with_lines_and_gift_promotion
+ method = shipping_zone.shipping_methods.get()
+ order.shipping_address = order.billing_address.get_copy()
+ order_set_shipping_method(order, method)
+ order.save()
+
+ site_settings.company_address = address
+ site_settings.save()
+
+ price = manager.calculate_order_total(order, order.lines.all())
+ price = quantize_price(price, price.currency)
+ assert price == TaxedMoney(net=Money("65.04", "USD"), gross=Money("80.00", "USD"))
+
+
@pytest.mark.vcr
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_calculate_order_shipping_entire_order_voucher(
diff --git a/saleor/tax/calculations/order.py b/saleor/tax/calculations/order.py
index 0d88de8cb5..d05c7bf174 100644
--- a/saleor/tax/calculations/order.py
+++ b/saleor/tax/calculations/order.py
@@ -68,18 +68,20 @@ def update_order_prices_with_flat_rates(
)
order.shipping_tax_rate = normalize_tax_rate_for_db(shipping_tax_rate)
- # Calculate order total.
- order.undiscounted_total = undiscounted_subtotal + order.base_shipping_price
- order.total = _calculate_order_total(
- order, lines, database_connection_name=database_connection_name
+ _set_order_totals(
+ order,
+ lines,
+ prices_entered_with_tax,
+ database_connection_name=database_connection_name,
)
-def _calculate_order_total(
+def _set_order_totals(
order: "Order",
lines: Iterable["OrderLine"],
+ prices_entered_with_tax: bool,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-) -> TaxedMoney:
+):
currency = order.currency
default_value = base_calculations.base_order_total(
@@ -87,16 +89,28 @@ def _calculate_order_total(
)
default_value = TaxedMoney(default_value, default_value)
if default_value <= zero_taxed_money(currency):
- return quantize_price(default_value, currency)
+ order.total = quantize_price(default_value, currency)
+ order.undiscounted_total = quantize_price(default_value, currency)
+ order.subtotal = quantize_price(default_value, currency)
+ return
- total = zero_taxed_money(currency)
+ subtotal = zero_taxed_money(currency)
undiscounted_subtotal = zero_taxed_money(currency)
for line in lines:
- total += line.total_price
+ subtotal += line.total_price
undiscounted_subtotal += line.undiscounted_total_price
- total += order.shipping_price
- return quantize_price(max(total, zero_taxed_money(currency)), currency)
+ shipping_tax_rate = order.shipping_tax_rate or 0
+ undiscounted_shipping_price = calculate_flat_rate_tax(
+ order.base_shipping_price,
+ Decimal(shipping_tax_rate * 100),
+ prices_entered_with_tax,
+ )
+ undiscounted_total = undiscounted_subtotal + undiscounted_shipping_price
+
+ order.total = quantize_price(subtotal + order.shipping_price, currency)
+ order.undiscounted_total = quantize_price(undiscounted_total, currency)
+ order.subtotal = quantize_price(subtotal, currency)
def _calculate_order_shipping(
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index 9b9d07239a..c026cda0be 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -7,7 +7,7 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import add_variant_to_checkout
from ...core.prices import quantize_price
from ...core.taxes import zero_taxed_money
-from ...discount.utils import create_discount_objects_for_order_promotions
+from ...discount.utils import create_checkout_discount_objects_for_order_promotions
from ...plugins.manager import get_plugins_manager
from ...tax.models import TaxClassCountryRate
from .. import TaxCalculationStrategy
@@ -880,7 +880,7 @@ def test_calculate_checkout_line_total_discount_from_order_promotion(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
checkout_line_info = lines[0]
- create_discount_objects_for_order_promotions(checkout_info, lines)
+ create_checkout_discount_objects_for_order_promotions(checkout_info, lines)
# when
line_price = calculate_checkout_line_total(
@@ -928,7 +928,7 @@ def test_calculate_checkout_line_total_discount_for_gift_line(
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, manager)
checkout_line_info = [line_info for line_info in lines if line_info.line.is_gift][0]
- create_discount_objects_for_order_promotions(checkout_info, lines)
+ create_checkout_discount_objects_for_order_promotions(checkout_info, lines)
# when
line_price = calculate_checkout_line_total(
diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.py
index e8daf7c612..1074037fcd 100644
--- a/saleor/tax/tests/test_order_calculations.py
+++ b/saleor/tax/tests/test_order_calculations.py
@@ -77,7 +77,7 @@ def test_calculations_calculate_order_undiscounted_total(
# then
assert order.undiscounted_total == TaxedMoney(
- net=Money("80.00", "USD"), gross=Money("80.00", "USD")
+ net=Money("65.04", "USD"), gross=Money("80.00", "USD")
)
diff --git a/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py b/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
index 13edade740..2bf3b3e34c 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_product_with_percentage_promotion.py
@@ -124,8 +124,8 @@ def test_order_products_on_percentage_promotion_CORE_2103(
product_price = order_line["undiscountedUnitPrice"]["gross"]["amount"]
assert product_price == float(product_variant_price)
assert discount == order_line["unitDiscount"]["amount"]
- assert order_line["unitDiscountType"] == "FIXED"
- assert order_line["unitDiscountValue"] == discount
+ assert order_line["unitDiscountType"] == "PERCENTAGE"
+ assert order_line["unitDiscountValue"] == discount_value
assert order_line["unitDiscountReason"] == promotion_reason
product_discounted_price = product_price - discount
assert product_discounted_price == order_line["unitPrice"]["gross"]["amount"]
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py
index e6b719f323..7fd8086ee1 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_percentage_sale.py
@@ -148,8 +148,8 @@ def test_order_products_on_percentage_sale_CORE_1003(
order_line = order["order"]["lines"][0]
assert order_line["unitDiscount"]["amount"] == discount
- assert order_line["unitDiscountValue"] == discount
- assert order_line["unitDiscountType"] == "FIXED"
+ assert order_line["unitDiscountValue"] == sale_discount_value
+ assert order_line["unitDiscountType"] == "PERCENTAGE"
assert draft_line["unitDiscountReason"] == f"Sale: {sale_id}"
product_price = order_line["undiscountedUnitPrice"]["gross"]["amount"]
assert product_price == undiscounted_price
diff --git a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
index 8965e3f9a0..4877ca7dd4 100644
--- a/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
+++ b/saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py
@@ -161,8 +161,8 @@ def test_order_products_on_promotion_and_manual_order_discount_CORE_2108(
)
assert product_price == product_variant_price
assert order_line["unitDiscount"]["amount"] == promotion_value
- assert order_line["unitDiscountType"] == "FIXED"
- assert order_line["unitDiscountValue"] == promotion_value
+ assert order_line["unitDiscountType"] == "PERCENTAGE"
+ assert order_line["unitDiscountValue"] == promotion_discount_value
assert order_line["unitDiscountReason"] == promotion_reason
product_discounted_price = product_price - promotion_value
shipping_amount = quantize_price(
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 1c24734f9b..f4f558fc7d 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -488,8 +488,6 @@ def checkout_with_item_on_promotion(checkout_with_item):
variant = line.variant
- channel = checkout_with_item.channel
-
reward_value = Decimal("5")
rule = promotion.rules.create(
catalogue_predicate={
@@ -5071,7 +5069,122 @@ def order_with_lines_for_cc(
@pytest.fixture
-def order_fulfill_data(order_with_lines, warehouse):
+def order_with_lines_and_catalogue_promotion(
+ order_with_lines, channel_USD, catalogue_promotion_without_rules
+):
+ order = order_with_lines
+ promotion = catalogue_promotion_without_rules
+ line = order.lines.get(quantity=3)
+ variant = line.variant
+ reward_value = Decimal(3)
+ rule = promotion.rules.create(
+ name="Catalogue rule fixed",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant)]
+ }
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel_USD)
+
+ listing = variant.channel_listings.get(channel=channel_USD)
+ listing.discounted_price_amount = listing.price_amount - reward_value
+ listing.save(update_fields=["discounted_price_amount"])
+ listing.variantlistingpromotionrule.create(
+ promotion_rule=rule,
+ discount_amount=reward_value,
+ currency=order.currency,
+ )
+
+ line.discounts.create(
+ type=DiscountType.PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=reward_value,
+ amount_value=reward_value * line.quantity,
+ currency=order.currency,
+ promotion_rule=rule,
+ )
+ return order
+
+
+def order_with_lines_and_order_promotion(
+ order_with_lines,
+ channel_USD,
+ order_promotion_without_rules,
+):
+ order = order_with_lines
+ promotion = order_promotion_without_rules
+ rule = promotion.rules.create(
+ name="Fixed subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_value_type=RewardValueType.FIXED,
+ reward_value=Decimal(25),
+ reward_type=RewardType.SUBTOTAL_DISCOUNT,
+ )
+ rule.channels.add(channel_USD)
+
+ order.discounts.create(
+ promotion_rule=rule,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=rule.reward_value_type,
+ value=rule.reward_value,
+ amount_value=rule.reward_value,
+ currency=order.currency,
+ )
+ return order
+
+
+def order_with_lines_and_gift_promotion(
+ order_with_lines,
+ channel_USD,
+ order_promotion_without_rules,
+ variant_with_many_stocks,
+):
+ order = order_with_lines
+ variant = variant_with_many_stocks
+ variant_listing = variant.channel_listings.get(channel=channel_USD)
+ promotion = order_promotion_without_rules
+ rule = promotion.rules.create(
+ name="Gift subtotal rule",
+ order_predicate={
+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}
+ },
+ reward_type=RewardType.GIFT,
+ )
+ rule.channels.add(channel_USD)
+ rule.gifts.set([variant])
+
+ gift_line = order.lines.create(
+ quantity=1,
+ variant=variant,
+ is_gift=True,
+ currency=order.currency,
+ unit_price_net_amount=0,
+ unit_price_gross_amount=0,
+ total_price_net_amount=0,
+ total_price_gross_amount=0,
+ is_shipping_required=True,
+ is_gift_card=False,
+ )
+ gift_line.discounts.create(
+ promotion_rule=rule,
+ type=DiscountType.ORDER_PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=variant_listing.price_amount,
+ amount_value=variant_listing.price_amount,
+ currency=order.currency,
+ )
+ return order
+
+
+def order_fulfill_data(order_with_lines, warehouse, checkout):
FulfillmentData = namedtuple("FulfillmentData", "order variables warehouse")
order = order_with_lines
order_id = graphene.Node.to_global_id("Order", order.id)
diff --git a/saleor/tests/utils.py b/saleor/tests/utils.py
index bd18d48214..bb677fc9c1 100644
--- a/saleor/tests/utils.py
+++ b/saleor/tests/utils.py
@@ -1,4 +1,6 @@
import json
+import math
+from decimal import Decimal
from django.db import connections, transaction
@@ -21,3 +23,11 @@ def flush_post_commit_hooks():
def dummy_editorjs(text, json_format=False):
data = {"blocks": [{"data": {"text": text}, "type": "paragraph"}]}
return json.dumps(data) if json_format else data
+
+
+def round_down(price: Decimal) -> Decimal:
+ return Decimal(math.floor(price * 100)) / 100
+
+
+def round_up(price: Decimal) -> Decimal:
+ return Decimal(math.ceil(price * 100)) / 100