Skip to content

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

Use denormalized prices during order update (#17160)

Piotr Zabieglikcd42e8a63183
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4cf4d94ff1..bf8c39d492 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -85,3 +85,6 @@ All notable, unreleased changes to this project will be documented in this file.
- Fixed Celery worker issues when using SQS by using celery[sqs] extras instead of direct pycurl dependency - by @mariobrgomes
- Added [`alg`](https://datatracker.ietf.org/doc/html/rfc7517#section-4.4) key to JWKS available at `/.well-known/jwks.json` - #17363 by @lkostrowski
- `checkout.shippingMethods` and `checkout.availableShippingMethods` will no longer return external shipping methods if their currency differs from the checkout's currency - #17350 by @korycins
+- Use denormalized base prices during order update - #17160 by @zedzior
+ - `UNCONFIRMED` orders will never refresh its base prices
+ - `DRAFT` orders will refresh its base prices after default 24 hours
diff --git a/saleor/celeryconf.py b/saleor/celeryconf.py
index 7e83024081..b09be0731b 100644
--- a/saleor/celeryconf.py
+++ b/saleor/celeryconf.py
@@ -27,5 +27,11 @@ app = Celery("saleor", task_cls="saleor.core.tasks:RestrictWriterDBTask")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
+app.autodiscover_tasks(
+ packages=[
+ "saleor.order.migrations.tasks",
+ ],
+ related_name="saleor3_21",
+)
app.autodiscover_tasks(lambda: discover_plugins_modules(settings.PLUGINS)) # type: ignore[misc] # circular import # noqa: E501
app.autodiscover_tasks(related_name="search_tasks")
diff --git a/saleor/channel/migrations/0019_channel_draft_order_line_price_freeze_period.py b/saleor/channel/migrations/0019_channel_draft_order_line_price_freeze_period.py
new file mode 100644
index 0000000000..f201166395
--- /dev/null
+++ b/saleor/channel/migrations/0019_channel_draft_order_line_price_freeze_period.py
@@ -0,0 +1,25 @@
+# Generated by Django 4.2.16 on 2025-02-21 14:16
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("channel", "0018_channel_automatically_complete_paid_checkouts"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="channel",
+ name="draft_order_line_price_freeze_period",
+ field=models.PositiveIntegerField(blank=True, default=24, null=True),
+ ),
+ migrations.RunSQL(
+ """
+ ALTER TABLE channel_channel
+ ALTER COLUMN draft_order_line_price_freeze_period
+ SET DEFAULT 24;
+ """,
+ migrations.RunSQL.noop,
+ ),
+ ]
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
index 899c2a55f5..9179a345fa 100644
--- a/saleor/channel/models.py
+++ b/saleor/channel/models.py
@@ -49,6 +49,11 @@ class Channel(ModelWithMetadata):
use_legacy_error_flow_for_checkout = models.BooleanField(default=True)
automatically_complete_fully_paid_checkouts = models.BooleanField(default=False)
+ # time in hours after which the draft order line price will be refreshed
+ draft_order_line_price_freeze_period = models.PositiveIntegerField(
+ default=24, null=True, blank=True
+ )
+
class Meta(ModelWithMetadata.Meta):
ordering = ("slug",)
app_label = "channel"
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index efdbf43046..f76cb8e4d9 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -14,7 +14,11 @@ from ..core.prices import quantize_price
from ..core.pricing.interface import LineInfo
from ..core.taxes import zero_money
from ..discount import VoucherType
-from ..discount.interface import fetch_variant_rules_info, fetch_voucher_info
+from ..discount.interface import (
+ VariantPromotionRuleInfo,
+ fetch_variant_rules_info,
+ fetch_voucher_info,
+)
from ..shipping.interface import ShippingMethodData
from ..shipping.models import ShippingMethod, ShippingMethodChannelListing
from ..shipping.utils import (
@@ -53,6 +57,9 @@ class CheckoutLineInfo(LineInfo):
product: "Product"
product_type: "ProductType"
discounts: list["CheckoutLineDiscount"]
+ rules_info: list["VariantPromotionRuleInfo"]
+ channel_listing: Optional["ProductVariantChannelListing"]
+
tax_class: Optional["TaxClass"] = None
@cached_property
@@ -417,7 +424,7 @@ def fetch_checkout_lines(
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
) -> tuple[list[CheckoutLineInfo], list[int]]:
"""Fetch checkout lines as CheckoutLineInfo objects."""
- from ..discount.utils.voucher import apply_voucher_to_line
+ from ..discount.utils.voucher import attach_voucher_to_line_info
from .utils import get_voucher_for_checkout
select_related_fields = ["variant__product__product_type__tax_class"]
@@ -516,7 +523,7 @@ def fetch_checkout_lines(
return lines_info, unavailable_variant_pks
if voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order:
voucher_info = fetch_voucher_info(voucher, checkout.voucher_code)
- apply_voucher_to_line(voucher_info, lines_info)
+ attach_voucher_to_line_info(voucher_info, lines_info)
return lines_info, unavailable_variant_pks
diff --git a/saleor/core/pricing/interface.py b/saleor/core/pricing/interface.py
index 9cda0e1c0d..3c7057c269 100644
--- a/saleor/core/pricing/interface.py
+++ b/saleor/core/pricing/interface.py
@@ -7,7 +7,6 @@ from ...discount import DiscountType
if TYPE_CHECKING:
from ...channel.models import Channel
from ...checkout.models import CheckoutLine
- from ...discount.interface import VariantPromotionRuleInfo
from ...discount.models import CheckoutLineDiscount, OrderLineDiscount, Voucher
from ...order.models import OrderLine
from ...product.models import (
@@ -15,7 +14,6 @@ if TYPE_CHECKING:
Product,
ProductType,
ProductVariant,
- ProductVariantChannelListing,
)
@@ -26,10 +24,8 @@ class LineInfo:
product: Optional["Product"]
product_type: Optional["ProductType"]
collections: list["Collection"]
- channel_listing: Optional["ProductVariantChannelListing"]
channel: "Channel"
discounts: Iterable[Union["OrderLineDiscount", "CheckoutLineDiscount"]]
- rules_info: list["VariantPromotionRuleInfo"]
voucher: Optional["Voucher"]
voucher_code: str | None
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index 43f29ba913..77e40b3f17 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -24,11 +24,11 @@ from ..utils.promotion import (
)
from ..utils.shared import discount_info_for_logs
from ..utils.voucher import (
- _get_the_cheapest_line,
activate_voucher_code,
add_voucher_usage_by_customer,
deactivate_voucher_code,
decrease_voucher_code_usage_value,
+ get_the_cheapest_line,
increase_voucher_code_usage_value,
is_order_level_voucher,
remove_voucher_usage_by_customer,
@@ -648,7 +648,7 @@ def test_is_order_level_voucher_another_type(voucher_type, voucher):
def test_get_the_cheapest_line_no_lines_provided():
# when
- line_info = _get_the_cheapest_line(None)
+ line_info = get_the_cheapest_line(None)
# then
assert line_info is None
@@ -672,7 +672,7 @@ def test_get_the_cheapest_line(checkout_with_items, channel_USD):
for line in checkout_with_items.lines.all()
]
# when
- line_info = _get_the_cheapest_line(lines)
+ line_info = get_the_cheapest_line(lines)
# then
assert line_info == lines[0]
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
index 3e44daf08b..172ec7c8f6 100644
--- 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
@@ -5,7 +5,7 @@ import graphene
from ....order.fetch import fetch_draft_order_lines_info
from ... import DiscountType, DiscountValueType
from ...models import PromotionRule
-from ...utils.order import _copy_unit_discount_data_to_order_line
+from ...utils.order import update_unit_discount_data_on_order_line
def test_copy_unit_discount_data_to_order_line_multiple_discounts(
@@ -38,7 +38,7 @@ def test_copy_unit_discount_data_to_order_line_multiple_discounts(
lines_info = fetch_draft_order_lines_info(order)
# when
- _copy_unit_discount_data_to_order_line(lines_info)
+ update_unit_discount_data_on_order_line(lines_info)
# then
line = lines_info[0].line
@@ -68,7 +68,7 @@ def test_copy_unit_discount_data_to_order_line_single_discount(
lines_info = fetch_draft_order_lines_info(order)
# when
- _copy_unit_discount_data_to_order_line(lines_info)
+ update_unit_discount_data_on_order_line(lines_info)
# then
line = lines_info[0].line
@@ -86,7 +86,7 @@ def test_copy_unit_discount_data_to_order_line_no_discount(order_with_lines):
lines_info = fetch_draft_order_lines_info(order)
# when
- _copy_unit_discount_data_to_order_line(lines_info)
+ update_unit_discount_data_on_order_line(lines_info)
# then
line = lines_info[0].line
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 4414b6b940..7a25f7fdd2 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
@@ -2303,7 +2303,7 @@ def test_create_checkout_line_discount_objects_for_catalogue_promotions_race_con
create_checkout_line_discount_objects_for_catalogue_promotions(lines_info)
with race_condition.RunBefore(
- "saleor.discount.utils.promotion.prepare_line_discount_objects_for_catalogue_promotions",
+ "saleor.discount.utils.checkout.prepare_checkout_line_discount_objects_for_catalogue_promotions",
call_before_creating_catalogue_line_discount,
):
lines_info, _ = fetch_checkout_lines(checkout)
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
index bd0938c6db..4b4e80dc55 100644
--- 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
@@ -9,8 +9,12 @@ from ....product.models import (
)
from ....warehouse.models import Stock
from ... import DiscountType, RewardType, RewardValueType
+from ...interface import VariantPromotionRuleInfo, fetch_variant_rules_info
from ...models import OrderDiscount, OrderLineDiscount
-from ...utils.order import create_or_update_discount_objects_from_promotion_for_order
+from ...utils.order import (
+ create_order_discount_objects_for_order_promotions,
+ create_order_line_discount_objects_for_catalogue_promotions,
+)
def test_create_catalogue_discount_fixed(
@@ -50,10 +54,12 @@ def test_create_catalogue_discount_fixed(
discount_amount=reward_value,
currency=currency,
)
- lines_info = fetch_draft_order_lines_info(order)
+ rules_info = fetch_variant_rules_info(listing, "en")
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_line_discount_objects_for_catalogue_promotions(
+ line_1, rules_info, channel
+ )
# then
assert OrderLineDiscount.objects.count() == 1
@@ -68,9 +74,6 @@ def test_create_catalogue_discount_fixed(
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,
@@ -110,10 +113,12 @@ def test_create_catalogue_discount_percentage(
discount_amount=discount_amount,
currency=currency,
)
- lines_info = fetch_draft_order_lines_info(order)
+ rules_info = fetch_variant_rules_info(listing, "en")
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_line_discount_objects_for_catalogue_promotions(
+ line_1, rules_info, channel
+ )
# then
assert OrderLineDiscount.objects.count() == 1
@@ -129,9 +134,6 @@ def test_create_catalogue_discount_percentage(
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
@@ -156,7 +158,7 @@ def test_create_order_discount_subtotal_fixed(
lines_info = fetch_draft_order_lines_info(order)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
assert OrderDiscount.objects.count() == 1
@@ -196,7 +198,7 @@ def test_create_order_discount_subtotal_percentage(
lines_info = fetch_draft_order_lines_info(order)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
assert OrderDiscount.objects.count() == 1
@@ -236,7 +238,7 @@ def test_create_order_discount_gift(
lines_info = fetch_draft_order_lines_info(order)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
assert OrderLineDiscount.objects.count() == 1
@@ -288,7 +290,7 @@ def test_multiple_rules_subtotal_and_catalogue_discount_applied(
)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
order.refresh_from_db()
@@ -319,8 +321,15 @@ def test_multiple_rules_gift_and_catalogue_discount_applied(draft_order_and_prom
rule_total.reward_value = Decimal(0)
rule_total.save(update_fields=["reward_value"])
+ 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)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
order.refresh_from_db()
@@ -354,6 +363,7 @@ def test_multiple_rules_no_discount_applied(
):
# given
order, rule_catalogue, rule_total, rule_gift = draft_order_and_promotions
+ OrderLineDiscount.objects.all().delete()
rule_total.order_predicate = {
"discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100000}}}
}
@@ -381,72 +391,13 @@ def test_multiple_rules_no_discount_applied(
lines_info = fetch_draft_order_lines_info(order)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(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
):
@@ -471,7 +422,7 @@ def test_update_order_discount_subtotal(
lines_info = fetch_draft_order_lines_info(order)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
assert OrderDiscount.objects.count() == 1
@@ -506,7 +457,7 @@ def test_update_gift_discount_new_gift_available(
lines_info = fetch_draft_order_lines_info(order)
# when
- create_or_update_discount_objects_from_promotion_for_order(order, lines_info)
+ create_order_discount_objects_for_order_promotions(order, lines_info)
# then
assert OrderLineDiscount.objects.count() == 1
@@ -524,3 +475,70 @@ def test_update_gift_discount_new_gift_available(
assert gift_line.quantity == 1
assert gift_line.variant == variant
+
+
+def test_create_multiple_catalogue_discounts_for_the_same_line_is_not_allowed(
+ order_line,
+ catalogue_promotion,
+ promotion_translation_fr,
+ promotion_rule_translation_fr,
+):
+ # given
+ promotion = catalogue_promotion
+ rules = promotion.rules.all()
+ rule_1 = rules[0]
+ rule_2 = rules[1]
+
+ order = order_line.order
+ variant = order_line.variant
+ variant_channel_listing = variant.channel_listings.get(
+ channel_id=order_line.order.channel_id
+ )
+
+ (
+ listing_promotion_rule_1,
+ listing_promotion_rule_2,
+ ) = VariantChannelListingPromotionRule.objects.bulk_create(
+ [
+ VariantChannelListingPromotionRule(
+ variant_channel_listing=variant_channel_listing,
+ promotion_rule=rule_1,
+ discount_amount=Decimal("10.0"),
+ currency=order.currency,
+ ),
+ VariantChannelListingPromotionRule(
+ variant_channel_listing=variant_channel_listing,
+ promotion_rule=rule_2,
+ discount_amount=Decimal("5.0"),
+ currency=order.currency,
+ ),
+ ]
+ )
+
+ promotion_rule_translation_fr.promotion_rule = rule_1
+ promotion_rule_translation_fr.save(update_fields=["promotion_rule"])
+
+ rules_info = [
+ VariantPromotionRuleInfo(
+ rule=rule_1,
+ variant_listing_promotion_rule=listing_promotion_rule_1,
+ promotion=promotion,
+ promotion_translation=promotion_translation_fr,
+ rule_translation=promotion_rule_translation_fr,
+ ),
+ VariantPromotionRuleInfo(
+ rule=rule_2,
+ variant_listing_promotion_rule=listing_promotion_rule_2,
+ promotion=promotion,
+ promotion_translation=promotion_translation_fr,
+ rule_translation=None,
+ ),
+ ]
+
+ # when
+ create_order_line_discount_objects_for_catalogue_promotions(
+ order_line, rules_info, order.channel
+ )
+
+ # then
+ assert order_line.discounts.count() == 1
diff --git a/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py b/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
new file mode 100644
index 0000000000..997038981a
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_create_voucher_discount_object_for_order.py
@@ -0,0 +1,1067 @@
+from decimal import Decimal
+
+import graphene
+
+from ....core.prices import Money, quantize_price
+from ....core.taxes import zero_money
+from ....order import OrderStatus
+from ....order.calculations import fetch_order_prices_if_expired
+from ... import DiscountType, DiscountValueType, VoucherType
+from ...models import (
+ OrderDiscount,
+ OrderLineDiscount,
+ PromotionRule,
+)
+from ...utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
+
+
+def test_create_discount_for_voucher_specific_product_fixed(
+ order_with_lines,
+ voucher_specific_product_type,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ voucher = voucher_specific_product_type
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ unit_discount_amount = Decimal("5")
+ voucher_listing.discount_value = unit_discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = unit_discount_amount * discounted_line.quantity
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == voucher.discount_value_type
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert discounted_line.unit_discount_value == unit_discount_amount
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_value == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert (
+ line_discount.value_type
+ == DiscountValueType.FIXED
+ == voucher.discount_value_type
+ )
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == unit_discount_amount
+
+
+def test_create_discount_for_voucher_specific_product_percentage(
+ order_with_lines,
+ voucher_specific_product_type,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ voucher = voucher_specific_product_type
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("10")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = (
+ discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * discount_value
+ / 100
+ )
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.PERCENTAGE
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert discounted_line.unit_discount_value == discount_value
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert (
+ line_discount.value_type
+ == voucher.discount_value_type
+ == DiscountValueType.PERCENTAGE
+ )
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_value
+
+
+def test_create_discount_for_voucher_apply_once_per_order_percentage(
+ order_with_lines,
+ voucher,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("10")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ discounted_line, line_1 = lines
+ discount_amount = (
+ discounted_line.undiscounted_base_unit_price_amount * discount_value / 100
+ )
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount - discount_amount
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - discount_amount) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+ assert quantize_price(
+ discounted_line.base_unit_price_amount, currency
+ ) == quantize_price(
+ discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount,
+ currency,
+ )
+ assert discounted_line.total_price_gross_amount == quantize_price(
+ discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate,
+ currency,
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.PERCENTAGE
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert (
+ line_discount.value_type
+ == voucher.discount_value_type
+ == DiscountValueType.PERCENTAGE
+ )
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_value
+
+
+def test_create_discount_for_voucher_apply_once_per_order_fixed(
+ order_with_lines,
+ voucher,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = Decimal("5")
+ voucher_listing.discount_value = discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ discounted_line, line_1 = lines
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount - discount_amount
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - discount_amount) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+
+ unit_discount_amount = discount_amount / discounted_line.quantity
+
+ assert quantize_price(
+ discounted_line.base_unit_price_amount, currency
+ ) == quantize_price(
+ discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount,
+ currency,
+ )
+ assert discounted_line.total_price_gross_amount == quantize_price(
+ discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate,
+ currency,
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == unit_discount_amount
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == discount_amount
+ assert line_discount.value_type == DiscountValueType.FIXED
+ assert line_discount.type == DiscountType.VOUCHER
+ assert line_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert line_discount.value == discount_amount
+
+
+def test_create_discount_for_voucher_entire_order_fixed(
+ order_with_lines,
+ voucher,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ assert voucher.type == VoucherType.ENTIRE_ORDER
+ assert voucher.discount_value_type == DiscountValueType.FIXED
+
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = Decimal("35")
+ voucher_listing.discount_value = discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.name = "Voucher name"
+ voucher.save(update_fields=["name"])
+
+ order.voucher = voucher
+ code = voucher.codes.first().code
+ order.voucher_code = code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ lines = order.lines.all()
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.first()
+ assert discount.voucher == voucher
+ assert discount.value_type == voucher.discount_value_type
+ assert discount.value == discount_amount
+ assert discount.amount_value == discount_amount
+ assert discount.reason == f"Voucher code: {code}"
+ assert discount.name == voucher.name
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.voucher_code == code
+ # TODO (SHOPX-914): set translated voucher name
+ assert discount.translated_name == ""
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+
+ 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]
+
+ 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 = discount_amount * line_1_base_total / base_total
+ line_2_order_discount_portion = discount_amount - line_1_order_discount_portion
+
+ 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_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ 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
+
+ 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_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.unit_price_net_amount == line_2_total_net_amount / line_2.quantity
+
+
+def test_create_discount_for_voucher_entire_order_multiple_lines(
+ order,
+ voucher,
+ plugins_manager,
+ order_lines_generator,
+ product_list,
+ tax_configuration_flat_rates,
+):
+ # given
+ assert voucher.type == VoucherType.ENTIRE_ORDER
+ assert voucher.discount_value_type == DiscountValueType.FIXED
+
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_amount = Decimal("3")
+ voucher_listing.discount_value = discount_amount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.name = "Voucher name"
+ voucher.save(update_fields=["name"])
+
+ code = voucher.codes.first().code
+ order.voucher = voucher
+ order.voucher_code = code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+
+ variant_list = [product.variants.first() for product in product_list[:3]]
+ unit_prices = [7, 33, 25]
+ quantities = [1, 1, 1]
+ lines = order_lines_generator(order, variant_list, unit_prices, quantities)
+
+ subtotal = Money(sum(unit_prices), currency)
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.first()
+ assert discount.voucher == voucher
+ assert discount.value_type == voucher.discount_value_type
+ assert discount.value == discount_amount
+ assert discount.amount_value == discount_amount
+ assert discount.reason == f"Voucher code: {code}"
+ assert discount.name == voucher.name
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.voucher_code == code
+ # TODO (SHOPX-914): set translated voucher name
+ assert discount.translated_name == ""
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount - discount_amount
+ assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+
+ remaining_discount = discount_amount
+ for idx, line in enumerate(lines):
+ line.refresh_from_db()
+ idx = variant_list.index(line.variant)
+ base_price = unit_prices[idx]
+ line_base_total = base_price
+ if idx < len(lines) - 1:
+ line_order_discount_portion = quantize_price(
+ discount_amount * line_base_total / subtotal.amount, currency
+ )
+ remaining_discount -= line_order_discount_portion
+ else:
+ line_order_discount_portion = remaining_discount
+
+ line_total_net_amount = (
+ line.undiscounted_total_price_net_amount - line_order_discount_portion
+ )
+ assert line.undiscounted_total_price_net_amount == base_price
+ assert line.undiscounted_unit_price_net_amount == base_price
+ assert line.total_price_net_amount == line_total_net_amount
+ assert line.base_unit_price_amount == base_price
+ assert line.unit_price_net_amount == line_total_net_amount
+
+
+def test_create_discount_for_voucher_entire_order_percentage(
+ order_with_lines,
+ voucher,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ assert voucher.type == VoucherType.ENTIRE_ORDER
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("50")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.name = "Voucher name"
+ voucher.save(update_fields=["name"])
+
+ order.voucher = voucher
+ code = voucher.codes.first().code
+ order.voucher_code = code
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ subtotal = zero_money(currency)
+ lines = order.lines.all()
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.first()
+ assert discount.voucher == voucher
+ assert discount.value_type == voucher.discount_value_type
+ assert discount.value == discount_value
+ assert discount.amount_value == Decimal(subtotal.amount / 2)
+ assert discount.reason == f"Voucher code: {code}"
+ assert discount.name == voucher.name
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.voucher_code == code
+ # TODO (SHOPX-914): set translated voucher name
+ assert discount.translated_name == ""
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == Decimal(subtotal.amount / 2)
+ assert order.subtotal_gross_amount == Decimal(subtotal.amount / 2) * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == subtotal + shipping_price
+ assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+
+ 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]
+
+ 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 / 2,
+ currency,
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == variant_1_undiscounted_unit_price * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
+ )
+ assert line_1.total_price_net_amount == line_1_total_net_amount
+ 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
+
+ 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 / 2,
+ currency,
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == variant_2_undiscounted_unit_price * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
+ )
+ assert line_2.total_price_net_amount == line_2_total_net_amount
+ assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
+ assert line_2.unit_price_net_amount == line_2_total_net_amount / line_2.quantity
+
+
+def test_create_discount_for_voucher_shipping_fixed(
+ order_with_lines,
+ voucher,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ voucher.type = VoucherType.SHIPPING
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["type", "discount_value_type"])
+
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("5")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.name = "Voucher shipping"
+ voucher.save(update_fields=["name"])
+
+ order.voucher = voucher
+ code = voucher.codes.first().code
+ order.voucher_code = code
+
+ undiscounted_shipping_price = order.shipping_price.net.amount
+ expected_shipping_price = Decimal(undiscounted_shipping_price - discount_value)
+ currency = order.currency
+ subtotal = zero_money(currency)
+ lines = order.lines.all()
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.first()
+ assert discount.voucher == voucher
+ assert discount.value_type == voucher.discount_value_type
+ assert discount.value == discount_value
+ assert (
+ discount.amount_value == undiscounted_shipping_price - expected_shipping_price
+ )
+ assert discount.reason == f"Voucher code: {code}"
+ assert discount.name == voucher.name
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.voucher_code == code
+ # TODO (SHOPX-914): set translated voucher name
+ assert discount.translated_name == ""
+
+ assert order.undiscounted_base_shipping_price_amount == undiscounted_shipping_price
+ assert order.base_shipping_price_amount == expected_shipping_price
+ assert order.shipping_price_net_amount == expected_shipping_price
+ assert order.shipping_price_gross.amount == expected_shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount
+ assert order.subtotal_gross_amount == subtotal.amount * tax_rate
+ assert order.total_net_amount == order.subtotal_net_amount + expected_shipping_price
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + expected_shipping_price) * tax_rate
+ )
+ assert (
+ order.undiscounted_total_net_amount
+ == subtotal.amount + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == (subtotal.amount + undiscounted_shipping_price) * tax_rate
+ )
+
+
+def test_create_discount_for_voucher_shipping_percentage(
+ order_with_lines,
+ voucher,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ voucher.type = VoucherType.SHIPPING
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["type", "discount_value_type"])
+
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ discount_value = Decimal("50")
+ voucher_listing.discount_value = discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.name = "Voucher shipping"
+ voucher.save(update_fields=["name"])
+
+ order.voucher = voucher
+ code = voucher.codes.first().code
+ order.voucher_code = code
+
+ undiscounted_shipping_price = order.shipping_price.net.amount
+ expected_shipping_price = Decimal(undiscounted_shipping_price / 2)
+ currency = order.currency
+ subtotal = zero_money(currency)
+ lines = order.lines.all()
+ for line in lines:
+ subtotal += line.base_unit_price * line.quantity
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
+ discount = order.discounts.first()
+ assert discount.voucher == voucher
+ assert discount.value_type == voucher.discount_value_type
+ assert discount.value == discount_value
+ assert (
+ discount.amount_value == undiscounted_shipping_price - expected_shipping_price
+ )
+ assert discount.reason == f"Voucher code: {code}"
+ assert discount.name == voucher.name
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.voucher_code == code
+ # TODO (SHOPX-914): set translated voucher name
+ assert discount.translated_name == ""
+
+ assert order.undiscounted_base_shipping_price.amount == undiscounted_shipping_price
+ assert order.base_shipping_price.amount == expected_shipping_price
+ assert order.shipping_price_net_amount == expected_shipping_price
+ assert order.shipping_price_gross.amount == expected_shipping_price * tax_rate
+ assert order.subtotal_net_amount == subtotal.amount
+ assert order.subtotal_gross_amount == subtotal.amount * tax_rate
+ assert order.total_net_amount == order.subtotal_net_amount + expected_shipping_price
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + expected_shipping_price) * tax_rate
+ )
+ assert (
+ order.undiscounted_total_net_amount
+ == subtotal.amount + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross_amount
+ == (subtotal.amount + undiscounted_shipping_price) * tax_rate
+ )
+
+
+def test_create_discount_for_voucher_specific_product_line_with_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_specific_product_type,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ currency = order.currency
+ order.status = OrderStatus.UNCONFIRMED
+ channel = order.channel
+ rule = PromotionRule.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion_id)
+ catalogue_reward_value = rule.reward_value
+ catalogue_reward_value_type = rule.reward_value_type
+ assert catalogue_reward_value_type == DiscountValueType.FIXED
+
+ line_1, line_2 = order.lines.all()
+ voucher = voucher_specific_product_type
+ voucher.products.set([])
+ voucher.variants.set([line_1.variant])
+ voucher_listing = voucher.channel_listings.get(channel=channel)
+ voucher_reward_value = voucher_listing.discount_value
+ voucher_reward_value_type = voucher.discount_value_type
+ assert voucher_reward_value_type == DiscountValueType.PERCENTAGE
+ order.voucher_code = voucher.codes.first().code
+ order.voucher = voucher
+ order.save(update_fields=["voucher_code", "voucher"])
+
+ tax_rate = Decimal("1.23")
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderLineDiscount.objects.count() == 2
+ assert not OrderDiscount.objects.exists()
+
+ line_1, line_2 = lines
+ catalogue_discount = line_1.discounts.get(type=DiscountType.PROMOTION)
+ catalogue_unit_discount_amount = catalogue_reward_value
+ catalogue_discount_amount = catalogue_unit_discount_amount * line_1.quantity
+ assert catalogue_discount.amount_value == catalogue_discount_amount
+ assert catalogue_discount.value == catalogue_reward_value
+ assert catalogue_discount.value_type == catalogue_reward_value_type
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.reason == f"Promotion: {promotion_id}"
+
+ voucher_discount = line_1.discounts.get(type=DiscountType.VOUCHER)
+ voucher_unit_discount_amount = (
+ voucher_reward_value
+ / 100
+ * (line_1.undiscounted_base_unit_price_amount - catalogue_unit_discount_amount)
+ )
+ voucher_discount_amount = voucher_unit_discount_amount * line_1.quantity
+ assert voucher_discount.amount_value == voucher_discount_amount
+ assert voucher_discount.value == voucher_reward_value
+ assert voucher_discount.value_type == voucher_reward_value_type
+ assert voucher_discount.type == DiscountType.VOUCHER
+ assert voucher_discount.reason == f"Voucher code: {order.voucher_code}"
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ assert (
+ line_1.undiscounted_base_unit_price_amount == variant_1_undiscounted_unit_price
+ )
+
+ 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
+ )
+
+ line_1_base_unit_price = (
+ variant_1_undiscounted_unit_price
+ - catalogue_unit_discount_amount
+ - voucher_unit_discount_amount
+ )
+ assert line_1.base_unit_price_amount == line_1_base_unit_price
+ assert line_1.unit_price_net_amount == line_1_base_unit_price
+ assert line_1.unit_price_gross_amount == quantize_price(
+ line_1_base_unit_price * tax_rate, currency
+ )
+ assert (
+ line_1.total_price_net_amount == line_1.unit_price_net_amount * line_1.quantity
+ )
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+
+ 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
+ - catalogue_discount_amount
+ - voucher_discount_amount
+ )
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+ assert order.subtotal_net_amount == order.total_net_amount - shipping_net_price
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+
+ assert (
+ line_1.unit_discount_amount
+ == catalogue_unit_discount_amount + voucher_unit_discount_amount
+ )
+ assert (
+ line_1.unit_discount_reason
+ == f"Promotion: {promotion_id}; Voucher code: {order.voucher_code}"
+ )
diff --git a/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py b/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
new file mode 100644
index 0000000000..530b0ae320
--- /dev/null
+++ b/saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
@@ -0,0 +1,1182 @@
+from decimal import Decimal
+
+import pytest
+from prices import Money
+
+from ....core.prices import quantize_price
+from ....core.taxes import zero_money
+from ....order import OrderStatus
+from ....order.calculations import fetch_order_prices_if_expired
+from ... import DiscountType, DiscountValueType, VoucherType
+from ...models import OrderDiscount, OrderLineDiscount, Voucher
+from ...utils.voucher import create_or_update_voucher_discount_objects_for_order
+
+
+def test_update_voucher_discount_specific_product_with_different_variants(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ for voucher in voucher_list:
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ Voucher.objects.bulk_update(voucher_list, ["discount_value_type", "type"])
+ voucher_1.variants.add(line_1.variant)
+ voucher_2.variants.add(line_2.variant)
+
+ # apply specific product voucher for line_1 variant
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_unit_discount_amount = voucher_listing_1.discount_value
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = voucher_1_unit_discount_amount * line_1.quantity
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - voucher_1_unit_discount_amount
+ )
+ assert discount_1.value == voucher_1_unit_discount_amount
+ assert discount_1.amount_value == discount_amount_1
+
+ # apply specific product voucher for line_2 variant
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_unit_discount_amount = voucher_listing_2.discount_value
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+ assert voucher_2_unit_discount_amount != voucher_1_unit_discount_amount
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ discount_2 = line_2.discounts.get()
+ discount_amount_2 = voucher_2_unit_discount_amount * line_2.quantity
+ assert discount_2.amount_value == discount_amount_2
+ assert discount_2.value_type == DiscountValueType.FIXED
+ assert discount_2.type == DiscountType.VOUCHER
+ assert discount_2.reason == f"Voucher code: {order.voucher_code}"
+ assert discount_2.value == voucher_2_unit_discount_amount
+
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - voucher_2_unit_discount_amount
+ )
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == voucher_2_unit_discount_amount
+ assert line_2.unit_discount_type == DiscountValueType.FIXED
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount - discount_amount_2
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - discount_amount_2) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+
+
+def test_update_voucher_discount_specific_product_with_apply_once_per_order(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ cheapest_line, line_2 = lines
+ assert cheapest_line.base_unit_price_amount < line_2.base_unit_price_amount
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.SPECIFIC_PRODUCT
+ voucher_1.variants.add(line_2.variant)
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.ENTIRE_ORDER
+ voucher_2.apply_once_per_order = True
+ Voucher.objects.bulk_update(
+ [voucher_1, voucher_2], ["discount_value_type", "type", "apply_once_per_order"]
+ )
+
+ # apply specific product voucher for line_2 variant
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_unit_discount_amount = voucher_listing_1.discount_value
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ cheapest_line, line_2 = lines
+ discount_1 = line_2.discounts.get()
+ discount_amount_1 = voucher_1_unit_discount_amount * line_2.quantity
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - voucher_1_unit_discount_amount
+ )
+ assert discount_1.value == voucher_1_unit_discount_amount
+ assert discount_1.amount_value == discount_amount_1
+ assert not cheapest_line.discounts.exists()
+
+ # apply voucher apply once per order type
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_discount_amount = voucher_listing_2.discount_value
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ cheapest_line, line_2 = lines
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ discount_2 = cheapest_line.discounts.get()
+ discount_amount_2 = voucher_2_discount_amount
+ assert discount_2.amount_value == discount_amount_2
+ assert discount_2.value_type == DiscountValueType.FIXED
+ assert discount_2.type == DiscountType.VOUCHER
+ assert discount_2.reason == f"Voucher code: {order.voucher_code}"
+ assert discount_2.value == voucher_2_discount_amount
+
+ unit_discount_amount_2 = discount_amount_2 / cheapest_line.quantity
+ assert quantize_price(
+ cheapest_line.base_unit_price_amount, currency
+ ) == quantize_price(
+ cheapest_line.undiscounted_base_unit_price_amount - unit_discount_amount_2,
+ currency,
+ )
+ assert cheapest_line.total_price_gross_amount == quantize_price(
+ cheapest_line.base_unit_price_amount * cheapest_line.quantity * tax_rate,
+ currency,
+ )
+ assert (
+ cheapest_line.undiscounted_total_price_gross_amount
+ == cheapest_line.undiscounted_base_unit_price_amount
+ * cheapest_line.quantity
+ * tax_rate
+ )
+ assert cheapest_line.unit_discount_amount == unit_discount_amount_2
+ assert cheapest_line.unit_discount_type == DiscountValueType.FIXED
+ assert cheapest_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount - discount_amount_2
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - discount_amount_2) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+
+
+def test_update_voucher_discount_apply_once_per_order_with_specific_product(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ assert line_1.base_unit_price_amount < line_2.base_unit_price_amount
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.ENTIRE_ORDER
+ voucher_1.apply_once_per_order = True
+ voucher_2.type = VoucherType.SPECIFIC_PRODUCT
+ voucher_2.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher_2.variants.add(line_1.variant)
+ Voucher.objects.bulk_update(
+ [voucher_1, voucher_2], ["discount_value_type", "type", "apply_once_per_order"]
+ )
+
+ # apply voucher apply once per order type
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_discount_amount = voucher_listing_1.discount_value
+ voucher_1_unit_discount_amount = voucher_1_discount_amount / line_1.quantity
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ discount = line_1.discounts.get()
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - voucher_1_unit_discount_amount,
+ currency,
+ )
+ assert discount.value == voucher_1_discount_amount
+ assert discount.amount_value == voucher_1_discount_amount
+ assert not line_2.discounts.exists()
+
+ # apply specific product voucher for line 1 variant
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_discount_value = Decimal("20")
+ voucher_listing_2.discount_value = voucher_2_discount_value
+ voucher_listing_2.save(update_fields=["discount_value"])
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount
+ * (100 - voucher_2_discount_value)
+ / 100
+ )
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.unit_discount_amount
+ == line_1.undiscounted_base_unit_price_amount - line_1.base_unit_price_amount
+ )
+ assert (
+ line_1.unit_discount_type
+ == DiscountValueType.PERCENTAGE
+ == voucher_2.discount_value_type
+ )
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount.refresh_from_db()
+ assert discount.amount_value == line_1.unit_discount_amount * line_1.quantity
+ assert discount.value_type == DiscountValueType.PERCENTAGE
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+ assert discount.value == voucher_2_discount_value
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - line_1.unit_discount_amount * line_1.quantity
+ )
+ assert order.subtotal_gross_amount == order.subtotal_net_amount * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+
+
+def test_update_voucher_discount_specific_product_with_entire_order(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.SPECIFIC_PRODUCT
+ voucher_1.variants.add(line_2.variant)
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.ENTIRE_ORDER
+ voucher_2.apply_once_per_order = False
+ Voucher.objects.bulk_update(
+ [voucher_1, voucher_2], ["discount_value_type", "type", "apply_once_per_order"]
+ )
+
+ # apply specific product voucher for line 2 variant
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_unit_discount_amount = voucher_listing_1.discount_value
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ discount_1 = line_2.discounts.get()
+ discount_amount_1 = voucher_1_unit_discount_amount * line_2.quantity
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - voucher_1_unit_discount_amount
+ )
+ assert discount_1.value == voucher_1_unit_discount_amount
+ assert discount_1.amount_value == discount_amount_1
+ assert not line_1.discounts.exists()
+
+ # apply entire order voucher
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_discount_value = Decimal("20")
+ voucher_listing_2.discount_value = voucher_2_discount_value
+ voucher_listing_2.save(update_fields=["discount_value"])
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+
+ discount_2 = order.discounts.get()
+ assert discount_2.amount_value == voucher_2_discount_value
+ assert discount_2.value_type == DiscountValueType.FIXED
+ assert discount_2.type == DiscountType.VOUCHER
+ assert discount_2.reason == f"Voucher code: {order.voucher_code}"
+ assert discount_2.value == voucher_2_discount_value
+
+ assert order.base_shipping_price == shipping_price
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - voucher_2_discount_value
+ )
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - voucher_2_discount_value) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+
+ line_1, line_2 = lines
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ line_1_total_base_price = line_1.base_unit_price_amount * line_1.quantity
+ line_2_total_base_price = line_2.base_unit_price_amount * line_2.quantity
+ base_subtotal = line_1_total_base_price + line_2_total_base_price
+ line_1_discount_portion = (
+ line_1_total_base_price / base_subtotal * voucher_2_discount_value
+ )
+ line_2_discount_portion = voucher_2_discount_value - line_1_discount_portion
+
+ assert line_1.total_price_net_amount == quantize_price(
+ line_1_total_base_price - line_1_discount_portion, currency
+ )
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_value == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+ assert not line_1.discounts.exists()
+
+ assert line_2.total_price_net_amount == quantize_price(
+ line_2_total_base_price - line_2_discount_portion, currency
+ )
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_value == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert not line_2.discounts.exists()
+
+
+def test_update_voucher_discount_shipping_with_specific_product(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.SHIPPING
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.SPECIFIC_PRODUCT
+ voucher_2.variants.add(line_1.variant)
+ Voucher.objects.bulk_update([voucher_1, voucher_2], ["discount_value_type", "type"])
+
+ # apply shipping voucher
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_discount = Money(voucher_listing_1.discount_value, currency)
+ shipping_price_after_discount = undiscounted_shipping_price - voucher_1_discount
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == shipping_price_after_discount
+ assert order.shipping_price_net == shipping_price_after_discount
+ assert order.shipping_price_gross == quantize_price(
+ shipping_price_after_discount * tax_rate, currency
+ )
+ shipping_discount = order.discounts.get()
+ assert shipping_discount.amount == voucher_1_discount
+
+ # apply specific product voucher for line 1 variant
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_unit_discount = voucher_listing_2.discount_value
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+
+ discount_2 = line_1.discounts.get()
+ discount_amount_2 = voucher_2_unit_discount * line_1.quantity
+ assert discount_2.amount_value == discount_amount_2
+ assert discount_2.value_type == voucher_2.discount_value_type
+ assert discount_2.type == DiscountType.VOUCHER
+ assert discount_2.reason == f"Voucher code: {order.voucher_code}"
+ assert discount_2.value == voucher_2_unit_discount
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - voucher_2_unit_discount,
+ currency,
+ )
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == voucher_2_unit_discount
+ assert line_1.unit_discount_type == voucher_2.discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == voucher_2_unit_discount
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ with pytest.raises(OrderDiscount.DoesNotExist):
+ shipping_discount.refresh_from_db()
+ assert not order.discounts.exists()
+
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == undiscounted_shipping_price * tax_rate
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount - discount_amount_2
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - discount_amount_2) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+
+
+def test_update_voucher_discount_specific_product_with_shipping(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.SPECIFIC_PRODUCT
+ voucher_1.variants.add(line_1.variant)
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.SHIPPING
+ Voucher.objects.bulk_update([voucher_1, voucher_2], ["discount_value_type", "type"])
+
+ # apply specific product voucher for line 1 variant
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_unit_discount = voucher_listing_1.discount_value
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - voucher_1_unit_discount
+ )
+ discount_1 = line_1.discounts.get()
+ assert discount_1.amount_value == voucher_1_unit_discount * line_1.quantity
+
+ # apply shipping voucher
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_discount = Money(voucher_listing_2.discount_value, currency)
+ shipping_price_after_discount = undiscounted_shipping_price - voucher_2_discount
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+ assert line_1.unit_discount_value == 0
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+
+ shipping_discount = order.discounts.get()
+ assert shipping_discount.amount == voucher_2_discount
+ assert shipping_discount.value_type == voucher_2.discount_value_type
+ assert shipping_discount.type == DiscountType.VOUCHER
+ assert shipping_discount.reason == f"Voucher code: {order.voucher_code}"
+ assert shipping_discount.value == voucher_2_discount.amount
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == shipping_price_after_discount
+ assert order.shipping_price_net == shipping_price_after_discount
+ assert order.shipping_price_gross == quantize_price(
+ shipping_price_after_discount * tax_rate, currency
+ )
+
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount
+ assert order.subtotal_gross_amount == undiscounted_subtotal.amount * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert order.total_gross == quantize_price(
+ (order.undiscounted_total_net - voucher_2_discount) * tax_rate, currency
+ )
+
+
+def test_update_voucher_discount_shipping_with_entire_order(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.SHIPPING
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.ENTIRE_ORDER
+ Voucher.objects.bulk_update([voucher_1, voucher_2], ["discount_value_type", "type"])
+
+ # apply shipping voucher
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_discount = Money(voucher_listing_1.discount_value, currency)
+ shipping_price_after_discount = undiscounted_shipping_price - voucher_1_discount
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == shipping_price_after_discount
+ assert order.shipping_price_net == shipping_price_after_discount
+ assert order.shipping_price_gross == quantize_price(
+ shipping_price_after_discount * tax_rate, currency
+ )
+ discount = order.discounts.get()
+ assert discount.amount == voucher_1_discount
+
+ # apply entire order voucher
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_discount_value = Decimal("20")
+ voucher_listing_2.discount_value = voucher_2_discount_value
+ voucher_listing_2.save(update_fields=["discount_value"])
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ line_1_total_base_price = line_1.base_unit_price_amount * line_1.quantity
+ line_2_total_base_price = line_2.base_unit_price_amount * line_2.quantity
+ base_subtotal = line_1_total_base_price + line_2_total_base_price
+ line_1_discount_portion = (
+ line_1_total_base_price / base_subtotal * voucher_2_discount_value
+ )
+ line_2_discount_portion = voucher_2_discount_value - line_1_discount_portion
+
+ assert line_1.total_price_net_amount == quantize_price(
+ line_1_total_base_price - line_1_discount_portion, currency
+ )
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_total_price_net_amount * tax_rate
+ )
+
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_value == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+ assert not line_1.discounts.exists()
+
+ assert line_2.total_price_net_amount == quantize_price(
+ line_2_total_base_price - line_2_discount_portion, currency
+ )
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_total_price_net_amount * tax_rate
+ )
+
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_value == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert not line_2.discounts.exists()
+
+ discount.refresh_from_db()
+ assert discount.amount_value == voucher_2_discount_value
+ assert discount.value_type == voucher_2.discount_value_type
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+ assert discount.value == voucher_2_discount_value
+
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == undiscounted_shipping_price * tax_rate
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - voucher_2_discount_value
+ )
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - voucher_2_discount_value) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+
+
+def test_update_voucher_discount_entire_order_with_shipping(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.ENTIRE_ORDER
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.SHIPPING
+ Voucher.objects.bulk_update([voucher_1, voucher_2], ["discount_value_type", "type"])
+
+ # apply entire order voucher
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_discount = Money(voucher_listing_1.discount_value, currency)
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ assert order.subtotal_net_amount == quantize_price(
+ undiscounted_subtotal.amount - voucher_1_discount.amount, currency
+ )
+ assert order.total_net_amount == quantize_price(
+ order.subtotal_net_amount + undiscounted_shipping_price.amount, currency
+ )
+ discount = order.discounts.get()
+ assert discount.amount == voucher_1_discount
+
+ # apply shipping voucher
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_discount = Money(voucher_listing_2.discount_value, currency)
+ shipping_price_after_discount = undiscounted_shipping_price - voucher_2_discount
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+ assert line_1.unit_discount_value == 0
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ discount.refresh_from_db()
+ assert discount.amount == voucher_2_discount
+ assert discount.value_type == voucher_2.discount_value_type
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+ assert discount.value == voucher_2_discount.amount
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == shipping_price_after_discount
+ assert order.shipping_price_net == shipping_price_after_discount
+ assert order.shipping_price_gross == quantize_price(
+ shipping_price_after_discount * tax_rate, currency
+ )
+
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount
+ assert order.subtotal_gross_amount == undiscounted_subtotal.amount * tax_rate
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert order.total_gross == quantize_price(
+ (order.undiscounted_total_net - voucher_2_discount) * tax_rate, currency
+ )
+
+
+def test_update_voucher_discount_entire_order_with_specific_product(
+ order_with_lines,
+ plugins_manager,
+ tax_configuration_flat_rates,
+ voucher_list,
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare vouchers
+ voucher_1, voucher_2, _ = voucher_list
+ voucher_1.discount_value_type = DiscountValueType.FIXED
+ voucher_1.type = VoucherType.ENTIRE_ORDER
+ voucher_2.discount_value_type = DiscountValueType.FIXED
+ voucher_2.type = VoucherType.SPECIFIC_PRODUCT
+ voucher_2.variants.add(line_1.variant)
+ Voucher.objects.bulk_update([voucher_1, voucher_2], ["discount_value_type", "type"])
+
+ # apply entire order voucher
+ voucher_listing_1 = voucher_1.channel_listings.get(channel=order.channel)
+ voucher_1_discount = Money(voucher_listing_1.discount_value, currency)
+ order.voucher = voucher_1
+ order.voucher_code = voucher_1.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ assert order.subtotal_net_amount == quantize_price(
+ undiscounted_subtotal.amount - voucher_1_discount.amount, currency
+ )
+ assert order.total_net_amount == quantize_price(
+ order.subtotal_net_amount + undiscounted_shipping_price.amount, currency
+ )
+ discount_1 = order.discounts.get()
+ assert discount_1.amount == voucher_1_discount
+
+ # apply specific product voucher for line 1 variant
+ voucher_listing_2 = voucher_2.channel_listings.get(channel=order.channel)
+ voucher_2_unit_discount = voucher_listing_2.discount_value
+ order.voucher = voucher_2
+ order.voucher_code = voucher_2.codes.first().code
+
+ # when
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ line_1, line_2 = lines
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - voucher_2_unit_discount,
+ currency,
+ )
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == voucher_2_unit_discount
+ assert line_1.unit_discount_type == voucher_2.discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == voucher_2_unit_discount
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ with pytest.raises(OrderDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+
+ discount_2 = line_1.discounts.get()
+ discount_amount_2 = voucher_2_unit_discount * line_1.quantity
+ assert discount_2.amount_value == discount_amount_2
+ assert discount_2.value_type == voucher_2.discount_value_type
+ assert discount_2.type == DiscountType.VOUCHER
+ assert discount_2.reason == f"Voucher code: {order.voucher_code}"
+ assert discount_2.value == voucher_2_unit_discount
+
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == undiscounted_shipping_price * tax_rate
+ assert order.subtotal_net_amount == undiscounted_subtotal.amount - discount_amount_2
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - discount_amount_2) * tax_rate
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ )
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
diff --git a/saleor/discount/utils/checkout.py b/saleor/discount/utils/checkout.py
index 91d1223147..29dcfa220d 100644
--- a/saleor/discount/utils/checkout.py
+++ b/saleor/discount/utils/checkout.py
@@ -15,9 +15,14 @@ from ..models import (
CheckoutLineDiscount,
)
from .promotion import (
+ _get_rule_discount_amount,
create_discount_objects_for_order_promotions,
delete_gift_line,
- prepare_line_discount_objects_for_catalogue_promotions,
+ get_discount_name,
+ get_discount_translated_name,
+ is_discounted_line_by_catalogue_promotion,
+ prepare_promotion_discount_reason,
+ update_promotion_discount,
)
from .shared import update_line_info_cached_discounts
@@ -39,7 +44,9 @@ def create_or_update_discount_objects_from_promotion_for_checkout(
def create_checkout_line_discount_objects_for_catalogue_promotions(
lines_info: list["CheckoutLineInfo"],
):
- discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)
+ discount_data = prepare_checkout_line_discount_objects_for_catalogue_promotions(
+ lines_info
+ )
if not discount_data or not lines_info:
return
@@ -86,6 +93,101 @@ def create_checkout_line_discount_objects_for_catalogue_promotions(
)
+def prepare_checkout_line_discount_objects_for_catalogue_promotions(
+ lines_info: list["CheckoutLineInfo"],
+) -> (
+ tuple[list[dict], list[CheckoutLineDiscount], list[CheckoutLineDiscount], list[str]]
+ | None
+):
+ line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_update: list[CheckoutLineDiscount] = []
+ line_discounts_to_remove: list[CheckoutLineDiscount] = []
+ updated_fields: list[str] = []
+
+ if not lines_info:
+ return None
+
+ for line_info in lines_info:
+ line = line_info.line
+
+ # if channel_listing is not present, we can't close the checkout. User needs to
+ # remove the line for the checkout first. Until that moment, we return the same
+ # price as we did when listing was present - including line discount.
+ if not line_info.channel_listing:
+ continue
+
+ # 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 line discounts
+ if [
+ discount
+ for discount in line_info.discounts
+ if discount.type == DiscountType.MANUAL
+ ]:
+ line_discounts_to_remove.extend(discounts_to_update)
+ continue
+
+ # check if the line price is discounted by catalogue promotion
+ discounted_line = is_discounted_line_by_catalogue_promotion(
+ line_info.channel_listing
+ )
+
+ # delete all existing discounts if the line is not discounted or it is a gift
+ if not discounted_line or line.is_gift:
+ line_discounts_to_remove.extend(discounts_to_update)
+ continue
+
+ if line_info.rules_info:
+ rule_info = line_info.rules_info[0]
+ rule = rule_info.rule
+ rule_discount_amount = _get_rule_discount_amount(
+ line, rule_info, line_info.channel
+ )
+ discount_name = get_discount_name(rule, rule_info.promotion)
+ translated_name = get_discount_translated_name(rule_info)
+ reason = prepare_promotion_discount_reason(rule_info.promotion)
+ if not discount_to_update:
+ 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_promotion_discount(
+ rule,
+ rule_info,
+ rule_discount_amount,
+ 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)
+
+ return (
+ line_discounts_to_create_inputs,
+ line_discounts_to_update,
+ line_discounts_to_remove,
+ updated_fields,
+ )
+
+
def create_checkout_discount_objects_for_order_promotions(
checkout_info: "CheckoutInfo",
lines_info: list["CheckoutLineInfo"],
diff --git a/saleor/discount/utils/order.py b/saleor/discount/utils/order.py
index c67df6ff17..01632c268b 100644
--- a/saleor/discount/utils/order.py
+++ b/saleor/discount/utils/order.py
@@ -1,68 +1,42 @@
+from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING
+from uuid import UUID
from django.conf import settings
from django.db import transaction
+from django.db.models import prefetch_related_objects
from prices import TaxedMoney
+from ...channel.models import Channel
from ...core.db.connection import allow_writer
+from ...core.prices import quantize_price
from ...core.taxes import zero_money
from ...order.base_calculations import base_order_subtotal
-from ...order.models import Order
-from ...order.utils import get_order_country
+from ...order.models import Order, OrderLine
from .. import DiscountType
+from ..interface import VariantPromotionRuleInfo
from ..models import (
DiscountValueType,
OrderLineDiscount,
)
from .manual_discount import apply_discount_to_value
from .promotion import (
+ _get_rule_discount_amount,
create_discount_objects_for_order_promotions,
delete_gift_line,
- prepare_line_discount_objects_for_catalogue_promotions,
+ get_discount_name,
+ get_discount_translated_name,
+ is_discounted_line_by_catalogue_promotion,
+ prepare_promotion_discount_reason,
+ update_promotion_discount,
)
from .shared import update_line_info_cached_discounts
-from .voucher import create_or_update_discount_objects_from_voucher
if TYPE_CHECKING:
from ...order.fetch import EditableOrderLineInfo
-def create_or_update_discount_objects_for_order(
- order: "Order",
- lines_info: list["EditableOrderLineInfo"],
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- create_or_update_discount_objects_from_promotion_for_order(
- order, lines_info, database_connection_name
- )
- create_or_update_line_discount_objects_for_manual_discounts(lines_info)
- create_or_update_discount_objects_from_voucher(
- order, lines_info, database_connection_name
- )
- _copy_unit_discount_data_to_order_line(lines_info)
-
-
-def create_or_update_discount_objects_from_promotion_for_order(
- order: "Order",
- lines_info: list["EditableOrderLineInfo"],
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
- create_order_line_discount_objects_for_catalogue_promotions(lines_info)
- # base unit price must reflect all actual catalogue discounts
- _update_base_unit_price_amount_for_catalogue_promotion(lines_info)
- create_order_discount_objects_for_order_promotions(
- order, lines_info, database_connection_name=database_connection_name
- )
-
-
-def create_order_line_discount_objects_for_catalogue_promotions(
- lines_info: list["EditableOrderLineInfo"],
-):
- discount_data = prepare_line_discount_objects_for_catalogue_promotions(lines_info)
- create_order_line_discount_objects(lines_info, discount_data)
-
-
def create_order_line_discount_objects(
lines_info: list["EditableOrderLineInfo"],
discount_data: tuple[
@@ -72,6 +46,8 @@ def create_order_line_discount_objects(
list[str],
],
) -> None | list["EditableOrderLineInfo"]:
+ from ...order.utils import order_qs_select_for_update
+
if not discount_data or not lines_info:
return None
@@ -83,18 +59,22 @@ def create_order_line_discount_objects(
) = discount_data
new_line_discounts: list[OrderLineDiscount] = []
+ affected_line_ids: list[UUID] = []
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
- _order_lock = list(
- Order.objects.filter(id=order_id).select_for_update(of=(["self"]))
- )
+ _order_lock = list(order_qs_select_for_update().filter(id=order_id))
if discount_ids_to_remove := [
discount.id for discount in discount_to_remove
]:
+ affected_line_ids.extend(
+ discount.line_id
+ for discount in discount_to_remove
+ if discount.line_id is not None
+ )
OrderLineDiscount.objects.filter(id__in=discount_ids_to_remove).delete()
if discounts_to_create_inputs:
@@ -113,23 +93,48 @@ def create_order_line_discount_objects(
update_line_info_cached_discounts(
lines_info, new_line_discounts, discounts_to_update, discount_ids_to_remove
)
- affected_line_ids = [
+ affected_line_ids.extend(
discount_line.line_id
for discount_line in (new_line_discounts + discounts_to_update)
- ]
- affected_line_ids.extend(discount_ids_to_remove)
+ if discount_line.line_id is not None
+ )
+
modified_lines_info = [
line_info for line_info in lines_info if line_info.line.id in affected_line_ids
]
return modified_lines_info
-def _copy_unit_discount_data_to_order_line(
+def update_catalogue_promotion_discount_amount_for_order(
+ discount_to_update: "OrderLineDiscount",
+ line: OrderLine,
+ quantity: int,
+ currency: str,
+):
+ """Update catalogue promotion discount amount.
+
+ The discount amount must be updated when:
+ - line quantity has changed
+ - line is updated with custom price
+ """
+ unit_price = apply_discount_to_value(
+ discount_to_update.value,
+ discount_to_update.value_type,
+ currency,
+ line.undiscounted_base_unit_price,
+ )
+ unit_discount = line.undiscounted_base_unit_price_amount - unit_price.amount
+ discount_amount = quantize_price(unit_discount * quantity, currency)
+ discount_to_update.amount_value = discount_amount
+ discount_to_update.save(update_fields=["amount_value"])
+
+
+def update_unit_discount_data_on_order_line(
lines_info: list["EditableOrderLineInfo"],
):
for line_info in lines_info:
+ line = line_info.line
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(
@@ -148,18 +153,26 @@ def _copy_unit_discount_data_to_order_line(
line.unit_discount_reason = discount_reason
line.unit_discount_type = discount_type
line.unit_discount_value = discount_value
+ else:
+ line.unit_discount_amount = Decimal("0.0")
+ line.unit_discount_reason = None
+ line.unit_discount_type = None
+ line.unit_discount_value = Decimal("0.0")
-def _update_base_unit_price_amount_for_catalogue_promotion(
- lines_info: list["EditableOrderLineInfo"],
+def handle_order_promotion(
+ order: "Order",
+ lines_info,
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- for line_info in lines_info:
- line = line_info.line
- base_unit_price = line.undiscounted_base_unit_price_amount
- for discount in line_info.get_catalogue_discounts():
- unit_discount = discount.amount_value / line.quantity
- base_unit_price -= unit_discount
- line.base_unit_price_amount = max(base_unit_price, Decimal(0))
+ create_order_discount_objects_for_order_promotions(
+ order, lines_info, database_connection_name=database_connection_name
+ )
+ # order object
+ _clear_prefetched_order_discounts(order)
+ with allow_writer():
+ # TODO: Load discounts with a dataloader and pass as argument
+ prefetch_related_objects([order], "discounts")
def create_order_discount_objects_for_order_promotions(
@@ -167,6 +180,8 @@ def create_order_discount_objects_for_order_promotions(
lines_info: list["EditableOrderLineInfo"],
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
+ 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)
@@ -196,6 +211,11 @@ def create_order_discount_objects_for_order_promotions(
return
+def _clear_prefetched_order_discounts(order):
+ if hasattr(order, "_prefetched_objects_cache"):
+ order._prefetched_objects_cache.pop("discounts", None)
+
+
def _set_order_base_prices(order: Order, lines_info: list["EditableOrderLineInfo"]):
"""Set base order prices that includes only catalogue discounts."""
lines = [line_info.line for line_info in lines_info]
@@ -226,13 +246,166 @@ def _clear_order_discount(
order_or_checkout.discounts.filter(type=DiscountType.ORDER_PROMOTION).delete()
-def create_or_update_line_discount_objects_for_manual_discounts(lines_info):
+def create_order_line_discount_objects_for_catalogue_promotions(
+ line: "OrderLine",
+ rules_info: Iterable[VariantPromotionRuleInfo],
+ channel: Channel,
+) -> Iterable["OrderLineDiscount"]:
+ from ...order.utils import order_qs_select_for_update
+
+ line_discounts_to_create_inputs: list[dict] = []
+ for rule_info in rules_info:
+ rule = rule_info.rule
+ rule_discount_amount = _get_rule_discount_amount(line, rule_info, channel)
+ discount_name = get_discount_name(rule, rule_info.promotion)
+ translated_name = get_discount_translated_name(rule_info)
+ reason = prepare_promotion_discount_reason(rule_info.promotion)
+
+ 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)
+
+ if line_discounts_to_create_inputs:
+ with allow_writer():
+ with transaction.atomic():
+ order_id = line.order_id
+ _order_lock = list(order_qs_select_for_update().filter(id=order_id))
+ new_line_discounts = [
+ OrderLineDiscount(**input)
+ for input in line_discounts_to_create_inputs
+ ]
+
+ return OrderLineDiscount.objects.bulk_create(
+ new_line_discounts, ignore_conflicts=True
+ )
+ return []
+
+
+def refresh_order_line_discount_objects_for_catalogue_promotions(
+ lines_info: list["EditableOrderLineInfo"],
+):
+ discount_data = prepare_order_line_discount_objects_for_catalogue_promotions(
+ lines_info
+ )
+ create_order_line_discount_objects(lines_info, discount_data)
+ _update_base_unit_price_amount_for_catalogue_promotion(lines_info)
+
+
+def prepare_order_line_discount_objects_for_catalogue_promotions(lines_info):
+ line_discounts_to_create_inputs: list[dict] = []
+ line_discounts_to_update: list[OrderLineDiscount] = []
+ line_discounts_to_remove: list[OrderLineDiscount] = []
+ updated_fields: list[str] = []
+
+ if not lines_info:
+ return None
+
+ 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 line discounts
+ if [
+ discount
+ for discount in line_info.discounts
+ if discount.type == DiscountType.MANUAL
+ ]:
+ line_discounts_to_remove.extend(discounts_to_update)
+ continue
+
+ # check if the line price is discounted by catalogue promotion
+ discounted_line = is_discounted_line_by_catalogue_promotion(
+ line_info.channel_listing
+ )
+
+ # delete all existing discounts if the line is not discounted or it is a gift
+ if not discounted_line or line.is_gift:
+ line_discounts_to_remove.extend(discounts_to_update)
+ continue
+
+ if line_info.rules_info:
+ rule_info = line_info.rules_info[0]
+ rule = rule_info.rule
+ rule_discount_amount = _get_rule_discount_amount(
+ line, rule_info, line_info.channel
+ )
+ discount_name = get_discount_name(rule, rule_info.promotion)
+ translated_name = get_discount_translated_name(rule_info)
+ reason = prepare_promotion_discount_reason(rule_info.promotion)
+ if not discount_to_update:
+ 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_promotion_discount(
+ rule,
+ rule_info,
+ rule_discount_amount,
+ 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)
+
+ return (
+ line_discounts_to_create_inputs,
+ line_discounts_to_update,
+ line_discounts_to_remove,
+ updated_fields,
+ )
+
+
+def _update_base_unit_price_amount_for_catalogue_promotion(
+ lines_info: list["EditableOrderLineInfo"],
+):
+ for line_info in lines_info:
+ line = line_info.line
+ base_unit_price = line.undiscounted_base_unit_price_amount
+ for discount in line_info.get_catalogue_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 refresh_manual_line_discount_object(lines_info):
discount_to_update: list[OrderLineDiscount] = []
for line_info in lines_info:
manual_discount = line_info.get_manual_line_discount()
if not manual_discount:
continue
line = line_info.line
+ # manual line discounts do not combine with other line-level discounts
base_unit_price = line.undiscounted_base_unit_price
reduced_unit_price = apply_discount_to_value(
manual_discount.value,
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index 1dda0c4b2b..e9399c9ae5 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -3,7 +3,7 @@ from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator
from decimal import Decimal
from itertools import chain
-from typing import TYPE_CHECKING, NamedTuple, Union, overload
+from typing import TYPE_CHECKING, NamedTuple, Union
from uuid import UUID
import graphene
@@ -47,6 +47,7 @@ from ..models import (
from .shared import update_discount
if TYPE_CHECKING:
+ from ...checkout.fetch import CheckoutLineInfo
from ...order.fetch import EditableOrderLineInfo
from ...order.models import OrderLine
from ...product.managers import ProductVariantQueryset
@@ -56,8 +57,10 @@ CatalogueInfo = defaultdict[str, set[int | str]]
CATALOGUE_FIELDS = ["categories", "collections", "products", "variants"]
-def prepare_promotion_discount_reason(promotion: "Promotion", sale_id: str):
- return f"{'Sale' if promotion.old_sale_id else 'Promotion'}: {sale_id}"
+def prepare_promotion_discount_reason(promotion: 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_sale_id(promotion: "Promotion"):
@@ -154,113 +157,7 @@ def get_product_discount_on_promotion(
raise NotApplicable("Promotion rule not applicable for this product")
-@overload
-def prepare_line_discount_objects_for_catalogue_promotions(
- lines_info: list["CheckoutLineInfo"],
-) -> tuple[
- list[dict], list["CheckoutLineDiscount"], list["CheckoutLineDiscount"], list[str]
-]: ...
-
-
-@overload
-def prepare_line_discount_objects_for_catalogue_promotions(
- lines_info: list["EditableOrderLineInfo"],
-) -> tuple[
- list[dict], list["OrderLineDiscount"], list["OrderLineDiscount"], list[str]
-]: ...
-
-
-def prepare_line_discount_objects_for_catalogue_promotions(lines_info):
- line_discounts_to_create_inputs: list[dict] = []
- line_discounts_to_update: list[CheckoutLineDiscount | OrderLineDiscount] = []
- line_discounts_to_remove: list[CheckoutLineDiscount | OrderLineDiscount] = []
- updated_fields: list[str] = []
-
- if not lines_info:
- return None
-
- for line_info in lines_info:
- line = line_info.line
-
- # if channel_listing is not present, we can't close the checkout. User needs to
- # remove the line for the checkout first. Until that moment, we return the same
- # price as we did when listing was present - including line discount.
- if isinstance(line_info, CheckoutLineInfo) and not line_info.channel_listing:
- continue
-
- # 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 line discounts
- if [
- discount
- for discount in line_info.discounts
- if discount.type == DiscountType.MANUAL
- ]:
- line_discounts_to_remove.extend(discounts_to_update)
- continue
-
- # check if the line price is discounted by catalogue promotion
- discounted_line = _is_discounted_line_by_catalogue_promotion(
- line_info.channel_listing
- )
-
- # delete all existing discounts if the line is not discounted or it is a gift
- if not discounted_line or line.is_gift:
- line_discounts_to_remove.extend(discounts_to_update)
- continue
-
- if line_info.rules_info:
- rule_info = line_info.rules_info[0]
- rule = rule_info.rule
- rule_discount_amount = _get_rule_discount_amount(
- line, rule_info, line_info.channel
- )
- 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_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_promotion_discount(
- rule,
- rule_info,
- rule_discount_amount,
- 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)
-
- return (
- line_discounts_to_create_inputs,
- line_discounts_to_update,
- line_discounts_to_remove,
- updated_fields,
- )
-
-
-def _is_discounted_line_by_catalogue_promotion(
+def is_discounted_line_by_catalogue_promotion(
variant_channel_listing: "ProductVariantChannelListing",
) -> bool:
"""Return True when the price is discounted by catalogue promotion."""
@@ -318,13 +215,6 @@ 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
@@ -337,7 +227,7 @@ def get_discount_translated_name(rule_info: "VariantPromotionRuleInfo"):
return None
-def _update_promotion_discount(
+def update_promotion_discount(
rule: PromotionRule,
rule_info: VariantPromotionRuleInfo,
rule_discount_amount: Decimal,
@@ -348,9 +238,7 @@ def _update_promotion_discount(
):
discount_name = get_discount_name(rule, rule_info.promotion)
translated_name = get_discount_translated_name(rule_info)
- reason = prepare_promotion_discount_reason(
- rule_info.promotion, get_sale_id(rule_info.promotion)
- )
+ reason = prepare_promotion_discount_reason(rule_info.promotion)
# gift rule has empty reward_value_type
value_type = rule.reward_value_type or RewardValueType.FIXED
# gift rule has empty reward_value
@@ -829,7 +717,7 @@ def create_discount_objects_for_order_promotions(
"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)),
+ "reason": prepare_promotion_discount_reason(rule_info.promotion),
}
if gift_listing:
_handle_gift_reward(
@@ -866,7 +754,7 @@ def _handle_order_promotion(
if not created:
fields_to_update: list[str] = []
- _update_promotion_discount(
+ update_promotion_discount(
discount_object_defaults["promotion_rule"],
rule_info,
discount_amount,
@@ -910,7 +798,7 @@ def _handle_gift_reward(
if line_discount.line_id != line.id:
line_discount.line = line
fields_to_update.append("line_id")
- _update_promotion_discount(
+ update_promotion_discount(
discount_object_defaults["promotion_rule"],
rule_info,
discount_object_defaults["amount_value"],
@@ -928,17 +816,18 @@ def _handle_gift_reward(
"product": variant.product,
"product_type": variant.product.product_type,
"collections": [],
- "channel_listing": gift_listing,
"discounts": [line_discount],
- "rules_info": [rule_info],
"channel": channel,
"voucher": None,
"voucher_code": None,
}
gift_line_info: CheckoutLineInfo | EditableOrderLineInfo
if isinstance(order_or_checkout, Checkout):
+ init_values["channel_listing"] = gift_listing
+ init_values["rules_info"] = [rule_info]
gift_line_info = CheckoutLineInfo(**init_values)
else:
+ init_values["voucher_denormalized_info"] = None
gift_line_info = EditableOrderLineInfo(**init_values)
lines_info.append(gift_line_info) # type: ignore[arg-type]
else:
diff --git a/saleor/discount/utils/voucher.py b/saleor/discount/utils/voucher.py
index 49e457c964..a4056f8ae6 100644
--- a/saleor/discount/utils/voucher.py
+++ b/saleor/discount/utils/voucher.py
@@ -1,11 +1,14 @@
from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
+from uuid import UUID
from django.db.models import Exists, F, OuterRef
from django.utils import timezone
from prices import Money
+from ... import settings
from ...channel.models import Channel
from ...core.db.connection import allow_writer
from ...core.taxes import zero_money
@@ -20,6 +23,7 @@ from ..models import (
VoucherCode,
VoucherCustomer,
)
+from .manual_discount import apply_discount_to_value
from .shared import update_discount
if TYPE_CHECKING:
@@ -33,6 +37,17 @@ if TYPE_CHECKING:
from ..models import Voucher
+@dataclass
+class VoucherDenormalizedInfo:
+ discount_value: Decimal
+ discount_value_type: str
+ voucher_type: str
+ reason: str | None
+ name: str | None
+ apply_once_per_order: bool
+ origin_line_ids: list[UUID]
+
+
def is_order_level_voucher(voucher: Voucher | None):
return bool(
voucher
@@ -45,6 +60,12 @@ def is_shipping_voucher(voucher: Voucher | None):
return bool(voucher and voucher.type == VoucherType.SHIPPING)
+def is_line_level_voucher(voucher: Voucher | None):
+ return voucher and (
+ voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order
+ )
+
+
def increase_voucher_usage(
voucher: "Voucher",
code: "VoucherCode",
@@ -160,7 +181,7 @@ def get_active_voucher_code(voucher, channel_slug):
return voucher_code
-def apply_voucher_to_line(
+def attach_voucher_to_line_info(
voucher_info: "VoucherInfo",
lines_info: Sequence["LineInfo"],
):
@@ -178,7 +199,7 @@ def apply_voucher_to_line(
)
lines_included_in_discount = discounted_lines_by_voucher
if voucher.apply_once_per_order:
- if cheapest_line := _get_the_cheapest_line(lines_included_in_discount):
+ if cheapest_line := get_the_cheapest_line(lines_included_in_discount):
discounted_lines_by_voucher = [cheapest_line]
for line_info in lines_info:
if line_info in discounted_lines_by_voucher:
@@ -222,7 +243,7 @@ def get_discounted_lines(
return discounted_lines
-def _get_the_cheapest_line(
+def get_the_cheapest_line(
lines_info: Iterable["LineInfo"] | None,
) -> Optional["LineInfo"]:
if not lines_info:
@@ -304,31 +325,57 @@ def get_products_voucher_discount(
return total_amount
-def create_or_update_discount_objects_from_voucher(
- order, lines_info, database_connection_name
+def create_or_update_voucher_discount_objects_for_order(
+ order: "Order", use_denormalized_data=False
):
- create_or_update_discount_object_from_order_level_voucher(
- order, database_connection_name
+ """Handle voucher discount objects for order.
+
+ Take into account all the mutual dependence and exclusivity between various types of
+ discounts.
+
+ `use_denormalized_data=True` indicates, that the discount should be calculated based on the
+ conditions from the moment of the voucher application. Otherwise, the latest
+ voucher values will be retrieved from the database.
+ """
+ from ...order.fetch import fetch_draft_order_lines_info
+ from ...order.models import OrderLine
+
+ create_or_update_discount_object_from_order_level_voucher(order)
+ lines_info = fetch_draft_order_lines_info(order)
+ create_or_update_line_discount_objects_from_voucher(
+ lines_info, use_denormalized_data
)
- create_or_update_line_discount_objects_from_voucher(lines_info)
+ lines = [line_info.line for line_info in lines_info]
+ OrderLine.objects.bulk_update(lines, ["base_unit_price_amount"])
def create_or_update_discount_object_from_order_level_voucher(
- order, database_connection_name
+ order,
+ database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
"""Create or update discount object for ENTIRE_ORDER and SHIPPING voucher."""
voucher = order.voucher
- if not order.voucher_id or (
- is_order_level_voucher(voucher)
- and order.discounts.filter(type=DiscountType.MANUAL)
- ):
+
+ # The order-level voucher discount should be deleted when:
+ # - order.voucher_id is None
+ # - manual order-level discount exists together with order-level voucher
+ # - the order has line-level voucher attached
+ is_manual_discount = order.discounts.filter(type=DiscountType.MANUAL).exists()
+ is_order_voucher = is_order_level_voucher(voucher)
+ is_line_level_voucher = not is_order_voucher and not is_shipping_voucher(voucher)
+ should_delete_order_level_voucher_discount = (
+ not order.voucher_id
+ or (is_order_voucher and is_manual_discount)
+ or is_line_level_voucher
+ )
+
+ if should_delete_order_level_voucher_discount:
with allow_writer():
order.discounts.filter(type=DiscountType.VOUCHER).delete()
+ if not is_shipping_voucher(voucher):
+ order.base_shipping_price = order.undiscounted_base_shipping_price
return
- if not is_order_level_voucher(voucher) and not is_shipping_voucher(voucher):
- return
-
voucher_channel_listing = (
voucher.channel_listings.using(database_connection_name)
.filter(channel=order.channel)
@@ -342,6 +389,7 @@ def create_or_update_discount_object_from_order_level_voucher(
discount_amount = voucher.get_discount_amount_for(
order.subtotal.net, order.channel
)
+
if is_shipping_voucher(voucher):
discount_amount = voucher.get_discount_amount_for(
order.undiscounted_base_shipping_price, order.channel
@@ -352,6 +400,8 @@ def create_or_update_discount_object_from_order_level_voucher(
order.undiscounted_base_shipping_price - discount_amount,
zero_money(order.currency),
)
+ else:
+ order.base_shipping_price = order.undiscounted_base_shipping_price
discount_reason = f"Voucher code: {order.voucher_code}"
discount_name = voucher.name or ""
@@ -396,27 +446,44 @@ def create_or_update_discount_object_from_order_level_voucher(
discount_object.save(update_fields=updated_fields)
-def create_or_update_line_discount_objects_from_voucher(lines_info):
+def create_or_update_line_discount_objects_from_voucher(
+ lines_info, use_denormalized_data=False
+):
"""Create or update line discount object for voucher applied on lines.
The LineDiscount object is created for each line with voucher applied.
Only `SPECIFIC_PRODUCT` and `apply_once_per_order` voucher types are applied.
+ `use_denormalized_data=True` indicates, that the discount should be calculated based
+ on the conditions from the moment of the voucher application. Otherwise, the latest
+ voucher values will be retrieved from the database.
"""
# FIXME: temporary - create_order_line_discount_objects should be moved to shared
- from .order import create_order_line_discount_objects
+ from .order import (
+ create_order_line_discount_objects,
+ update_unit_discount_data_on_order_line,
+ )
- discount_data = prepare_line_discount_objects_for_voucher(lines_info)
+ discount_data = prepare_line_discount_objects_for_voucher(
+ lines_info, use_denormalized_data
+ )
modified_lines_info = create_order_line_discount_objects(lines_info, discount_data)
- # base unit price must reflect all actual line voucher discounts
if modified_lines_info:
_reduce_base_unit_price_for_voucher_discount(modified_lines_info)
+ update_unit_discount_data_on_order_line(modified_lines_info)
# TODO (SHOPX-912): share the method with checkout
def prepare_line_discount_objects_for_voucher(
lines_info: list["EditableOrderLineInfo"],
+ use_denormalized_data=False,
):
+ """Prepare line-level voucher discount objects to be created, updated and deleted.
+
+ `use_denormalized_data=True` indicates, that the discount should be calculated based on the
+ conditions from the moment of the voucher application. Otherwise, the latest
+ voucher values will be retrieved from the database.
+ """
line_discounts_to_create_inputs: list[dict] = []
line_discounts_to_update: list[OrderLineDiscount] = []
line_discounts_to_remove: list[OrderLineDiscount] = []
@@ -427,10 +494,9 @@ def prepare_line_discount_objects_for_voucher(
for line_info in lines_info:
line = line_info.line
- total_price = line.base_unit_price * line.quantity
- discount_amount = calculate_line_discount_amount_from_voucher(
- line_info, total_price
- )
+ voucher = cast(Voucher, line_info.voucher)
+ total_price = line_info.variant_discounted_price * line.quantity
+
# only one voucher can be applied
discount_to_update = None
if discounts_to_update := line_info.get_voucher_discounts():
@@ -439,16 +505,43 @@ def prepare_line_discount_objects_for_voucher(
# manual line discount do not stack with other line discounts
manual_line_discount = line_info.get_manual_line_discount()
- if not discount_amount or line.is_gift or manual_line_discount:
+ if (
+ (not voucher and use_denormalized_data is False)
+ or line.is_gift
+ or manual_line_discount
+ ):
if discount_to_update:
line_discounts_to_remove.append(discount_to_update)
continue
+ if use_denormalized_data:
+ if not line_info.voucher_denormalized_info:
+ if discount_to_update:
+ line_discounts_to_remove.append(discount_to_update)
+ continue
+
+ discount_amount = (
+ calculate_order_line_discount_amount_from_denormalized_voucher(
+ line_info, total_price
+ )
+ )
+ voucher_denormalized_info = line_info.voucher_denormalized_info
+ discount_name = f"{voucher_denormalized_info.name}"
+ discount_value = voucher_denormalized_info.discount_value
+ discount_value_type = voucher_denormalized_info.discount_value_type
+ else:
+ discount_amount = calculate_line_discount_amount_from_voucher(
+ line_info, total_price
+ )
+ voucher_listing = voucher.channel_listings.get(channel=line_info.channel)
+ discount_name = f"{voucher.name}"
+ discount_value = voucher_listing.discount_value
+ discount_value_type = voucher.discount_value_type
+
discount_amount = discount_amount.amount
code = line_info.voucher_code
discount_reason = f"Voucher code: {code}"
- voucher = cast(Voucher, line_info.voucher)
- discount_name = f"{voucher.name}"
+
if discount_to_update:
update_discount(
rule=None,
@@ -457,10 +550,9 @@ def prepare_line_discount_objects_for_voucher(
# TODO (SHOPX-914): set translated voucher name
translated_name="",
discount_reason=discount_reason,
- # TODO (SHOPX-914): should be taken from voucher value_type and value
discount_amount=discount_amount,
- value=discount_amount,
- value_type=voucher.discount_value_type,
+ value=discount_value,
+ value_type=discount_value_type,
unique_type=DiscountType.VOUCHER,
discount_to_update=discount_to_update,
updated_fields=updated_fields,
@@ -471,15 +563,14 @@ def prepare_line_discount_objects_for_voucher(
line_discount_input = {
"line": line,
"type": DiscountType.VOUCHER,
- # TODO (SHOPX-914): should be taken from voucher value_type and value
- "value_type": DiscountValueType.FIXED,
- "value": discount_amount,
+ "value_type": discount_value_type,
+ "value": discount_value,
"amount_value": discount_amount,
"currency": line.currency,
"name": discount_name,
"translated_name": None,
"reason": discount_reason,
- "voucher": line_info.voucher,
+ "voucher": voucher,
"unique_type": DiscountType.VOUCHER,
"voucher_code": code,
}
@@ -535,12 +626,59 @@ def calculate_line_discount_amount_from_voucher(
return discount_amount
+def calculate_order_line_discount_amount_from_denormalized_voucher(
+ line_info: "EditableOrderLineInfo", total_price: Money
+) -> Money:
+ """Calculate discount amount for line-level vouchers with denormalized values."""
+ voucher_info = line_info.voucher_denormalized_info
+ if not voucher_info:
+ return zero_money(total_price.currency)
+
+ quantity = line_info.line.quantity
+ currency = total_price.currency
+ if not voucher_info.apply_once_per_order:
+ if voucher_info.discount_value_type == DiscountValueType.PERCENTAGE:
+ discounted_total_price = apply_discount_to_value(
+ value=voucher_info.discount_value,
+ value_type=voucher_info.discount_value_type,
+ currency=currency,
+ price_to_discount=total_price,
+ )
+ discount_amount = min(total_price - discounted_total_price, total_price)
+ else:
+ unit_price = Money(total_price.amount / quantity, currency)
+ discounted_unit_price = apply_discount_to_value(
+ value=voucher_info.discount_value,
+ value_type=voucher_info.discount_value_type,
+ currency=currency,
+ price_to_discount=unit_price,
+ )
+ voucher_unit_discount_amount = max(
+ unit_price - discounted_unit_price, zero_money(unit_price.currency)
+ )
+ discount_amount = min(voucher_unit_discount_amount * quantity, total_price)
+ else:
+ unit_price = Money(total_price.amount / quantity, currency)
+ discounted_unit_price = apply_discount_to_value(
+ value=voucher_info.discount_value,
+ value_type=voucher_info.discount_value_type,
+ currency=currency,
+ price_to_discount=unit_price,
+ )
+ voucher_unit_discount_amount = max(
+ unit_price - discounted_unit_price, zero_money(unit_price.currency)
+ )
+ # vouchers applicable once per order discounts only a single unit of the line
+ discount_amount = min(voucher_unit_discount_amount, unit_price)
+ return discount_amount
+
+
def _reduce_base_unit_price_for_voucher_discount(
lines_info: list["EditableOrderLineInfo"],
):
for line_info in lines_info:
line = line_info.line
- base_unit_price = line.base_unit_price_amount
+ base_unit_price = line_info.variant_discounted_price.amount
for discount in line_info.get_voucher_discounts():
base_unit_price -= discount.amount_value / line.quantity
line.base_unit_price_amount = max(base_unit_price, Decimal(0))
diff --git a/saleor/graphql/account/tests/queries/test_me.py b/saleor/graphql/account/tests/queries/test_me.py
index 9e6e3e8eee..05c6e5a872 100644
--- a/saleor/graphql/account/tests/queries/test_me.py
+++ b/saleor/graphql/account/tests/queries/test_me.py
@@ -311,11 +311,11 @@ ME_WITH_ORDERS_WITH_LINES_TOTAL_PRICE_QUERY = """
@pytest.mark.parametrize(
"query", [ME_WITH_ORDERS_QUERY, ME_WITH_ORDERS_WITH_LINES_TOTAL_PRICE_QUERY]
)
[email protected]("saleor.order.calculations._recalculate_prices")
[email protected]("saleor.order.calculations.calculate_prices")
@mock.patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_me_query_orders_do_not_trigger_sync_tax_webhooks(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
query,
user_api_client,
order_with_lines,
@@ -345,7 +345,7 @@ def test_me_query_orders_do_not_trigger_sync_tax_webhooks(
assert order_with_lines.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
@pytest.mark.parametrize(
diff --git a/saleor/graphql/channel/mutations/channel_create.py b/saleor/graphql/channel/mutations/channel_create.py
index bb410e6187..74786da5b3 100644
--- a/saleor/graphql/channel/mutations/channel_create.py
+++ b/saleor/graphql/channel/mutations/channel_create.py
@@ -11,6 +11,7 @@ from ...core import ResolveInfo
from ...core.descriptions import (
ADDED_IN_318,
ADDED_IN_320,
+ ADDED_IN_321,
DEPRECATED_IN_3X_INPUT,
PREVIEW_FEATURE,
)
@@ -22,7 +23,7 @@ from ...core.doc_category import (
DOC_CATEGORY_PRODUCTS,
)
from ...core.mutations import ModelMutation
-from ...core.scalars import Day, Minute
+from ...core.scalars import Day, Hour, Minute
from ...core.types import BaseInputObjectType, ChannelError, NonNullList
from ...core.types import common as common_types
from ...core.utils import WebhookEventInfo
@@ -140,6 +141,14 @@ class OrderSettingsInput(BaseInputObjectType):
+ PREVIEW_FEATURE
),
)
+ draft_order_line_price_freeze_period = Hour(
+ required=False,
+ description=(
+ "Time in hours after which the draft order line price will be refreshed. "
+ "Default value is 24 hours. "
+ "Enter 0 or null to disable." + ADDED_IN_321 + PREVIEW_FEATURE
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_ORDERS
diff --git a/saleor/graphql/channel/mutations/utils.py b/saleor/graphql/channel/mutations/utils.py
index 684e796641..cb4179395c 100644
--- a/saleor/graphql/channel/mutations/utils.py
+++ b/saleor/graphql/channel/mutations/utils.py
@@ -77,6 +77,11 @@ def clean_input_order_settings(
instance.include_draft_order_in_voucher_usage
)
+ if "draft_order_line_price_freeze_period" in order_settings:
+ cleaned_input["draft_order_line_price_freeze_period"] = order_settings[
+ "draft_order_line_price_freeze_period"
+ ]
+
def clean_input_checkout_settings(checkout_settings: dict, cleaned_input: dict):
input_to_model_fields = {
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_create.py b/saleor/graphql/channel/tests/mutations/test_channel_create.py
index 6e70e942d1..e5b1a2392a 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_create.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_create.py
@@ -47,6 +47,7 @@ CHANNEL_CREATE_MUTATION = """
deleteExpiredOrdersAfter
allowUnpaidOrders
includeDraftOrderInVoucherUsage
+ draftOrderLinePriceFreezePeriod
}
checkoutSettings {
useLegacyErrorFlow
@@ -88,6 +89,7 @@ def test_channel_create_mutation_as_staff_user(
"automaticallyFulfillNonShippableGiftCard": False,
"expireOrdersAfter": 10,
"includeDraftOrderInVoucherUsage": True,
+ "draftOrderLinePriceFreezePeriod": 10,
},
"checkoutSettings": {"useLegacyErrorFlow": False},
}
@@ -122,6 +124,7 @@ def test_channel_create_mutation_as_staff_user(
)
assert channel_data["orderSettings"]["expireOrdersAfter"] == 10
assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is True
+ assert channel_data["orderSettings"]["draftOrderLinePriceFreezePeriod"] == 10
assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False
assert (
channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
@@ -183,6 +186,7 @@ def test_channel_create_mutation_as_app(
)
assert channel_data["orderSettings"]["expireOrdersAfter"] is None
assert channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"] is False
+ assert channel_data["orderSettings"]["draftOrderLinePriceFreezePeriod"] == 24
assert channel_data["checkoutSettings"]["useLegacyErrorFlow"] is False
assert (
channel_data["checkoutSettings"]["automaticallyCompleteFullyPaidCheckouts"]
@@ -259,6 +263,43 @@ def test_channel_create_mutation_negative_expire_orders(
assert error["code"] == ChannelErrorCode.INVALID.name
+def test_channel_create_draft_order_line_price_freeze_period_negative_value(
+ permission_manage_channels,
+ app_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ default_country = "US"
+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.name
+ variables = {
+ "input": {
+ "name": name,
+ "slug": slug,
+ "currencyCode": currency_code,
+ "defaultCountry": default_country,
+ "stockSettings": {"allocationStrategy": allocation_strategy},
+ "orderSettings": {
+ "draftOrderLinePriceFreezePeriod": -1,
+ },
+ }
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ # then
+ content = get_graphql_content(response)
+ error = content["data"]["channelCreate"]["errors"][0]
+ assert error["field"] == "draftOrderLinePriceFreezePeriod"
+ assert error["code"] == ChannelErrorCode.INVALID.name
+
+
@pytest.mark.parametrize("expire_input", [0, None])
def test_channel_create_mutation_disabled_expire_orders(
expire_input,
diff --git a/saleor/graphql/channel/tests/mutations/test_channel_update.py b/saleor/graphql/channel/tests/mutations/test_channel_update.py
index 08ab4f990e..cb30cede3a 100644
--- a/saleor/graphql/channel/tests/mutations/test_channel_update.py
+++ b/saleor/graphql/channel/tests/mutations/test_channel_update.py
@@ -47,6 +47,7 @@ CHANNEL_UPDATE_MUTATION = """
deleteExpiredOrdersAfter
allowUnpaidOrders
includeDraftOrderInVoucherUsage
+ draftOrderLinePriceFreezePeriod
}
}
errors{
@@ -1207,6 +1208,77 @@ def test_channel_update_order_settings_voucher_usage_enable(
disconnect_voucher_codes_from_draft_orders_task_mock.assert_called_once()
[email protected]("new_freeze_period", [10, None, 0])
+def test_channel_update_draft_order_line_price_freeze_period(
+ new_freeze_period,
+ permission_manage_orders,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ assert channel_USD.draft_order_line_price_freeze_period == 24
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {
+ "draftOrderLinePriceFreezePeriod": new_freeze_period,
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert (
+ channel_data["orderSettings"]["draftOrderLinePriceFreezePeriod"]
+ == new_freeze_period
+ )
+ assert channel_USD.draft_order_line_price_freeze_period == new_freeze_period
+
+
+def test_channel_update_draft_order_line_price_freeze_period_negative_value(
+ permission_manage_orders,
+ staff_api_client,
+ channel_USD,
+):
+ # given
+ assert channel_USD.draft_order_line_price_freeze_period == 24
+ new_freeze_period = -5
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "orderSettings": {
+ "draftOrderLinePriceFreezePeriod": new_freeze_period,
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_orders,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ error = content["data"]["channelUpdate"]["errors"][0]
+ assert error["field"] == "draftOrderLinePriceFreezePeriod"
+ assert error["code"] == ChannelErrorCode.INVALID.name
+
+
CHANNEL_UPDATE_MUTATION_WITH_CHECKOUT_SETTINGS = """
mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){
channelUpdate(id: $id, input: $input){
diff --git a/saleor/graphql/channel/tests/queries/test_channel.py b/saleor/graphql/channel/tests/queries/test_channel.py
index ec2564505d..fe9d2802b8 100644
--- a/saleor/graphql/channel/tests/queries/test_channel.py
+++ b/saleor/graphql/channel/tests/queries/test_channel.py
@@ -311,6 +311,7 @@ QUERY_CHANNEL_ORDER_SETTINGS = """
deleteExpiredOrdersAfter
allowUnpaidOrders
includeDraftOrderInVoucherUsage
+ draftOrderLinePriceFreezePeriod
}
}
}
@@ -367,6 +368,10 @@ def test_query_channel_order_settings_as_staff_user(
channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"]
== channel_USD.include_draft_order_in_voucher_usage
)
+ assert (
+ channel_data["orderSettings"]["draftOrderLinePriceFreezePeriod"]
+ == channel_USD.draft_order_line_price_freeze_period
+ )
def test_query_channel_order_settings_as_app(
@@ -413,6 +418,10 @@ def test_query_channel_order_settings_as_app(
channel_data["orderSettings"]["includeDraftOrderInVoucherUsage"]
== channel_USD.include_draft_order_in_voucher_usage
)
+ assert (
+ channel_data["orderSettings"]["draftOrderLinePriceFreezePeriod"]
+ == channel_USD.draft_order_line_price_freeze_period
+ )
def test_query_channel_order_settings_as_staff_user_no_permission(
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 8d7344c7ca..6e240a9455 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -22,6 +22,7 @@ from ..core import ResolveInfo
from ..core.descriptions import (
ADDED_IN_318,
ADDED_IN_320,
+ ADDED_IN_321,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -33,7 +34,7 @@ from ..core.doc_category import (
DOC_CATEGORY_TAXES,
)
from ..core.fields import PermissionsField
-from ..core.scalars import Day, Minute
+from ..core.scalars import Day, Hour, Minute
from ..core.types import BaseObjectType, CountryDisplay, ModelObjectType, NonNullList
from ..meta.types import ObjectWithMetadata
from ..tax.dataloaders import TaxConfigurationByChannelId
@@ -201,6 +202,14 @@ class OrderSettings(ObjectType):
"voucher usage." + ADDED_IN_318 + PREVIEW_FEATURE
),
)
+ draft_order_line_price_freeze_period = Hour(
+ required=False,
+ description=(
+ "Time in hours after which the draft order line price will be refreshed."
+ + ADDED_IN_321
+ + PREVIEW_FEATURE
+ ),
+ )
class Meta:
description = "Represents the channel-specific order settings."
@@ -497,7 +506,10 @@ class Channel(ModelObjectType):
include_draft_order_in_voucher_usage=(
root.include_draft_order_in_voucher_usage
),
- allow_unpaid_orders=(root.allow_unpaid_orders),
+ allow_unpaid_orders=root.allow_unpaid_orders,
+ draft_order_line_price_freeze_period=(
+ root.draft_order_line_price_freeze_period
+ ),
)
@staticmethod
diff --git a/saleor/graphql/checkout/dataloaders/checkout_infos.py b/saleor/graphql/checkout/dataloaders/checkout_infos.py
index 1cd03b8d3b..51fc6376b3 100644
--- a/saleor/graphql/checkout/dataloaders/checkout_infos.py
+++ b/saleor/graphql/checkout/dataloaders/checkout_infos.py
@@ -6,7 +6,7 @@ from promise import Promise
from ....checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ....core.db.connection import allow_writer_in_context
from ....discount import VoucherType
-from ....discount.utils.voucher import apply_voucher_to_line
+from ....discount.utils.voucher import attach_voucher_to_line_info
from ...account.dataloaders import AddressByIdLoader, UserByUserIdLoader
from ...channel.dataloaders import ChannelByIdLoader
from ...core.dataloaders import DataLoader
@@ -322,7 +322,7 @@ class CheckoutLinesInfoByCheckoutTokenLoader(
voucher.type == VoucherType.SPECIFIC_PRODUCT
or voucher.apply_once_per_order
):
- apply_voucher_to_line(
+ attach_voucher_to_line_info(
voucher_info=voucher_info,
lines_info=lines_info_map[checkout.pk],
)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 8d4accd9b8..2fb07784c4 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -1167,7 +1167,7 @@ def test_add_checkout_lines_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(94):
+ with django_assert_num_queries(93):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1253,7 +1253,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(
# when
user_api_client.ensure_access_token()
- with django_assert_num_queries(94):
+ with django_assert_num_queries(93):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/core/scalars.py b/saleor/graphql/core/scalars.py
index b74383fc3f..414b799e83 100644
--- a/saleor/graphql/core/scalars.py
+++ b/saleor/graphql/core/scalars.py
@@ -194,3 +194,7 @@ class Minute(graphene.Int):
class Day(graphene.Int):
"""The `Day` scalar type represents number of days by integer value."""
+
+
+class Hour(graphene.Int):
+ """The `Hour` scalar type represents number of hours by integer value."""
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 231985678c..6928f1b267 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -16,6 +16,7 @@ from ....order.actions import order_created
from ....order.calculations import fetch_order_prices_if_expired
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderInfo, OrderLineInfo
+from ....order.models import OrderLine
from ....order.search import prepare_order_search_vector_value
from ....order.utils import (
get_order_country,
@@ -141,7 +142,8 @@ class DraftOrderComplete(BaseMutation):
cls.setup_voucher_customer(order, channel)
order_lines_info = []
- for line in order.lines.all():
+ lines = order.lines.all()
+ for line in lines:
if not line.variant:
# we only care about stock for variants that still exist
continue
@@ -173,6 +175,10 @@ class DraftOrderComplete(BaseMutation):
errors = prepare_insufficient_stock_order_validation_errors(e)
raise ValidationError({"lines": errors}) from e
+ # clear draft base price expiration time
+ line.draft_base_price_expire_at = None
+ OrderLine.objects.bulk_update(lines, ["draft_base_price_expire_at"])
+
order_info = OrderInfo(
order=order,
customer_email=order.get_customer_email(),
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index b092094b68..f7c56332c8 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -10,6 +10,7 @@ from ....core.tracing import traced_atomic_transaction
from ....core.utils.url import validate_storefront_url
from ....discount.models import Voucher, VoucherCode
from ....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
get_active_voucher_code,
get_voucher_code_instance,
increase_voucher_usage,
@@ -26,7 +27,6 @@ from ....order.utils import (
update_order_display_gross_prices,
)
from ....permission.enums import OrderPermissions
-from ....shipping.utils import convert_to_shipping_method_data
from ....webhook.event_types import WebhookEventAsyncType
from ...account.i18n import I18nMixin
from ...account.mixins import AddressMetadataMixin
@@ -613,12 +613,12 @@ class DraftOrderCreate(
shipping_channel_listing = cls.validate_shipping_channel_listing(
method, instance
)
- shipping_method_data = convert_to_shipping_method_data(
- method,
- shipping_channel_listing,
- )
- cls.update_shipping_method(instance, method, shipping_method_data)
- cls._update_shipping_price(instance, shipping_channel_listing)
+ cls.update_shipping_method(instance, method)
+ cls.assign_shipping_price(instance, shipping_channel_listing)
+ # for new instance the shipping discount is created later
+ if not is_new_instance:
+ cls.update_shipping_discount(instance)
+
updated_fields.extend(SHIPPING_METHOD_UPDATE_FIELDS)
if instance.undiscounted_base_shipping_price_amount is None:
@@ -672,14 +672,30 @@ class DraftOrderCreate(
@classmethod
def handle_order_voucher(
- cls, cleaned_input, instance, is_new_instance, old_voucher, old_voucher_code
+ cls,
+ cleaned_input,
+ instance: models.Order,
+ is_new_instance: bool,
+ old_voucher: Voucher | None,
+ old_voucher_code: str | None,
):
- user_email = instance.user_email or instance.user and instance.user.email
+ voucher = cleaned_input["voucher"]
+ if voucher is None and old_voucher is None:
+ return
+
+ # create or update voucher discount object
+ create_or_update_voucher_discount_objects_for_order(instance)
+
+ # handle voucher usage
+ user_email = instance.user_email
+ if not user_email and instance.user:
+ user_email = instance.user.email
+
channel = instance.channel
if not channel.include_draft_order_in_voucher_usage:
return
- if voucher := cleaned_input["voucher"]:
+ if voucher:
code_instance = cleaned_input.pop("voucher_code_instance", None)
increase_voucher_usage(
voucher,
diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.py
index 879057e0ca..635ae25b7e 100644
--- a/saleor/graphql/order/mutations/order_line_update.py
+++ b/saleor/graphql/order/mutations/order_line_update.py
@@ -88,6 +88,7 @@ class OrderLineUpdate(
variant=instance.variant,
warehouse_pk=warehouse_pk,
)
+ order = instance.order
try:
change_order_line_quantity(
info.context.user,
@@ -95,7 +96,7 @@ class OrderLineUpdate(
line_info,
instance.old_quantity,
instance.quantity,
- instance.order.channel,
+ order,
manager,
)
except InsufficientStock as e:
@@ -103,11 +104,11 @@ class OrderLineUpdate(
"Cannot set new quantity because of insufficient stock.",
code=OrderErrorCode.INSUFFICIENT_STOCK.value,
) from e
- invalidate_order_prices(instance.order)
- recalculate_order_weight(instance.order)
- instance.order.save(update_fields=["should_refresh_prices", "weight"])
+ invalidate_order_prices(order)
+ recalculate_order_weight(order)
+ order.save(update_fields=["should_refresh_prices", "weight"])
- call_event_by_order_status(instance.order, manager)
+ call_event_by_order_status(order, manager)
@classmethod
def success_response(cls, instance):
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 4144ff74a0..c2a3d1e59f 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -3,11 +3,14 @@ from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
+from ....account.models import User
+from ....app.models import App
from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
-from ....order import events, models
+from ....order import events
+from ....order import models as order_models
from ....order.error_codes import OrderErrorCode
-from ....order.fetch import fetch_order_lines
+from ....order.fetch import OrderLineInfo, fetch_order_lines
from ....order.search import update_order_search_vector
from ....order.utils import (
add_variant_to_order,
@@ -15,6 +18,8 @@ from ....order.utils import (
recalculate_order_weight,
)
from ....permission.enums import OrderPermissions
+from ....plugins.manager import PluginsManager
+from ....product import models as product_models
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
@@ -32,6 +37,7 @@ from ..utils import (
from .draft_order_create import OrderLineCreateInput
from .utils import (
EditableOrderValidationMixin,
+ VariantData,
call_event_by_order_status,
get_variant_rule_info_map,
)
@@ -61,7 +67,11 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
@classmethod
def validate_lines(
- cls, info: ResolveInfo, data, existing_lines_info, variants_data
+ cls,
+ info: ResolveInfo,
+ data: list,
+ existing_lines_info: list[OrderLineInfo],
+ variant_rule_map: dict[str, VariantData],
):
grouped_lines_data: list[OrderLineData] = []
lines_data_map: dict[str, OrderLineData] = defaultdict(OrderLineData)
@@ -74,8 +84,8 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
for input_line in data:
variant_id: str = input_line["variant_id"]
force_new_line = input_line["force_new_line"]
- variant_data = variants_data.get(variant_id)
- variant = variant_data.variant
+ variant_rule_data = variant_rule_map[variant_id]
+ variant = variant_rule_data.variant
quantity = input_line["quantity"]
custom_price = input_line.get("price")
@@ -87,7 +97,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
variant=variant,
quantity=quantity,
price_override=custom_price,
- rules_info=variant_data.rules_info,
+ rules_info=variant_rule_data.rules_info,
)
)
else:
@@ -105,7 +115,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
line_data.variant = variant
line_data.quantity += quantity
line_data.price_override = custom_price
- line_data.rules_info = variant_data.rules_info
+ line_data.rules_info = variant_rule_data.rules_info
else:
invalid_ids.append(variant_id)
if invalid_ids:
@@ -123,7 +133,9 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
return grouped_lines_data
@classmethod
- def validate_variants(cls, order, variants):
+ def validate_variants(
+ cls, order: order_models.Order, variants: list[product_models.ProductVariant]
+ ):
try:
channel = order.channel
validate_product_is_published_in_channel(variants, channel)
@@ -133,8 +145,14 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
raise ValidationError(e) from e
@staticmethod
- def add_lines_to_order(order, lines_data, user, app, manager):
- added_lines: list[models.OrderLine] = []
+ def add_lines_to_order(
+ order: order_models.Order,
+ lines_data: list[OrderLineData],
+ user: User | None,
+ app: App | None,
+ manager: PluginsManager,
+ ):
+ added_lines: list[order_models.OrderLine] = []
try:
for line_data in lines_data:
line = add_variant_to_order(
@@ -164,12 +182,12 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
variant_pks = cls.get_global_ids_or_error(
[line["variant_id"] for line in input], ProductVariant, "variant_id"
)
- variants_data = get_variant_rule_info_map(
+ variants_rule_map = get_variant_rule_info_map(
variant_pks, order.channel_id, order.language_code
)
lines_to_add = cls.validate_lines(
- info, input, existing_lines_info, variants_data
+ info, input, existing_lines_info, variants_rule_map
)
variants = [line.variant for line in lines_to_add]
cls.validate_variants(order, variants)
@@ -211,7 +229,9 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
)
@classmethod
- def _find_line_id_for_variant_if_exist(cls, variant_id, lines_info) -> None | str:
+ def _find_line_id_for_variant_if_exist(
+ cls, variant_id: int, lines_info: list[OrderLineInfo]
+ ) -> None | str:
"""Return line id by using provided variantId parameter."""
if not lines_info:
return None
diff --git a/saleor/graphql/order/mutations/order_update_shipping.py b/saleor/graphql/order/mutations/order_update_shipping.py
index 6378553f9d..f0159f308e 100644
--- a/saleor/graphql/order/mutations/order_update_shipping.py
+++ b/saleor/graphql/order/mutations/order_update_shipping.py
@@ -132,8 +132,8 @@ class OrderUpdateShipping(
manager = get_plugin_manager_promise(info.context).get()
if order.status != OrderStatus.DRAFT:
clean_order_update_shipping(order, shipping_method_data, manager)
- cls.update_shipping_method(order, method, shipping_channel_listing)
- cls._update_shipping_price(order, shipping_channel_listing)
+ cls.update_shipping_method(order, method)
+ cls.update_shipping_price(order, shipping_channel_listing)
order.save(update_fields=SHIPPING_METHOD_UPDATE_FIELDS)
# Post-process the results
diff --git a/saleor/graphql/order/mutations/utils.py b/saleor/graphql/order/mutations/utils.py
index 4c7d8da180..1c6e3af8ec 100644
--- a/saleor/graphql/order/mutations/utils.py
+++ b/saleor/graphql/order/mutations/utils.py
@@ -6,7 +6,9 @@ from django.core.exceptions import ValidationError
from ....checkout.fetch import get_variant_channel_listing
from ....core.taxes import zero_money, zero_taxed_money
+from ....discount import VoucherType
from ....discount.interface import VariantPromotionRuleInfo, fetch_variant_rules_info
+from ....discount.utils.manual_discount import apply_discount_to_value
from ....order import ORDER_EDITABLE_STATUS, OrderStatus, events
from ....order.actions import call_order_event
from ....order.error_codes import OrderErrorCode
@@ -75,7 +77,7 @@ class ShippingMethodUpdateMixin:
invalidate_order_prices(order)
@classmethod
- def update_shipping_method(cls, order, method, shipping_method_data):
+ def update_shipping_method(cls, order, method):
order.shipping_method = method
order.shipping_method_name = method.name
@@ -104,11 +106,12 @@ class ShippingMethodUpdateMixin:
return shipping_channel_listing
@classmethod
- def _update_shipping_price(
- cls,
- order,
- shipping_channel_listing,
- ):
+ def update_shipping_price(cls, order, shipping_channel_listing):
+ cls.assign_shipping_price(order, shipping_channel_listing)
+ cls.update_shipping_discount(order)
+
+ @classmethod
+ def assign_shipping_price(cls, order, shipping_channel_listing):
if not shipping_channel_listing:
order.base_shipping_price = zero_money(order.currency)
order.undiscounted_base_shipping_price = zero_money(order.currency)
@@ -119,12 +122,32 @@ class ShippingMethodUpdateMixin:
and order.shipping_address
and order.is_shipping_required()
):
- order.base_shipping_price = shipping_channel_listing.price
- order.undiscounted_base_shipping_price = shipping_channel_listing.price
+ undiscounted_shipping_price = shipping_channel_listing.price
+ order.undiscounted_base_shipping_price = undiscounted_shipping_price
+ order.base_shipping_price = undiscounted_shipping_price
+
else:
order.base_shipping_price = zero_money(order.currency)
order.undiscounted_base_shipping_price = zero_money(order.currency)
+ @classmethod
+ def update_shipping_discount(cls, order):
+ if shipping_discount := order.discounts.filter(
+ voucher__type=VoucherType.SHIPPING
+ ).first():
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ shipping_price = apply_discount_to_value(
+ value=shipping_discount.value,
+ value_type=shipping_discount.value_type,
+ currency=order.currency,
+ price_to_discount=undiscounted_shipping_price,
+ )
+ order.base_shipping_price = shipping_price
+ shipping_discount_amount = undiscounted_shipping_price - shipping_price
+ if shipping_discount.amount != shipping_discount_amount:
+ shipping_discount.amount = shipping_discount_amount
+ shipping_discount.save(update_fields=["amount_value"])
+
def clean_order_update_shipping(
order, method: ShippingMethodData, manager: "PluginsManager"
@@ -201,7 +224,6 @@ def get_variant_rule_info_map(
variants = product_models.ProductVariant.objects.filter(
pk__in=variant_ids
).prefetch_related(
- "channel_listings__variantlistingpromotionrule__promotion_rule__promotion",
"channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations",
"channel_listings__variantlistingpromotionrule__promotion_rule__translations",
)
diff --git a/saleor/graphql/order/tests/deprecated/test_discount_order.py b/saleor/graphql/order/tests/deprecated/test_discount_order.py
index 64afd04b6c..eaf4302f78 100644
--- a/saleor/graphql/order/tests/deprecated/test_discount_order.py
+++ b/saleor/graphql/order/tests/deprecated/test_discount_order.py
@@ -15,6 +15,14 @@ mutation OrderDiscountDelete($discountId: ID!){
orderDiscountDelete(discountId: $discountId){
order{
id
+ total {
+ net {
+ amount
+ }
+ gross {
+ amount
+ }
+ }
}
errors{
field
@@ -32,6 +40,7 @@ def test_delete_order_discount_from_order_with_old_id(
draft_order_with_fixed_discount_order,
staff_api_client,
permission_group_manage_orders,
+ tax_configuration_flat_rates,
):
# given
order = draft_order_with_fixed_discount_order
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 ea53c95973..6704cfd084 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -5,6 +5,7 @@ from unittest.mock import call, patch
import graphene
from django.db.models import Sum
from django.test import override_settings
+from django.utils import timezone
from freezegun import freeze_time
from prices import Money, TaxedMoney
@@ -14,6 +15,9 @@ from .....core.prices import quantize_price
from .....core.taxes import zero_taxed_money
from .....discount import DiscountValueType
from .....discount.models import VoucherCustomer
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from .....order import OrderOrigin, OrderStatus
from .....order import events as order_events
from .....order.actions import (
@@ -23,7 +27,7 @@ from .....order.actions import (
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
+from .....order.models import OrderEvent, OrderLine
from .....payment.model_helpers import get_subtotal
from .....plugins import PLUGIN_IDENTIFIER_PREFIX
from .....plugins.base_plugin import ExcludedShippingMethod
@@ -260,6 +264,7 @@ def test_draft_order_complete_with_voucher(
order.voucher_code = code_instance.code
order.should_refresh_prices = True
order.save(update_fields=["voucher", "voucher_code", "should_refresh_prices"])
+ create_or_update_voucher_discount_objects_for_order(order)
voucher_listing = voucher.channel_listings.get(channel=order.channel)
discount_value = voucher_listing.discount_value
@@ -1794,3 +1799,32 @@ def test_draft_order_complete_do_not_save_user_addresses_in_customer_book(
assert order.draft_save_shipping_address is None
assert order.draft_save_billing_address is None
+
+
+def test_draft_order_complete_clear_line_draft_base_price_expire_at_field(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+):
+ # given
+ order = draft_order
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ expire_time = timezone.now() + datetime.timedelta(hours=24)
+ lines = order.lines.all()
+ for line in lines:
+ line.draft_base_price_expire_at = expire_time
+ OrderLine.objects.bulk_update(lines, ["draft_base_price_expire_at"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderComplete"]["errors"]
+
+ for line in order.lines.all():
+ assert line.draft_base_price_expire_at is None
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 03e2a38c69..06ccdf0b46 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_create.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_create.py
@@ -1,10 +1,13 @@
import datetime
+from datetime import timedelta
from decimal import Decimal
from unittest.mock import Mock, patch
import graphene
import pytest
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from prices import Money
from .....checkout import AddressType
@@ -17,7 +20,7 @@ from .....order import OrderStatus
from .....order import events as order_events
from .....order.actions import call_order_event
from .....order.error_codes import OrderErrorCode
-from .....order.models import Order, OrderEvent
+from .....order.models import Order, OrderEvent, OrderLine
from .....payment.model_helpers import get_subtotal
from .....product.models import ProductVariant
from .....tax import TaxCalculationStrategy
@@ -815,7 +818,9 @@ def test_draft_order_create_with_voucher_specific_product(
discounted_line_data["unitDiscount"]["amount"]
== discount_amount / variant_0_qty
)
- assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert (
+ discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
+ )
assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
assert line_1_data["productVariantId"] == variant_1_id
@@ -835,8 +840,8 @@ def test_draft_order_create_with_voucher_specific_product(
order_line_discount = discounted_line.discounts.first()
assert order_line_discount.voucher == voucher
assert order_line_discount.type == DiscountType.VOUCHER
- assert order_line_discount.value_type == DiscountValueType.FIXED
- assert order_line_discount.value == discount_amount
+ assert order_line_discount.value_type == voucher.discount_value_type
+ assert order_line_discount.value == discount_value
assert order_line_discount.amount_value == discount_amount
@@ -957,7 +962,9 @@ def test_draft_order_create_with_voucher_apply_once_per_order(
discounted_line_data["unitDiscount"]["amount"]
== discount_amount / variant_0_qty
)
- assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert (
+ discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
+ )
assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
assert line_1_data["productVariantId"] == variant_1_id
@@ -977,8 +984,8 @@ def test_draft_order_create_with_voucher_apply_once_per_order(
order_line_discount = discounted_line.discounts.first()
assert order_line_discount.voucher == voucher
assert order_line_discount.type == DiscountType.VOUCHER
- assert order_line_discount.value_type == DiscountValueType.FIXED
- assert order_line_discount.value == discount_amount
+ assert order_line_discount.value_type == voucher.discount_value_type
+ assert order_line_discount.value == discount_value
assert order_line_discount.amount_value == discount_amount
@@ -2837,6 +2844,9 @@ def test_draft_order_create_product_catalogue_promotion(
reward_value = Decimal("1.0")
rule = promotion.rules.first()
+ rule.reward_value = reward_value
+ rule.save(update_fields=["reward_value"])
+
variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
variant_channel_listing.discounted_price_amount = (
@@ -2968,6 +2978,8 @@ def test_draft_order_create_product_catalogue_promotion_flat_taxes(
reward_value = Decimal("1.0")
rule = promotion.rules.first()
+ rule.reward_value = reward_value
+ rule.save(update_fields=["reward_value"])
variant_channel_listing = variant.channel_listings.get(channel=channel_USD)
variant_channel_listing.discounted_price_amount = (
@@ -3919,3 +3931,45 @@ def test_draft_order_create_no_billing_address_provided_save_address_raising_err
error = data["errors"][0]
assert error["field"] == "saveBillingAddress"
assert error["code"] == OrderErrorCode.MISSING_ADDRESS_DATA.name
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_draft_order_create_set_order_line_price_expiration_time(
+ staff_api_client,
+ permission_group_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ graphql_address_data,
+ channel_USD,
+):
+ # given
+ query = DRAFT_ORDER_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ 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)
+
+ variables = {
+ "input": {
+ "user": user_id,
+ "channelId": channel_id,
+ "lines": [{"variantId": variant_id, "quantity": 2}],
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ }
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ expire_period = channel_USD.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+ expected_expire_time = timezone.now() + timedelta(hours=expire_period)
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ new_line = OrderLine.objects.get()
+ assert new_line.draft_base_price_expire_at == expected_expire_time
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 5e930b0fb3..5ccec369ae 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_update.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_update.py
@@ -11,10 +11,15 @@ from .....core.prices import quantize_price
from .....core.taxes import zero_money
from .....discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
from .....discount.models import OrderDiscount, Voucher
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from .....order import OrderStatus
from .....order.actions import call_order_event
+from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
+from .....order.utils import update_discount_for_order_line
from .....payment.model_helpers import get_subtotal
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -361,7 +366,9 @@ def test_draft_order_update_with_voucher_specific_product(
discounted_line_data["unitDiscount"]["amount"]
== discount_amount / discounted_line.quantity
)
- assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert (
+ discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
+ )
assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
line_1_total = line_1.undiscounted_base_unit_price_amount * line_1.quantity
@@ -380,8 +387,8 @@ def test_draft_order_update_with_voucher_specific_product(
order_line_discount = discounted_line.discounts.first()
assert order_line_discount.voucher == voucher
assert order_line_discount.type == DiscountType.VOUCHER
- assert order_line_discount.value_type == DiscountValueType.FIXED
- assert order_line_discount.value == discount_amount
+ assert order_line_discount.value_type == voucher.discount_value_type
+ assert order_line_discount.value == voucher_listing.discount_value
assert order_line_discount.amount_value == discount_amount
@@ -453,7 +460,9 @@ def test_draft_order_update_with_voucher_apply_once_per_order(
assert discounted_line_data["unitDiscount"]["amount"] == float(
round(discount_amount / discounted_line.quantity, 2)
)
- assert discounted_line_data["unitDiscountType"] == DiscountValueType.FIXED.upper()
+ assert (
+ discounted_line_data["unitDiscountType"] == voucher.discount_value_type.upper()
+ )
assert discounted_line_data["unitDiscountReason"] == f"Voucher code: {code}"
line_1_total = line_1.undiscounted_base_unit_price_amount * line_1.quantity
@@ -472,8 +481,8 @@ def test_draft_order_update_with_voucher_apply_once_per_order(
order_line_discount = discounted_line.discounts.first()
assert order_line_discount.voucher == voucher
assert order_line_discount.type == DiscountType.VOUCHER
- assert order_line_discount.value_type == DiscountValueType.FIXED
- assert order_line_discount.value == discount_amount
+ assert order_line_discount.value_type == voucher.discount_value_type
+ assert order_line_discount.value == voucher_listing.discount_value
assert order_line_discount.amount_value == discount_amount
@@ -1844,6 +1853,75 @@ def test_draft_order_update_shipping_method(
assert order.shipping_price_gross == shipping_price.gross
+def test_draft_order_update_shipping_method_order_with_shipping_voucher(
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ shipping_method,
+ voucher_free_shipping,
+ channel_USD,
+):
+ # given
+ voucher = voucher_free_shipping
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = draft_order
+
+ # clear shipping data
+ order.shipping_method = None
+ order.undiscounted_base_shipping_price_amount = 0
+ order.base_shipping_price_amount = 0
+ order.shipping_price_gross_amount = 0
+ order.shipping_price_net_amount = 0
+
+ order.voucher = voucher
+ order.save()
+
+ # create shipping voucher discount
+ voucher_reward = 50
+ voucher.channel_listings.filter(channel=channel_USD).update(
+ discount_value=voucher_reward
+ )
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ query = DRAFT_ORDER_UPDATE_SHIPPING_METHOD_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {
+ "id": order_id,
+ "shippingMethod": method_id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ order.refresh_from_db()
+
+ undiscounted_shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).price
+ shipping_total = undiscounted_shipping_total * voucher_reward / 100
+ shipping_price = TaxedMoney(shipping_total, shipping_total)
+
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ assert data["order"]["shippingMethodName"] == shipping_method.name
+ assert data["order"]["shippingPrice"]["net"]["amount"] == quantize_price(
+ shipping_price.net.amount, shipping_price.currency
+ )
+ assert data["order"]["shippingPrice"]["gross"]["amount"] == quantize_price(
+ shipping_price.gross.amount, shipping_price.currency
+ )
+
+ assert order.base_shipping_price == shipping_total
+ assert order.shipping_method == shipping_method
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_total
+ assert order.shipping_price_net == shipping_price.net
+ assert order.shipping_price_gross == shipping_price.gross
+
+
def test_draft_order_update_no_shipping_method_channel_listings(
staff_api_client, permission_group_manage_orders, draft_order, shipping_method
):
@@ -2660,3 +2738,300 @@ def test_draft_order_update_with_metadata(
assert private_metadata_result_list[0]["key"] == private_metadata_key
assert private_metadata_result_list[0]["value"] == private_metadata_value
+
+
+def test_draft_order_update_with_voucher_specific_product_and_manual_line_discount(
+ order_with_lines,
+ voucher_specific_product_type,
+ staff_api_client,
+ permission_group_manage_orders,
+ tax_configuration_flat_rates,
+ plugins_manager,
+):
+ """Manual line discount takes precedence over vouchers."""
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ voucher = voucher_specific_product_type
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ voucher_discount_value = Decimal("2")
+ voucher_listing.discount_value = voucher_discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+
+ # create manual order line discount
+ manual_line_discount_value = Decimal("3")
+ update_discount_for_order_line(
+ discounted_line,
+ order=order,
+ reason="Manual line discount",
+ value_type=DiscountValueType.FIXED,
+ value=manual_line_discount_value,
+ )
+ fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": voucher.codes.first().code,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ discounted_line.refresh_from_db()
+ line_1.refresh_from_db()
+
+ manual_discount_amount = manual_line_discount_value * discounted_line.quantity
+ assert (
+ order.total_net_amount
+ == undiscounted_subtotal.amount + shipping_price.amount - manual_discount_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (
+ undiscounted_subtotal.amount
+ + shipping_price.amount
+ - manual_discount_amount
+ )
+ * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - manual_discount_amount
+ )
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - manual_discount_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.base_shipping_price == shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ - manual_line_discount_value
+ )
+ assert (
+ discounted_line.total_price_net_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity * tax_rate
+ )
+ assert (
+ discounted_line.undiscounted_total_price_net_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == manual_line_discount_value
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == "Manual line discount"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_net_amount
+ == order.subtotal_net_amount - discounted_line.total_price_net_amount
+ )
+ assert (
+ line_1.total_price_gross_amount
+ == (order.subtotal_net_amount - discounted_line.total_price_net_amount)
+ * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+
+
+def test_draft_order_update_with_voucher_apply_once_per_order_and_manual_line_discount(
+ order_with_lines,
+ voucher,
+ staff_api_client,
+ permission_group_manage_orders,
+ tax_configuration_flat_rates,
+ plugins_manager,
+):
+ """Manual line discount takes precedence over vouchers."""
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ voucher_discount_value = Decimal("3")
+ voucher_listing.discount_value = voucher_discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+
+ # create manual order line discount
+ manual_line_discount_value = Decimal("3")
+ update_discount_for_order_line(
+ discounted_line,
+ order=order,
+ reason="Manual line discount",
+ value_type=DiscountValueType.FIXED,
+ value=manual_line_discount_value,
+ )
+ fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ variables = {
+ "id": order_id,
+ "input": {
+ "voucherCode": voucher.codes.first().code,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_UPDATE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderUpdate"]
+ assert not data["errors"]
+
+ discounted_line.refresh_from_db()
+ line_1.refresh_from_db()
+
+ manual_discount_amount = manual_line_discount_value * discounted_line.quantity
+ assert (
+ order.total_net_amount
+ == undiscounted_subtotal.amount + shipping_price.amount - manual_discount_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (
+ undiscounted_subtotal.amount
+ + shipping_price.amount
+ - manual_discount_amount
+ )
+ * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - manual_discount_amount
+ )
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - manual_discount_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.base_shipping_price == shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ - manual_line_discount_value
+ )
+ assert (
+ discounted_line.total_price_net_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity * tax_rate
+ )
+ assert (
+ discounted_line.undiscounted_total_price_net_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == manual_line_discount_value
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == "Manual line discount"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_net_amount
+ == order.subtotal_net_amount - discounted_line.total_price_net_amount
+ )
+ assert (
+ line_1.total_price_gross_amount
+ == (order.subtotal_net_amount - discounted_line.total_price_net_amount)
+ * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
diff --git a/saleor/graphql/order/tests/mutations/test_order_discount.py b/saleor/graphql/order/tests/mutations/test_order_discount.py
index d8812b1be5..4e6749c6f2 100644
--- a/saleor/graphql/order/tests/mutations/test_order_discount.py
+++ b/saleor/graphql/order/tests/mutations/test_order_discount.py
@@ -7,7 +7,11 @@ import pytest
from prices import Money, TaxedMoney, fixed_discount, percentage_discount
from .....core.prices import quantize_price
+from .....core.taxes import zero_money
from .....discount import DiscountType, DiscountValueType
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from .....order import OrderEvents, OrderStatus
from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
@@ -1358,23 +1362,27 @@ def test_update_order_line_discount_line_with_catalogue_promotion(
order_with_lines_and_catalogue_promotion,
staff_api_client,
permission_group_manage_orders,
+ tax_configuration_flat_rates,
):
# given
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines_and_catalogue_promotion
+ currency = order.currency
order.status = OrderStatus.DRAFT
order.save(update_fields=["status"])
line = order.lines.get(quantity=3)
assert line.discounts.filter(type=DiscountType.PROMOTION).exists()
+ unidscounted_unit_price = line.undiscounted_base_unit_price.amount
+ tax_rate = Decimal("1.23")
- value = Decimal("5")
+ manual_discount_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,
+ "value": manual_discount_value,
"reason": reason,
},
}
@@ -1386,13 +1394,44 @@ def test_update_order_line_discount_line_with_catalogue_promotion(
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountUpdate"]
assert not data["errors"]
+ line.refresh_from_db()
line_discount = line.discounts.get()
assert line_discount.type == DiscountType.MANUAL
- assert line_discount.value == value
+ assert line_discount.value == manual_discount_value
assert line_discount.value_type == value_type.value
assert line_discount.reason == reason
- assert line_discount.amount_value == value * line.quantity
+ assert line_discount.amount_value == manual_discount_value * line.quantity
+
+ line_unit_price = unidscounted_unit_price - manual_discount_value
+ line_undiscounted_total_net_amount = quantize_price(
+ unidscounted_unit_price * line.quantity,
+ currency,
+ )
+ line_total_net_amount = quantize_price(
+ line.base_unit_price_amount * line.quantity,
+ currency,
+ )
+ assert line.undiscounted_unit_price_net_amount == unidscounted_unit_price
+ assert line.undiscounted_unit_price_gross_amount == quantize_price(
+ unidscounted_unit_price * tax_rate, currency
+ )
+ assert line.undiscounted_base_unit_price_amount == unidscounted_unit_price
+ assert line.base_unit_price_amount == line_unit_price
+ assert line.unit_price_net_amount == line_unit_price
+ assert line.unit_price_gross_amount == quantize_price(
+ line_unit_price * tax_rate, currency
+ )
+ assert line.total_price_net_amount == line_total_net_amount
+ assert line.total_price_gross_amount == quantize_price(
+ line_total_net_amount * tax_rate, currency
+ )
+ assert (
+ line.undiscounted_total_price_net_amount == line_undiscounted_total_net_amount
+ )
+ assert line.undiscounted_total_price_gross_amount == quantize_price(
+ line_undiscounted_total_net_amount * tax_rate, currency
+ )
def test_update_order_line_discount_order_is_not_draft(
@@ -1430,6 +1469,291 @@ def test_update_order_line_discount_order_is_not_draft(
assert line_to_discount.unit_discount_amount == Decimal("0")
+def test_add_manual_line_discount_order_with_voucher_specific_product(
+ order_with_lines,
+ voucher_specific_product_type,
+ staff_api_client,
+ permission_group_manage_orders,
+ tax_configuration_flat_rates,
+):
+ """Manual line discount takes precedence over vouchers."""
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ voucher = voucher_specific_product_type
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ voucher_discount_value = Decimal("2")
+ voucher_listing.discount_value = voucher_discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+ voucher.variants.add(discounted_line.variant)
+
+ # create voucher line discount
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ manual_line_discount_value = Decimal("3")
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", discounted_line.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": manual_line_discount_value,
+ "reason": "Manual line discount",
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLineDiscountUpdate"]
+ assert not data["errors"]
+
+ discounted_line.refresh_from_db()
+ line_1.refresh_from_db()
+ order.refresh_from_db()
+
+ manual_discount_amount = manual_line_discount_value * discounted_line.quantity
+ assert (
+ order.total_net_amount
+ == undiscounted_subtotal.amount + shipping_price.amount - manual_discount_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (
+ undiscounted_subtotal.amount
+ + shipping_price.amount
+ - manual_discount_amount
+ )
+ * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - manual_discount_amount
+ )
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - manual_discount_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.base_shipping_price == shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ - manual_line_discount_value
+ )
+ assert (
+ discounted_line.total_price_net_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity * tax_rate
+ )
+ assert (
+ discounted_line.undiscounted_total_price_net_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == manual_line_discount_value
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == "Manual line discount"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_net_amount
+ == order.subtotal_net_amount - discounted_line.total_price_net_amount
+ )
+ assert (
+ line_1.total_price_gross_amount
+ == (order.subtotal_net_amount - discounted_line.total_price_net_amount)
+ * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+
+
+def test_add_manual_line_discount_order_with_voucher_apply_once_per_order(
+ order_with_lines,
+ voucher,
+ staff_api_client,
+ permission_group_manage_orders,
+ tax_configuration_flat_rates,
+):
+ """Manual line discount takes precedence over vouchers."""
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ tax_rate = Decimal("1.23")
+
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ voucher_discount_value = Decimal("3")
+ voucher_listing.discount_value = voucher_discount_value
+ voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
+
+ lines = order.lines.all()
+ discounted_line, line_1 = lines
+
+ # create voucher line discount
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ shipping_price = order.shipping_price.net
+ currency = order.currency
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ manual_line_discount_value = Decimal("3")
+ variables = {
+ "orderLineId": graphene.Node.to_global_id("OrderLine", discounted_line.pk),
+ "input": {
+ "valueType": DiscountValueTypeEnum.FIXED.name,
+ "value": manual_line_discount_value,
+ "reason": "Manual line discount",
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_LINE_DISCOUNT_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLineDiscountUpdate"]
+ assert not data["errors"]
+
+ discounted_line.refresh_from_db()
+ line_1.refresh_from_db()
+ order.refresh_from_db()
+
+ manual_discount_amount = manual_line_discount_value * discounted_line.quantity
+ assert (
+ order.total_net_amount
+ == undiscounted_subtotal.amount + shipping_price.amount - manual_discount_amount
+ )
+ assert (
+ order.total_gross_amount
+ == (
+ undiscounted_subtotal.amount
+ + shipping_price.amount
+ - manual_discount_amount
+ )
+ * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - manual_discount_amount
+ )
+ assert (
+ order.subtotal_gross_amount
+ == (undiscounted_subtotal.amount - manual_discount_amount) * tax_rate
+ )
+ assert order.undiscounted_total_net == undiscounted_subtotal + shipping_price
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + shipping_price) * tax_rate
+ )
+ assert order.shipping_price_net == shipping_price
+ assert order.shipping_price_gross == shipping_price * tax_rate
+ assert order.base_shipping_price == shipping_price
+
+ assert (
+ discounted_line.base_unit_price_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ - manual_line_discount_value
+ )
+ assert (
+ discounted_line.total_price_net_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity
+ )
+ assert (
+ discounted_line.total_price_gross_amount
+ == discounted_line.unit_price_net_amount * discounted_line.quantity * tax_rate
+ )
+ assert (
+ discounted_line.undiscounted_total_price_net_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ )
+ assert (
+ discounted_line.undiscounted_total_price_gross_amount
+ == discounted_line.undiscounted_base_unit_price_amount
+ * discounted_line.quantity
+ * tax_rate
+ )
+ assert discounted_line.unit_discount_amount == manual_line_discount_value
+ assert discounted_line.unit_discount_type == DiscountValueType.FIXED
+ assert discounted_line.unit_discount_reason == "Manual line discount"
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_net_amount
+ == order.subtotal_net_amount - discounted_line.total_price_net_amount
+ )
+ assert (
+ line_1.total_price_gross_amount
+ == (order.subtotal_net_amount - discounted_line.total_price_net_amount)
+ * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+
+ assert discounted_line.discounts.count() == 1
+
+
ORDER_LINE_DISCOUNT_REMOVE = """
mutation OrderLineDiscountRemove($orderLineId: ID!){
orderLineDiscountRemove(orderLineId: $orderLineId){
@@ -1694,6 +2018,7 @@ def test_delete_order_line_discount_line_with_catalogue_promotion(
staff_api_client,
permission_group_manage_orders,
):
+ """Deleting the discount should restore undiscounted prices for the line."""
# given
permission_group_manage_orders.user_set.add(staff_api_client.user)
order = order_with_lines_and_catalogue_promotion
@@ -1722,7 +2047,10 @@ def test_delete_order_line_discount_line_with_catalogue_promotion(
content = get_graphql_content(response)
data = content["data"]["orderLineDiscountRemove"]
assert not data["errors"]
- assert line.discounts.filter(type=DiscountType.PROMOTION).exists()
+ line.refresh_from_db()
+ assert not line.discounts.filter(type=DiscountType.PROMOTION).exists()
+ assert line.unit_price_net_amount == line.undiscounted_unit_price_net_amount
+ assert line.total_price_net_amount == line.undiscounted_total_price_net_amount
def test_delete_order_line_discount_with_line_level_voucher(
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 226b576208..a4b3f4c654 100644
--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py
+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py
@@ -6,13 +6,22 @@ import pytest
from django.test import override_settings
from .....core.models import EventDelivery
-from .....discount import DiscountType, RewardValueType
+from .....core.prices import quantize_price
+from .....core.taxes import zero_money
+from .....discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from .....discount.models import PromotionRule
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from .....order import OrderStatus
from .....order import events as order_events
from .....order.actions import call_order_event
+from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
-from .....product.models import ProductVariant
+from .....product.models import Product, ProductVariant
+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 Allocation, Stock
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -35,6 +44,40 @@ ORDER_LINE_UPDATE_MUTATION = """
unitDiscountType
unitDiscountValue
isGift
+ totalPrice {
+ gross {
+ amount
+ }
+ net {
+ amount
+ }
+ }
+ undiscountedTotalPrice {
+ gross {
+ amount
+ }
+ net {
+ amount
+ }
+ }
+ unitPrice {
+ gross {
+ amount
+ currency
+ }
+ net {
+ amount
+ currency
+ }
+ }
+ undiscountedUnitPrice {
+ gross {
+ amount
+ }
+ net {
+ amount
+ }
+ }
}
order {
total {
@@ -667,3 +710,736 @@ def test_order_line_update_triggers_webhooks(
)
assert wrapped_call_order_event.called
+
+
+def test_order_line_update_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+):
+ # give
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ tax_rate = Decimal(1.23)
+
+ currency = order.currency
+ line = order.lines.first()
+ old_quantity = line.quantity
+ lines_count = len(order.lines.all())
+ undiscounted_unit_price = line.undiscounted_base_unit_price_amount
+
+ discount = line.discounts.get()
+ initial_discount_amount = discount.amount_value
+ unit_discount = quantize_price(initial_discount_amount / old_quantity, currency)
+
+ # update variant channel listing
+ variant_channel_listing = line.variant.channel_listings.get(channel=order.channel)
+ new_variant_price = undiscounted_unit_price + Decimal(100)
+ variant_channel_listing.price_amount = new_variant_price
+ variant_channel_listing.save(update_fields=["price_amount"])
+
+ # update catalogue discount
+ rule = discount.promotion_rule
+ reward_value = rule.reward_value
+ new_reward_value = reward_value + Decimal(10)
+ rule.reward_value = new_reward_value
+ rule.save(update_fields=["reward_value"])
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ new_quantity = 4
+ line_id = graphene.Node.to_global_id("OrderLine", line.id)
+ variables = {"lineId": line_id, "quantity": new_quantity}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+
+ assert order.lines.count() == lines_count
+ line.refresh_from_db()
+ line_data = content["data"]["orderLineUpdate"]["orderLine"]
+ assert line_data["quantity"] == new_quantity
+ unit_price = undiscounted_unit_price - unit_discount
+ assert line_data["unitPrice"]["net"]["amount"] == unit_price
+ assert Decimal(str(line_data["unitPrice"]["gross"]["amount"])) == quantize_price(
+ unit_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedUnitPrice"]["net"]["amount"] == undiscounted_unit_price
+ )
+ assert Decimal(
+ str(line_data["undiscountedUnitPrice"]["gross"]["amount"])
+ ) == quantize_price(undiscounted_unit_price * tax_rate, currency)
+ total_price = unit_price * new_quantity
+ assert line_data["totalPrice"]["net"]["amount"] == total_price
+ assert Decimal(str(line_data["totalPrice"]["gross"]["amount"])) == quantize_price(
+ total_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedTotalPrice"]["net"]["amount"]
+ == undiscounted_unit_price * new_quantity
+ )
+ assert Decimal(
+ str(line_data["undiscountedTotalPrice"]["gross"]["amount"])
+ ) == quantize_price(undiscounted_unit_price * new_quantity * tax_rate, currency)
+
+ discount.refresh_from_db()
+ assert discount.amount_value != initial_discount_amount
+ assert discount.amount_value == unit_discount * new_quantity
+
+
+def test_order_line_update_apply_once_per_order_voucher_discount(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+ voucher,
+ plugins_manager,
+):
+ """Updating the cheapest product line should only update voucher discount amount.
+
+ The voucher discount should use denormalized voucher reward.
+ """
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply voucher apply once per order type
+ initial_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_discount_value = voucher_listing.discount_value
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price < line_2.undiscounted_base_unit_price
+ discount = line_1.discounts.get()
+ initial_discount_amount = (
+ line_1.undiscounted_base_unit_price_amount * initial_discount_value / 100
+ )
+ initial_unit_discount_amount = initial_discount_amount / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - initial_discount_amount,
+ currency,
+ )
+ assert discount.value == initial_discount_value
+ assert discount.value_type == DiscountValueType.PERCENTAGE
+ assert discount.amount_value == initial_discount_amount
+
+ # update voucher listing value and voucher discount value type
+ voucher_listing.discount_value /= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_discount_value
+ new_voucher_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+
+ # add 1 unit to line 1
+ new_quantity = line_1.quantity + 1
+ line_1_id = graphene.Node.to_global_id("OrderLine", line_1.id)
+ variables = {"lineId": line_1_id, "quantity": new_quantity}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLineUpdate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2 = order.lines.all()
+ new_unit_discount_amount = initial_discount_amount / new_quantity
+
+ discount.refresh_from_db()
+ assert discount.value == initial_discount_value
+ assert discount.value_type == initial_discount_value_type
+ assert discount.amount_value == initial_discount_amount
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - new_unit_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - initial_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_gross_amount, currency) == quantize_price(
+ line_1.base_unit_price_amount * new_quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ line_1.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert line_1.unit_discount_amount == new_unit_discount_amount
+ assert line_1.unit_discount_type == initial_discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == initial_discount_value
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += line_1.undiscounted_unit_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - initial_discount_amount
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (order.undiscounted_total_net_amount - initial_discount_amount) * tax_rate,
+ currency,
+ )
+
+
+def test_order_line_update_specific_product_voucher_discount_percentage(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+ voucher,
+ plugins_manager,
+):
+ """The voucher discount should use denormalized voucher values."""
+
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply specific product voucher
+ initial_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.add(line_1.variant)
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_discount_value = voucher_listing.discount_value
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ initial_unit_discount = (
+ line_1.undiscounted_base_unit_price_amount * initial_discount_value / 100
+ )
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_unit_discount
+ )
+ discount_amount = initial_unit_discount * line_1.quantity
+ discount = line_1.discounts.get()
+ assert discount.value == initial_discount_value
+ assert discount.value_type == DiscountValueType.PERCENTAGE
+ assert discount.amount_value == discount_amount
+
+ # update voucher listing value, discount value type and eligible variants
+ voucher_listing.discount_value /= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_discount_value
+ new_voucher_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+ voucher.variants.set([line_2.variant])
+
+ # add 1 unit to line 1
+ new_quantity = line_1.quantity + 1
+ line_1_id = graphene.Node.to_global_id("OrderLine", line_1.id)
+ variables = {"lineId": line_1_id, "quantity": new_quantity}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLineUpdate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2 = order.lines.all()
+ new_discount_amount = initial_unit_discount * new_quantity
+
+ discount.refresh_from_db()
+ assert discount.value == initial_discount_value
+ assert discount.value_type == initial_discount_value_type
+ assert discount.amount_value == new_discount_amount
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - new_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_gross_amount, currency) == quantize_price(
+ line_1.base_unit_price_amount * new_quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ line_1.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert line_1.unit_discount_amount == initial_unit_discount
+ assert line_1.unit_discount_type == initial_discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == initial_discount_value
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += line_1.undiscounted_unit_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal.amount - new_discount_amount
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (order.undiscounted_total_net_amount - new_discount_amount) * tax_rate,
+ currency,
+ )
+
+
+def test_order_line_update_specific_product_voucher_discount_fixed(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+ voucher,
+ plugins_manager,
+):
+ """The voucher discount should use denormalized voucher values."""
+
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply specific product voucher
+ initial_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.add(line_1.variant)
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_unit_discount = Decimal(2)
+ voucher_listing.discount_value = initial_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_unit_discount
+ )
+ discount_amount = initial_unit_discount * line_1.quantity
+ discount = line_1.discounts.get()
+ assert discount.value == initial_unit_discount
+ assert discount.value_type == initial_discount_value_type
+ assert discount.amount_value == discount_amount
+
+ # update voucher listing value, discount value type and eligible variants
+ voucher_listing.discount_value *= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_unit_discount
+ new_voucher_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+ voucher.variants.set([line_2.variant])
+
+ # add 1 unit to line 1
+ new_quantity = line_1.quantity + 1
+ line_1_id = graphene.Node.to_global_id("OrderLine", line_1.id)
+ variables = {"lineId": line_1_id, "quantity": new_quantity}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLineUpdate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2 = order.lines.all()
+ new_discount_amount = initial_unit_discount * new_quantity
+
+ discount.refresh_from_db()
+ assert discount.value == initial_unit_discount
+ assert discount.value_type == initial_discount_value_type
+ assert discount.amount_value == new_discount_amount
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - new_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_gross_amount, currency) == quantize_price(
+ line_1.base_unit_price_amount * new_quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ line_1.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert line_1.unit_discount_amount == initial_unit_discount
+ assert line_1.unit_discount_type == initial_discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == initial_unit_discount
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += line_1.undiscounted_unit_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal.amount - new_discount_amount
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (order.undiscounted_total_net_amount - new_discount_amount) * tax_rate,
+ currency,
+ )
+
+
+def test_order_line_update_specific_product_voucher_discount_multiple_lines(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+ voucher,
+ plugins_manager,
+):
+ """The voucher discount should use denormalized voucher values."""
+
+ query = ORDER_LINE_UPDATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply specific product voucher
+ initial_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.set([line_1.variant, line_2.variant])
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_unit_discount = Decimal(2)
+ voucher_listing.discount_value = initial_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_unit_discount
+ )
+ discount_amount_1 = initial_unit_discount * line_1.quantity
+ discount_1 = line_1.discounts.get()
+ assert discount_1.value == initial_unit_discount
+ assert discount_1.value_type == initial_discount_value_type
+ assert discount_1.amount_value == discount_amount_1
+
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - initial_unit_discount
+ )
+ discount_amount_2 = initial_unit_discount * line_2.quantity
+ discount_2 = line_2.discounts.get()
+ assert discount_2.value == initial_unit_discount
+ assert discount_2.value_type == initial_discount_value_type
+ assert discount_2.amount_value == discount_amount_2
+
+ # update voucher listing value, discount value type and eligible variants
+ voucher_listing.discount_value *= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_unit_discount
+ new_voucher_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+ voucher.variants.set([])
+
+ # add 1 unit to line 1
+ new_quantity_1 = line_1.quantity + 1
+ line_1_id = graphene.Node.to_global_id("OrderLine", line_1.id)
+ variables = {"lineId": line_1_id, "quantity": new_quantity_1}
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLineUpdate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2 = order.lines.all()
+ new_discount_amount_1 = initial_unit_discount * new_quantity_1
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == initial_unit_discount
+ assert discount_1.value_type == initial_discount_value_type
+ assert discount_1.amount_value == new_discount_amount_1
+ assert discount_1.type == DiscountType.VOUCHER
+ assert discount_1.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - new_discount_amount_1,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_gross_amount, currency) == quantize_price(
+ line_1.base_unit_price_amount * new_quantity_1 * tax_rate, currency
+ )
+ assert quantize_price(
+ line_1.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert line_1.unit_discount_amount == initial_unit_discount
+ assert line_1.unit_discount_type == initial_discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == initial_unit_discount
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == initial_unit_discount
+ assert discount_2.value_type == initial_discount_value_type
+ assert discount_2.amount_value == discount_amount_2
+ assert discount_2.type == DiscountType.VOUCHER
+ assert discount_2.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_2.base_unit_price_amount, currency) == quantize_price(
+ line_2.undiscounted_base_unit_price_amount - initial_unit_discount,
+ currency,
+ )
+ assert quantize_price(line_2.total_price_net_amount, currency) == quantize_price(
+ line_2.undiscounted_total_price_net_amount - discount_amount_2,
+ currency,
+ )
+ assert quantize_price(line_2.total_price_gross_amount, currency) == quantize_price(
+ line_2.base_unit_price_amount * line_2.quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ line_2.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate,
+ currency,
+ )
+ assert line_2.unit_discount_amount == initial_unit_discount
+ assert line_2.unit_discount_type == initial_discount_value_type
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_2.unit_discount_value == initial_unit_discount
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += line_1.undiscounted_unit_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - new_discount_amount_1 - discount_amount_2
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (
+ order.undiscounted_total_net_amount
+ - new_discount_amount_1
+ - discount_amount_2
+ )
+ * tax_rate,
+ currency,
+ )
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 197fdfcfcd..c3c551d0b1 100644
--- a/saleor/graphql/order/tests/mutations/test_order_lines_create.py
+++ b/saleor/graphql/order/tests/mutations/test_order_lines_create.py
@@ -1,4 +1,5 @@
import datetime
+from datetime import timedelta
from decimal import Decimal
from unittest.mock import patch
@@ -6,15 +7,26 @@ import graphene
import pytest
from django.db.models import Sum
from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from .....core.models import EventDelivery
-from .....discount import DiscountType, RewardValueType
+from .....core.prices import quantize_price
+from .....core.taxes import zero_money
+from .....discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from .....discount.models import OrderLineDiscount, PromotionRule
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from .....order import OrderStatus
from .....order import events as order_events
from .....order.actions import call_order_event
+from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent, OrderLine
-from .....product.models import ProductVariant
+from .....product.models import Product, ProductVariant
+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 Allocation, Stock
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -50,6 +62,22 @@ ORDER_LINES_CREATE_MUTATION = """
productSku
productVariantId
saleId
+ totalPrice {
+ gross {
+ amount
+ }
+ net {
+ amount
+ }
+ }
+ undiscountedTotalPrice {
+ gross {
+ amount
+ }
+ net {
+ amount
+ }
+ }
unitPrice {
gross {
amount
@@ -64,6 +92,9 @@ ORDER_LINES_CREATE_MUTATION = """
gross {
amount
}
+ net {
+ amount
+ }
}
unitDiscount {
amount
@@ -1099,7 +1130,6 @@ def test_order_lines_create_with_custom_price_and_catalogue_discount(
order.status = OrderStatus.DRAFT
order.save(update_fields=["status"])
- order_line = order.lines.first()
old_qty = order_line.quantity
lines_count = len(order.lines.all())
@@ -1108,11 +1138,8 @@ def test_order_lines_create_with_custom_price_and_catalogue_discount(
variant_listings = variant.channel_listings.get(channel=order.channel)
promotion_rule = variant_listings.promotion_rules.first()
promotion_rule.variants.add(variant)
-
- reward_value = Decimal("5")
- promotion_rule.reward_value = reward_value
- promotion_rule.reward_value_type = RewardValueType.FIXED
- promotion_rule.save(update_fields=["reward_value", "reward_value_type"])
+ reward_value = promotion_rule.reward_value
+ assert promotion_rule.reward_value_type == DiscountValueType.FIXED
quantity = 1
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -1168,11 +1195,10 @@ def test_order_lines_create_with_custom_price_force_new_line_and_catalogue_disco
variant_listings = variant.channel_listings.get(channel=order.channel)
promotion_rule = variant_listings.promotion_rules.first()
promotion_rule.variants.add(variant)
+ reward_value = promotion_rule.reward_value
+ assert promotion_rule.reward_value_type == DiscountValueType.FIXED
- reward_value = Decimal("5")
- promotion_rule.reward_value = reward_value
- promotion_rule.reward_value_type = RewardValueType.FIXED
- promotion_rule.save(update_fields=["reward_value", "reward_value_type"])
+ update_discounted_prices_for_promotion(Product.objects.all())
quantity = 1
order_id = graphene.Node.to_global_id("Order", order.id)
@@ -1328,3 +1354,815 @@ def test_order_lines_create_triggers_webhooks(
)
assert wrapped_call_order_event.called
+
+
+def test_order_lines_create_with_catalogue_discount_existing_variant(
+ order_with_lines_and_catalogue_promotion,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+ channel = order.channel
+ tax_rate = Decimal("1.23")
+
+ currency = order.currency
+ line = order.lines.first()
+ variant = line.variant
+ old_qty = line.quantity
+ lines_count = len(order.lines.all())
+ undiscounted_unit_price = line.undiscounted_base_unit_price_amount
+
+ discount = line.discounts.get()
+ initial_discount_amount = discount.amount_value
+ unit_discount = quantize_price(initial_discount_amount / old_qty, currency)
+
+ # update variant channel listing
+ variant_channel_listing = variant.channel_listings.get(channel=channel)
+ new_variant_price = undiscounted_unit_price + Decimal(100)
+ variant_channel_listing.price_amount = new_variant_price
+ variant_channel_listing.save(update_fields=["price_amount"])
+
+ # update catalogue discount
+ rule = discount.promotion_rule
+ reward_value = rule.reward_value
+ new_reward_value = reward_value + Decimal(10)
+ rule.reward_value = new_reward_value
+ rule.save(update_fields=["reward_value"])
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ quantity = 1
+ 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,
+ "forceNewLine": False,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ new_qty = quantity + old_qty
+
+ assert order.lines.count() == lines_count
+ line.refresh_from_db()
+ data = content["data"]["orderLinesCreate"]
+ line_data = data["orderLines"][0]
+ assert line_data["productSku"] == variant.sku
+ assert line_data["quantity"] == new_qty
+ unit_price = undiscounted_unit_price - unit_discount
+ assert line_data["unitPrice"]["net"]["amount"] == unit_price
+ assert Decimal(str(line_data["unitPrice"]["gross"]["amount"])) == quantize_price(
+ unit_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedUnitPrice"]["net"]["amount"] == undiscounted_unit_price
+ )
+ assert Decimal(
+ str(line_data["undiscountedUnitPrice"]["gross"]["amount"])
+ ) == quantize_price(undiscounted_unit_price * tax_rate, currency)
+ total_price = unit_price * new_qty
+ assert line_data["totalPrice"]["net"]["amount"] == total_price
+ assert Decimal(str(line_data["totalPrice"]["gross"]["amount"])) == quantize_price(
+ total_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedTotalPrice"]["net"]["amount"]
+ == undiscounted_unit_price * new_qty
+ )
+ assert Decimal(
+ str(line_data["undiscountedTotalPrice"]["gross"]["amount"])
+ ) == quantize_price(undiscounted_unit_price * new_qty * tax_rate, currency)
+
+ discount.refresh_from_db()
+ assert discount.amount_value != initial_discount_amount
+ assert discount.amount_value == unit_discount * new_qty
+
+
+def test_order_lines_create_apply_once_per_order_voucher_new_cheapest_line(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ product_variant_list,
+ tax_configuration_flat_rates,
+ warehouse,
+ voucher,
+ plugins_manager,
+):
+ """Adding new line with the cheapest product should update voucher discount.
+
+ The voucher discount should use denormalized voucher reward.
+ """
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ channel = order.channel
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply voucher apply once per order type
+ initial_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_discount_value = voucher_listing.discount_value
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price < line_2.undiscounted_base_unit_price
+ initial_discount = line_1.discounts.get()
+ initial_discount_amount = (
+ line_1.undiscounted_base_unit_price_amount * initial_discount_value / 100
+ )
+ initial_unit_discount_amount = initial_discount_amount / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - initial_discount_amount,
+ currency,
+ )
+ assert initial_discount.value == initial_discount_value
+ assert initial_discount.value_type == DiscountValueType.PERCENTAGE
+ assert initial_discount.amount_value == initial_discount_amount
+
+ # update voucher listing value and voucher discount value type
+ voucher_listing.discount_value /= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_discount_value
+ new_voucher_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+
+ # prepare new line with the cheapest product
+ new_variant = product_variant_list[0]
+ new_variant_channel_listing = new_variant.channel_listings.get(channel=channel)
+ new_variant_price = line_1.undiscounted_base_unit_price_amount - Decimal(1)
+ new_variant_channel_listing.price_amount = new_variant_price
+ new_variant_channel_listing.discounted_price_amount = new_variant_price
+ new_variant_channel_listing.save(
+ update_fields=["price_amount", "discounted_price_amount"]
+ )
+
+ quantity = 2
+ Stock.objects.create(
+ warehouse=warehouse, product_variant=new_variant, quantity=quantity
+ )
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", new_variant.id)
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": quantity,
+ "forceNewLine": False,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLinesCreate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2, new_line = order.lines.all()
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ initial_discount.refresh_from_db()
+
+ assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
+ assert (
+ line_1.total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert (
+ line_1.undiscounted_total_price_gross_amount
+ == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ )
+ assert line_1.unit_discount_amount == 0
+ assert line_1.unit_discount_type is None
+ assert line_1.unit_discount_reason is None
+ assert line_1.unit_discount_value == 0
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ # new discount should be applied to new line with denormalized voucher reward values
+ new_discount = new_line.discounts.get()
+ new_discount_amount = (
+ new_line.undiscounted_base_unit_price_amount * initial_discount_value / 100
+ )
+ new_unit_discount_amount = new_discount_amount / new_line.quantity
+ assert new_discount.value == initial_discount_value
+ assert new_discount.amount_value == new_discount_amount
+ assert new_discount.value_type == initial_discount_value_type
+ assert new_discount.type == DiscountType.VOUCHER
+ assert new_discount.reason == f"Voucher code: {order.voucher_code}"
+
+ assert (
+ new_line.base_unit_price_amount
+ == new_line.undiscounted_base_unit_price_amount - new_unit_discount_amount
+ )
+ assert (
+ new_line.total_price_net_amount
+ == new_line.undiscounted_total_price_net_amount - new_discount_amount
+ )
+ assert quantize_price(
+ new_line.total_price_gross_amount, currency
+ ) == quantize_price(
+ new_line.base_unit_price_amount * new_line.quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ new_line.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ new_line.undiscounted_base_unit_price_amount * new_line.quantity * tax_rate,
+ currency,
+ )
+ assert new_line.unit_discount_amount == new_unit_discount_amount
+ assert new_line.unit_discount_type == initial_discount_value_type
+ assert new_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert new_line.unit_discount_value == initial_discount_value
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += new_line.undiscounted_total_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal.amount - new_discount_amount
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (order.undiscounted_total_net_amount - new_discount_amount) * tax_rate, currency
+ )
+
+
+def test_order_lines_create_apply_once_per_order_voucher_existing_variant(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+ voucher,
+ plugins_manager,
+):
+ """Creating line with existing variant should only update voucher discount amount.
+
+ The voucher discount should use denormalized voucher reward.
+ """
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply voucher apply once per order type
+ initial_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_discount_value = voucher_listing.discount_value
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price < line_2.undiscounted_base_unit_price
+ discount = line_1.discounts.get()
+ initial_discount_amount = (
+ line_1.undiscounted_base_unit_price_amount * initial_discount_value / 100
+ )
+ initial_unit_discount_amount = initial_discount_amount / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - initial_discount_amount,
+ currency,
+ )
+ assert discount.value == initial_discount_value
+ assert discount.value_type == DiscountValueType.PERCENTAGE
+ assert discount.amount_value == initial_discount_amount
+
+ # update voucher listing value and voucher discount value type
+ voucher_listing.discount_value /= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_discount_value
+ new_voucher_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+
+ # add 1 unit of line 1 variant
+ extra_quantity = 1
+ new_quantity = line_1.quantity + extra_quantity
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", line_1.variant.id)
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": extra_quantity,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLinesCreate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2 = order.lines.all()
+ new_unit_discount_amount = initial_discount_amount / new_quantity
+
+ discount.refresh_from_db()
+ assert discount.value == initial_discount_value
+ assert discount.value_type == initial_discount_value_type
+ assert discount.amount_value == initial_discount_amount
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - new_unit_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - initial_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_gross_amount, currency) == quantize_price(
+ line_1.base_unit_price_amount * new_quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ line_1.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert line_1.unit_discount_amount == new_unit_discount_amount
+ assert line_1.unit_discount_type == initial_discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == initial_discount_value
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += line_1.undiscounted_unit_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal.amount - initial_discount_amount
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (order.undiscounted_total_net_amount - initial_discount_amount) * tax_rate,
+ currency,
+ )
+
+
+def test_order_lines_create_specific_product_voucher_existing_variant(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+ tax_configuration_flat_rates,
+ voucher,
+ plugins_manager,
+):
+ """The order line should be updated with denormalized voucher values."""
+
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ undiscounted_shipping_price = order.undiscounted_base_shipping_price
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # apply specific product voucher
+ initial_discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.discount_value_type = initial_discount_value_type
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.add(line_1.variant)
+ voucher_listing = voucher.channel_listings.get(channel=order.channel)
+ initial_discount_value = voucher_listing.discount_value
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher_code", "voucher_id", "status"])
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ line_1, line_2 = lines
+ initial_unit_discount = (
+ line_1.undiscounted_base_unit_price_amount * initial_discount_value / 100
+ )
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_unit_discount
+ )
+ discount_amount = initial_unit_discount * line_1.quantity
+ discount = line_1.discounts.get()
+ assert discount.value == initial_discount_value
+ assert discount.value_type == DiscountValueType.PERCENTAGE
+ assert discount.amount_value == discount_amount
+
+ # update voucher listing value, discount value type and eligible variants
+ voucher_listing.discount_value /= 2
+ voucher_listing.save(update_fields=["discount_value"])
+ assert voucher_listing.discount_value != initial_discount_value
+ new_voucher_discount_value_type = DiscountValueType.FIXED
+ voucher.discount_value_type = new_voucher_discount_value_type
+ voucher.save(update_fields=["discount_value_type"])
+ assert initial_discount_value_type != new_voucher_discount_value_type
+ voucher.variants.set([line_2.variant])
+
+ # add 1 unit of line 1 variant
+ extra_quantity = 1
+ new_quantity = line_1.quantity + extra_quantity
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", line_1.variant.id)
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": extra_quantity,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderLinesCreate"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ line_1, line_2 = order.lines.all()
+ new_discount_amount = initial_unit_discount * new_quantity
+
+ discount.refresh_from_db()
+ assert discount.value == initial_discount_value
+ assert discount.value_type == initial_discount_value_type
+ assert discount.amount_value == new_discount_amount
+ assert discount.type == DiscountType.VOUCHER
+ assert discount.reason == f"Voucher code: {order.voucher_code}"
+
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - initial_unit_discount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_net_amount, currency) == quantize_price(
+ line_1.undiscounted_total_price_net_amount - new_discount_amount,
+ currency,
+ )
+ assert quantize_price(line_1.total_price_gross_amount, currency) == quantize_price(
+ line_1.base_unit_price_amount * new_quantity * tax_rate, currency
+ )
+ assert quantize_price(
+ line_1.undiscounted_total_price_gross_amount, currency
+ ) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate,
+ currency,
+ )
+ assert line_1.unit_discount_amount == initial_unit_discount
+ assert line_1.unit_discount_type == initial_discount_value_type
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+ assert line_1.unit_discount_value == initial_discount_value
+
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+ assert (
+ line_2.total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert (
+ line_2.undiscounted_total_price_gross_amount
+ == line_2.undiscounted_base_unit_price_amount * line_2.quantity * tax_rate
+ )
+ assert line_2.unit_discount_amount == 0
+ assert line_2.unit_discount_type is None
+ assert line_2.unit_discount_reason is None
+ assert line_2.unit_discount_value == 0
+
+ assert order.undiscounted_base_shipping_price == undiscounted_shipping_price
+ assert order.base_shipping_price == undiscounted_shipping_price
+ assert order.shipping_price_net == undiscounted_shipping_price
+ assert order.shipping_price_gross == quantize_price(
+ undiscounted_shipping_price * tax_rate, currency
+ )
+
+ undiscounted_subtotal += line_1.undiscounted_unit_price.net
+ assert (
+ order.undiscounted_total_net
+ == undiscounted_subtotal + undiscounted_shipping_price
+ )
+ assert (
+ order.undiscounted_total_gross
+ == (undiscounted_subtotal + undiscounted_shipping_price) * tax_rate
+ )
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal.amount - new_discount_amount
+ )
+ assert quantize_price(order.subtotal_gross_amount, currency) == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert (
+ order.total_net_amount
+ == order.subtotal_net_amount + order.base_shipping_price_amount
+ )
+ assert quantize_price(order.total_gross_amount, currency) == quantize_price(
+ (order.undiscounted_total_net_amount - new_discount_amount) * tax_rate,
+ currency,
+ )
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_lines_create_set_price_expiration_time(
+ order_with_lines,
+ variant_with_many_stocks,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ variant = variant_with_many_stocks
+ quantity = 1
+ 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)
+
+ expire_period = order.channel.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+ expected_expire_time = timezone.now() + timedelta(hours=expire_period)
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ new_line = OrderLine.objects.get(variant_id=variant.id)
+ assert new_line.draft_base_price_expire_at == expected_expire_time
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_lines_create_dont_set_price_expiration_time_when_period_is_none(
+ order_with_lines,
+ variant_with_many_stocks,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ variant = variant_with_many_stocks
+ quantity = 1
+ 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)
+
+ # change default draft_order_line_price_freeze_period setting to None
+ channel = order.channel
+ channel.draft_order_line_price_freeze_period = None
+ channel.save(update_fields=["draft_order_line_price_freeze_period"])
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ new_line = OrderLine.objects.get(variant_id=variant.id)
+ assert new_line.draft_base_price_expire_at is None
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_lines_create_dont_set_price_expiration_time_when_price_overridden(
+ order_with_lines,
+ variant_with_many_stocks,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ variant = variant_with_many_stocks
+ quantity = 1
+ custom_price = Decimal("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,
+ "price": custom_price,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ expire_period = order.channel.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ new_line = OrderLine.objects.get(variant_id=variant.id)
+ assert new_line.is_price_overridden is True
+ assert new_line.draft_base_price_expire_at is None
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_lines_create_with_existing_variant_dont_set_expiration_date(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ line = order.lines.first()
+ variant = line.variant
+ old_quantity = line.quantity
+ extra_quantity = 1
+ 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": extra_quantity,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ expire_period = order.channel.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+
+ initial_expire_date = timezone.now() + timedelta(hours=expire_period - 1)
+ line.draft_base_price_expire_at = initial_expire_date
+ line.save(update_fields=["draft_base_price_expire_at"])
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ line.refresh_from_db()
+ assert line.quantity == old_quantity + extra_quantity
+ assert line.draft_base_price_expire_at == initial_expire_date
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_order_lines_create_existing_variant_and_custom_price_unset_expiration_date(
+ order_with_lines,
+ permission_group_manage_orders,
+ staff_api_client,
+):
+ # given
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ line = order.lines.first()
+ variant = line.variant
+ old_quantity = line.quantity
+ extra_quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ custom_price = Decimal("5")
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": extra_quantity,
+ "price": custom_price,
+ }
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ expire_period = order.channel.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+
+ initial_expire_date = timezone.now() + timedelta(hours=expire_period - 1)
+ line.draft_base_price_expire_at = initial_expire_date
+ line.save(update_fields=["draft_base_price_expire_at"])
+
+ # when
+ staff_api_client.post_graphql(query, variables)
+
+ # then
+ line.refresh_from_db()
+ assert line.quantity == old_quantity + extra_quantity
+ assert line.draft_base_price_expire_at is None
diff --git a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
index a64f4e485f..f71c02dbd0 100644
--- a/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
+++ b/saleor/graphql/order/tests/mutations/test_order_update_shipping.py
@@ -4,12 +4,16 @@ from unittest.mock import patch
import graphene
import pytest
from django.test import override_settings
-from prices import TaxedMoney
+from prices import Money, TaxedMoney
from .....core.models import EventDelivery
from .....core.taxes import zero_money, zero_taxed_money
+from .....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from .....order import OrderStatus
from .....order.actions import call_order_event
+from .....order.calculations import fetch_order_prices_if_expired
from .....order.error_codes import OrderErrorCode
from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -476,6 +480,81 @@ def test_draft_order_clear_shipping_method(
assert draft_order.shipping_method_name is None
+def test_order_update_shipping_with_voucher_discount(
+ staff_api_client,
+ permission_group_manage_orders,
+ order_with_lines,
+ shipping_method,
+ voucher_free_shipping,
+ plugins_manager,
+):
+ # given
+ voucher = voucher_free_shipping
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+ order = order_with_lines
+ currency = order.currency
+ order.status = OrderStatus.DRAFT
+ assert order.shipping_method != shipping_method
+
+ new_undiscounted_shipping_price = Money(Decimal("16"), currency)
+ assert new_undiscounted_shipping_price > order.undiscounted_base_shipping_price
+ new_shipping_listing = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ )
+ new_shipping_listing.price = new_undiscounted_shipping_price
+ new_shipping_listing.save(update_fields=["price_amount"])
+
+ # apply shipping voucher
+ initial_voucher_reward = Decimal(50)
+ voucher_listing = voucher.channel_listings.get()
+ voucher_listing.discount_value = initial_voucher_reward
+ voucher_listing.save(update_fields=["discount_value"])
+ order.voucher = voucher
+ order.save()
+ create_or_update_voucher_discount_objects_for_order(order)
+ order, lines = fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ discount = order.discounts.get()
+ initial_discount_amount = (
+ order.undiscounted_base_shipping_price * initial_voucher_reward / 100
+ )
+ assert discount.amount == initial_discount_amount
+
+ # update voucher listing value
+ new_voucher_reward = Decimal(30)
+ voucher_listing.discount_value = new_voucher_reward
+ voucher_listing.save(update_fields=["discount_value"])
+
+ query = ORDER_UPDATE_SHIPPING_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ method_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {"order": order_id, "shippingMethod": method_id}
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["orderUpdateShipping"]
+ assert not data["errors"]
+
+ order.refresh_from_db()
+ new_shipping_discount_amount = Money(
+ new_undiscounted_shipping_price.amount * initial_voucher_reward / 100, currency
+ )
+ assert order.undiscounted_base_shipping_price == new_undiscounted_shipping_price
+ assert (
+ order.base_shipping_price
+ == new_undiscounted_shipping_price - new_shipping_discount_amount
+ )
+ assert order.shipping_method == shipping_method
+ assert order.shipping_price_net == order.base_shipping_price
+
+ discount.refresh_from_db()
+ assert discount.amount == new_shipping_discount_amount
+ assert discount.value == initial_voucher_reward
+
+
ORDER_UPDATE_SHIPPING_QUERY_WITH_TOTAL = """
mutation OrderUpdateShipping(
$orderId: ID!
diff --git a/saleor/graphql/order/tests/queries/test_draft_order.py b/saleor/graphql/order/tests/queries/test_draft_order.py
index e9f7de68e5..8df39e92f4 100644
--- a/saleor/graphql/order/tests/queries/test_draft_order.py
+++ b/saleor/graphql/order/tests/queries/test_draft_order.py
@@ -167,11 +167,11 @@ def test_query_orders_when_flat_rates_active(
mocked_update_order_prices_with_flat_rates.assert_called_once()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_lines_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -198,14 +198,14 @@ def test_query_orders_for_order_with_lines_when_tax_app_active(
assert order_with_lines.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_granted_refunds_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -246,14 +246,14 @@ def test_query_orders_for_order_with_granted_refunds_when_tax_app_active(
assert order.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_fulfillments_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -284,14 +284,14 @@ def test_query_orders_for_order_with_fulfillments_when_tax_app_active(
assert order.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_events_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -339,7 +339,7 @@ def test_query_orders_for_order_with_events_when_tax_app_active(
assert order.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
@patch.object(PluginsManager, "excluded_shipping_methods_for_order")
diff --git a/saleor/graphql/order/tests/queries/test_orders.py b/saleor/graphql/order/tests/queries/test_orders.py
index 55fa6c7cee..4664e84bc4 100644
--- a/saleor/graphql/order/tests/queries/test_orders.py
+++ b/saleor/graphql/order/tests/queries/test_orders.py
@@ -58,11 +58,11 @@ def test_query_orders_when_flat_rates_active(
mocked_update_order_prices_with_flat_rates.assert_called_once()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_lines_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -87,14 +87,14 @@ def test_query_orders_for_order_with_lines_when_tax_app_active(
assert order_with_lines.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_granted_refunds_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -133,14 +133,14 @@ def test_query_orders_for_order_with_granted_refunds_when_tax_app_active(
assert order.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_fulfillments_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -169,14 +169,14 @@ def test_query_orders_for_order_with_fulfillments_when_tax_app_active(
assert order.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
-@patch("saleor.order.calculations._recalculate_prices")
+@patch("saleor.order.calculations.calculate_prices")
@patch("saleor.order.calculations.update_order_prices_with_flat_rates")
def test_query_orders_for_order_with_events_when_tax_app_active(
mocked_update_order_prices_with_flat_rates,
- mocked__recalculate_prices,
+ mocked_calculate_prices,
order_with_lines,
tax_configuration_tax_app,
staff_api_client,
@@ -222,7 +222,7 @@ def test_query_orders_for_order_with_events_when_tax_app_active(
assert order.total_gross_amount == Decimal(0)
mocked_update_order_prices_with_flat_rates.assert_not_called()
- mocked__recalculate_prices.assert_not_called()
+ mocked_calculate_prices.assert_not_called()
@patch.object(PluginsManager, "excluded_shipping_methods_for_order")
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index b7cd08c2de..459f267656 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5199,6 +5199,15 @@ type OrderSettings {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
includeDraftOrderInVoucherUsage: Boolean!
+
+ """
+ Time in hours after which the draft order line price will be refreshed.
+
+ Added in Saleor 3.21.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ draftOrderLinePriceFreezePeriod: Hour
}
"""
@@ -5223,6 +5232,9 @@ enum MarkAsPaidStrategyEnum @doc(category: "Channels") {
"""The `Day` scalar type represents number of days by integer value."""
scalar Day
+"""The `Hour` scalar type represents number of hours by integer value."""
+scalar Hour
+
"""Represents the channel-specific checkout settings."""
type CheckoutSettings {
"""
@@ -27539,6 +27551,15 @@ input OrderSettingsInput @doc(category: "Orders") {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
includeDraftOrderInVoucherUsage: Boolean
+
+ """
+ Time in hours after which the draft order line price will be refreshed. Default value is 24 hours. Enter 0 or null to disable.
+
+ Added in Saleor 3.21.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ draftOrderLinePriceFreezePeriod: Hour
}
input CheckoutSettingsInput @doc(category: "Checkout") {
diff --git a/saleor/order/base_calculations.py b/saleor/order/base_calculations.py
index 9a408acad1..ade164f89e 100644
--- a/saleor/order/base_calculations.py
+++ b/saleor/order/base_calculations.py
@@ -50,7 +50,7 @@ def base_order_total(
All discounts are included in this price.
"""
- subtotal, shipping_price = apply_order_discounts(
+ subtotal, shipping_price = calculate_prices(
order,
lines,
assign_prices=False,
@@ -168,7 +168,7 @@ def propagate_order_discount_on_order_prices(
return subtotal, shipping_price
-def apply_order_discounts(
+def calculate_prices(
order: "Order",
lines: Iterable["OrderLine"],
assign_prices=True,
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index b9ea10b939..d8495431e1 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -1,10 +1,11 @@
import logging
from collections.abc import Iterable
from decimal import Decimal
+from uuid import UUID
from django.conf import settings
from django.db import transaction
-from django.db.models import prefetch_related_objects
+from django.utils import timezone
from prices import Money, TaxedMoney
from ..core.db.connection import allow_writer
@@ -16,7 +17,16 @@ from ..core.taxes import (
TaxError,
zero_taxed_money,
)
-from ..discount.utils.order import create_or_update_discount_objects_for_order
+from ..discount.utils.order import (
+ handle_order_promotion,
+ refresh_manual_line_discount_object,
+ refresh_order_line_discount_objects_for_catalogue_promotions,
+ update_unit_discount_data_on_order_line,
+)
+from ..discount.utils.voucher import (
+ create_or_update_line_discount_objects_from_voucher,
+ get_the_cheapest_line,
+)
from ..payment.model_helpers import get_subtotal
from ..plugins import PLUGIN_IDENTIFIER_PREFIX
from ..plugins.manager import PluginsManager
@@ -30,12 +40,20 @@ from ..tax.utils import (
normalize_tax_rate_for_db,
validate_tax_data,
)
-from . import ORDER_EDITABLE_STATUS
-from .base_calculations import apply_order_discounts, base_order_line_total
-from .fetch import EditableOrderLineInfo, fetch_draft_order_lines_info
+from . import ORDER_EDITABLE_STATUS, OrderStatus
+from .base_calculations import base_order_line_total, calculate_prices
+from .fetch import (
+ EditableOrderLineInfo,
+ fetch_draft_order_lines_info,
+ reattach_apply_once_per_order_voucher_info,
+)
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
-from .utils import log_address_if_validation_skipped_for_order, order_info_for_logs
+from .utils import (
+ calculate_draft_order_line_price_expiration_date,
+ log_address_if_validation_skipped_for_order,
+ order_info_for_logs,
+)
logger = logging.getLogger(__name__)
@@ -58,27 +76,37 @@ def fetch_order_prices_if_expired(
if order.status not in ORDER_EDITABLE_STATUS:
return order, lines
- if not force_update and not order.should_refresh_prices:
+ expired_line_ids = get_expired_line_ids(order, lines)
+ if not force_update and not order.should_refresh_prices and not expired_line_ids:
return order, lines
tax_strategy = get_tax_calculation_strategy_for_order(order)
if tax_strategy == TaxCalculationStrategy.TAX_APP and not allow_sync_webhooks:
return order, lines
- # handle promotions
- lines_info: list[EditableOrderLineInfo] = fetch_draft_order_lines_info(order, lines)
- create_or_update_discount_objects_for_order(
- order, lines_info, database_connection_name
- )
- lines = [line_info.line for line_info in lines_info]
+ if expired_line_ids:
+ # handle line base price expiration
+ lines_info = refresh_order_base_prices_and_discounts(
+ order, expired_line_ids, lines
+ )
+ else:
+ lines_info = fetch_draft_order_lines_info(order, lines)
+
+ # order promotion is qualified based on the most actual prices, therefor need to be assessed
+ # on the every recalculation
+ handle_order_promotion(order, lines_info, database_connection_name)
- _clear_prefetched_discounts(order, lines)
- with allow_writer():
- # TODO: Load discounts with a dataloader and pass as argument
- prefetch_related_objects([order], "discounts")
+ # update `OrderLine.unit_discount_...` fields
+ update_unit_discount_data_on_order_line(lines_info)
+
+ lines = [line_info.line for line_info in lines_info]
+ calculate_prices(
+ order,
+ lines,
+ database_connection_name=database_connection_name,
+ )
- # handle taxes
- _recalculate_prices(
+ calculate_taxes(
order,
manager,
lines,
@@ -128,23 +156,27 @@ def fetch_order_prices_if_expired(
return order, lines
-def _clear_prefetched_discounts(order, lines):
- if hasattr(order, "_prefetched_objects_cache"):
- order._prefetched_objects_cache.pop("discounts", None)
+def get_expired_line_ids(order: Order, lines: Iterable[OrderLine] | None) -> list[UUID]:
+ if order.status != OrderStatus.DRAFT:
+ return []
- for line in lines:
- if hasattr(line, "_prefetched_objects_cache"):
- line._prefetched_objects_cache.pop("discounts", None)
+ if lines is None:
+ lines = order.lines.all()
+ now = timezone.now()
+ return [
+ line.pk
+ for line in lines
+ if line.draft_base_price_expire_at and line.draft_base_price_expire_at < now
+ ]
-def _recalculate_prices(
+def calculate_taxes(
order: Order,
manager: PluginsManager,
lines: Iterable[OrderLine],
tax_calculation_strategy: str,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- """Calculate prices after handling order level discounts and taxes."""
tax_configuration = order.channel.tax_configuration
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
charge_taxes = get_charge_taxes_for_order(order)
@@ -152,12 +184,6 @@ def _recalculate_prices(
tax_app_identifier = get_tax_app_identifier_for_order(order)
order.tax_error = None
-
- apply_order_discounts(
- order,
- lines,
- database_connection_name=database_connection_name,
- )
if prices_entered_with_tax:
# If prices are entered with tax, we need to always calculate it anyway, to
# display the tax rate to the user.
@@ -492,6 +518,99 @@ def _find_order_line(
)
+def refresh_order_base_prices_and_discounts(
+ order: "Order",
+ line_ids_to_refresh: Iterable[UUID],
+ lines: Iterable[OrderLine] | None = None,
+) -> list[EditableOrderLineInfo]:
+ """Force order to fetch the latest channel listing prices and update discounts."""
+ if order.status != OrderStatus.DRAFT:
+ return []
+
+ lines_info = fetch_draft_order_lines_info(
+ order, lines=lines, fetch_actual_prices=True
+ )
+ if not lines_info:
+ return []
+
+ lines_info_to_update = [
+ line_info
+ for line_info in lines_info
+ if line_info.line.id in line_ids_to_refresh
+ ]
+
+ initial_cheapest_line = get_the_cheapest_line(lines_info)
+
+ # update prices based on the latest channel listing prices
+ _set_channel_listing_prices(lines_info_to_update)
+ # update prices based on the latest catalogue promotions
+ refresh_order_line_discount_objects_for_catalogue_promotions(lines_info_to_update)
+ # update manual line discount object amount based on the new listing prices
+ refresh_manual_line_discount_object(lines_info_to_update)
+
+ # update prices based on the associated voucher
+ is_apply_once_per_order_voucher = (
+ order.voucher and order.voucher.apply_once_per_order
+ )
+ if is_apply_once_per_order_voucher:
+ # voucher of type apply once per order can impact other order line, if the
+ # cheapest line has changed
+ reattach_apply_once_per_order_voucher_info(
+ lines_info, initial_cheapest_line, order
+ )
+ create_or_update_line_discount_objects_from_voucher(lines_info)
+ else:
+ create_or_update_line_discount_objects_from_voucher(lines_info_to_update)
+
+ # update unit discount fields based on updated discounts
+ update_unit_discount_data_on_order_line(lines_info)
+
+ # set price expiration time
+ expiration_time = calculate_draft_order_line_price_expiration_date(
+ order.channel, order.status
+ )
+ for line_info in lines_info_to_update:
+ line_info.line.draft_base_price_expire_at = expiration_time
+
+ lines = [line_info.line for line_info in lines_info]
+ # cleanup after potential outdated prefetched line discounts
+ _clear_prefetched_order_line_discounts(lines)
+ OrderLine.objects.bulk_update(
+ lines,
+ [
+ "unit_discount_amount",
+ "unit_discount_reason",
+ "unit_discount_type",
+ "unit_discount_value",
+ "base_unit_price_amount",
+ "undiscounted_base_unit_price_amount",
+ "draft_base_price_expire_at",
+ ],
+ )
+ return lines_info
+
+
+def _set_channel_listing_prices(lines_info: list[EditableOrderLineInfo]):
+ for line_info in lines_info:
+ line = line_info.line
+ channel_listing = line_info.channel_listing
+ if channel_listing and channel_listing.price_amount:
+ line.undiscounted_base_unit_price_amount = channel_listing.price_amount
+ line.base_unit_price_amount = channel_listing.price_amount
+
+
+def _clear_prefetched_order_line_discounts(lines):
+ for line in lines:
+ if hasattr(line, "_prefetched_objects_cache"):
+ line._prefetched_objects_cache.pop("discounts", None)
+
+
+def refresh_all_order_base_prices_and_discounts(order):
+ lines = order.lines.all()
+ line_ids_to_refresh = [line.id for line in lines]
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh, lines)
+
+
def order_line_unit(
order: Order,
order_line: OrderLine,
diff --git a/saleor/order/fetch.py b/saleor/order/fetch.py
index 60cf1903a2..9b29dfbf1a 100644
--- a/saleor/order/fetch.py
+++ b/saleor/order/fetch.py
@@ -1,7 +1,6 @@
from collections.abc import Iterable
from dataclasses import dataclass
-from functools import cached_property
-from typing import Optional
+from typing import Optional, cast
from uuid import UUID
from django.db.models import prefetch_related_objects
@@ -12,9 +11,17 @@ from ..core.prices import quantize_price
from ..core.pricing.interface import LineInfo
from ..core.taxes import zero_money
from ..discount import DiscountType, VoucherType
-from ..discount.interface import fetch_variant_rules_info, fetch_voucher_info
-from ..discount.models import OrderLineDiscount
-from ..discount.utils.voucher import apply_voucher_to_line
+from ..discount.interface import (
+ VariantPromotionRuleInfo,
+ fetch_variant_rules_info,
+ fetch_voucher_info,
+)
+from ..discount.models import OrderLineDiscount, Voucher
+from ..discount.utils.voucher import (
+ VoucherDenormalizedInfo,
+ attach_voucher_to_line_info,
+ get_the_cheapest_line,
+)
from ..graphql.core.types import Money
from ..payment.models import Payment
from ..product.models import (
@@ -83,19 +90,13 @@ def fetch_order_lines(order: "Order") -> list[OrderLineInfo]:
class EditableOrderLineInfo(LineInfo):
line: "OrderLine"
discounts: list["OrderLineDiscount"]
+ rules_info: list["VariantPromotionRuleInfo"] | None = None
+ channel_listing: ProductVariantChannelListing | None = None
+ voucher_denormalized_info: VoucherDenormalizedInfo | None = None
- @cached_property
+ @property
def variant_discounted_price(self) -> Money:
- """Return the discounted variant price.
-
- If listing is present return the discounted price from the listing.
- if listing is not present, calculate current unit price based on the details
- assigned to the line. We want to show the same prices as they were
- before removing listing.
- """
- if self.channel_listing and self.channel_listing.discounted_price is not None:
- return self.channel_listing.discounted_price
-
+ """Return the variant price discounted by catalogue promotion."""
catalogue_discounts = self.get_catalogue_discounts()
total_price = self.line.undiscounted_base_unit_price * self.line.quantity
for discount in catalogue_discounts:
@@ -115,15 +116,28 @@ class EditableOrderLineInfo(LineInfo):
def fetch_draft_order_lines_info(
- order: "Order", lines: Iterable["OrderLine"] | None = None
+ order: "Order",
+ lines: Iterable["OrderLine"] | None = None,
+ fetch_actual_prices: bool = False,
) -> list[EditableOrderLineInfo]:
+ """Fetch the necessary order lines info in order to recalculate its prices.
+
+ `fetch_actual_prices` argument determines if the function should additionally
+ retrieve the latest variant channel listing prices
+ """
prefetch_related_fields = [
"discounts__promotion_rule__promotion",
- "variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations",
- "variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations",
"variant__product__collections",
"variant__product__product_type",
]
+ if fetch_actual_prices:
+ prefetch_related_fields.extend(
+ [
+ "variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations",
+ "variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations",
+ ]
+ )
+
if lines is None:
with allow_writer():
# TODO: load lines with dataloader and pass as an argument
@@ -142,15 +156,20 @@ def fetch_draft_order_lines_info(
if not variant:
continue
product = variant.product
- 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 []
- )
+ variant_channel_listing = None
+ rules_info = []
+ if fetch_actual_prices:
+ variant_channel_listing = _get_variant_listing(variant, channel.id)
+ if variant_channel_listing:
+ rules_info = (
+ fetch_variant_rules_info(
+ variant_channel_listing, order.language_code
+ )
+ if not line.is_gift
+ else []
+ )
+
lines_info.append(
EditableOrderLineInfo(
line=line,
@@ -158,24 +177,55 @@ def fetch_draft_order_lines_info(
product=product,
product_type=product.product_type,
collections=list(product.collections.all()) if product else [],
- channel_listing=variant_channel_listing,
discounts=list(line.discounts.all()),
- rules_info=rules_info,
channel=channel,
voucher=None,
voucher_code=None,
+ voucher_denormalized_info=None,
+ channel_listing=variant_channel_listing,
+ rules_info=rules_info,
)
)
+
+ attach_voucher_info(lines_info, order)
+
+ return lines_info
+
+
+def attach_voucher_info(lines_info: list[EditableOrderLineInfo], order: Order):
+ """Collect necessary voucher info and attach it to order lines info."""
voucher = order.voucher
if voucher and (
voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order
):
voucher_info = fetch_voucher_info(voucher, order.voucher_code)
- apply_voucher_to_line(voucher_info, lines_info)
- return lines_info
+ attach_voucher_to_line_info(voucher_info, lines_info)
+ denormalized_voucher_info = _fetch_denormalized_voucher_info(
+ lines_info, voucher
+ )
+ _attach_denormalized_voucher_to_line_info(
+ lines_info, denormalized_voucher_info, order.voucher_code
+ )
+
+
+def reattach_apply_once_per_order_voucher_info(
+ lines_info: list[EditableOrderLineInfo],
+ initial_cheapest_line_info: LineInfo | None,
+ order: Order,
+):
+ """Reattach apply once per order voucher info if the cheapest line has changed."""
+ if get_the_cheapest_line(lines_info) == initial_cheapest_line_info:
+ return
+ for line_info in lines_info:
+ line_info.voucher = None
+ line_info.voucher_code = None
+ line_info.voucher_denormalized_info = None
-def get_prefetched_variant_listing(
+ attach_voucher_info(lines_info, order)
+
+
+def _get_variant_listing(
variant: ProductVariant | None, channel_id: int
) -> ProductVariantChannelListing | None:
if not variant:
@@ -184,3 +234,61 @@ def get_prefetched_variant_listing(
if channel_listing.channel_id == channel_id:
return channel_listing
return None
+
+
+def _fetch_denormalized_voucher_info(
+ lines_info: list[EditableOrderLineInfo], voucher: Voucher
+):
+ voucher_discounts = [
+ discount
+ for line_info in lines_info
+ for discount in line_info.discounts
+ if discount.voucher == voucher
+ ]
+ if not voucher_discounts:
+ return None
+
+ voucher_discount = voucher_discounts[0]
+ return VoucherDenormalizedInfo(
+ discount_value=voucher_discount.value,
+ discount_value_type=voucher_discount.value_type,
+ voucher_type=voucher.type,
+ reason=voucher_discount.reason,
+ name=voucher_discount.name,
+ apply_once_per_order=voucher.apply_once_per_order,
+ origin_line_ids=[
+ discount.line_id for discount in voucher_discounts if discount.line_id
+ ],
+ )
+
+
+def _attach_denormalized_voucher_to_line_info(
+ lines_info: list[EditableOrderLineInfo],
+ denormalized_voucher_info: VoucherDenormalizedInfo | None,
+ voucher_code: str | None,
+):
+ if not denormalized_voucher_info:
+ return
+
+ # Denormalized vouchers of type SPECIFIC PRODUCT shouldn't be evaluated against
+ # the latest eligible product catalog so it should be applied to the same lines
+ # it originates from
+ if denormalized_voucher_info.voucher_type == VoucherType.SPECIFIC_PRODUCT:
+ discounted_lines_info = (
+ line_info
+ for line_info in lines_info
+ if line_info.line.pk in denormalized_voucher_info.origin_line_ids
+ )
+ for line_info in discounted_lines_info:
+ line_info.voucher_denormalized_info = denormalized_voucher_info
+ line_info.voucher_code = voucher_code
+ return
+
+ # Denormalized voucher applicable once per order can be applied to the different
+ # line than it originates from (it depends on the actual cheapest line)
+ if denormalized_voucher_info.apply_once_per_order is True:
+ if cheapest_line_info := get_the_cheapest_line(lines_info):
+ cheapest_line_info = cast(EditableOrderLineInfo, cheapest_line_info)
+ cheapest_line_info.voucher_denormalized_info = denormalized_voucher_info
+ cheapest_line_info.voucher_code = voucher_code
+ return
diff --git a/saleor/order/migrations/0198_orderline_draft_base_price_expire_at.py b/saleor/order/migrations/0198_orderline_draft_base_price_expire_at.py
new file mode 100644
index 0000000000..9e07774fb4
--- /dev/null
+++ b/saleor/order/migrations/0198_orderline_draft_base_price_expire_at.py
@@ -0,0 +1,17 @@
+# Generated by Django 4.2.16 on 2025-02-21 15:57
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0197_order_draft_save_billing_address_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="orderline",
+ name="draft_base_price_expire_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/saleor/order/migrations/0199_set_draft_base_price_expire_at.py b/saleor/order/migrations/0199_set_draft_base_price_expire_at.py
new file mode 100644
index 0000000000..44628e75bd
--- /dev/null
+++ b/saleor/order/migrations/0199_set_draft_base_price_expire_at.py
@@ -0,0 +1,28 @@
+# Generated by Django 4.2.16 on 2025-03-05 11:21
+
+from django.apps import apps as registry
+from django.db import migrations
+from django.db.models.signals import post_migrate
+
+from .tasks.saleor3_21 import set_base_price_expire_time_task
+
+
+def set_base_price_expire_time(apps, _schema_editor):
+ def on_migrations_complete(sender=None, **kwargs):
+ set_base_price_expire_time_task.delay()
+
+ sender = registry.get_app_config("order")
+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0198_orderline_draft_base_price_expire_at"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ set_base_price_expire_time,
+ reverse_code=migrations.RunPython.noop,
+ )
+ ]
diff --git a/saleor/order/migrations/tasks/saleor3_21.py b/saleor/order/migrations/tasks/saleor3_21.py
new file mode 100644
index 0000000000..78aa79f4ab
--- /dev/null
+++ b/saleor/order/migrations/tasks/saleor3_21.py
@@ -0,0 +1,34 @@
+from datetime import timedelta
+
+from django.db import transaction
+from django.db.models import Exists, OuterRef
+from django.utils import timezone
+
+from ....celeryconf import app
+from ....core.db.connection import allow_writer
+from ...models import Order, OrderLine
+
+# The batch of size 250 takes ~0.2 second and consumes ~20MB memory at peak
+BATCH_SIZE = 250
+DEFAULT_EXPIRE_TIME = 24
+
+
+@allow_writer()
+def set_base_price_expire_time_task():
+ orders = Order.objects.filter(status="draft")
+ qs = (
+ OrderLine.objects.filter(Exists(orders.filter(pk=OuterRef("order_id"))))
+ .filter(draft_base_price_expire_at__isnull=True)
+ .order_by("pk")
+ )
+ line_ids = qs.values_list("pk", flat=True)[:BATCH_SIZE]
+ if line_ids:
+ order_lines = OrderLine.objects.filter(id__in=line_ids).order_by("pk")
+ now = timezone.now()
+ expire_time = now + timedelta(hours=DEFAULT_EXPIRE_TIME)
+ with transaction.atomic():
+ _order_lines_lock = list(order_lines.select_for_update(of=(["self"])))
+ order_lines.update(draft_base_price_expire_at=expire_time)
+
+ set_base_price_expire_time_task.delay()
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 3aad6cc4cc..de07ff333e 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -719,6 +719,10 @@ class OrderLine(ModelWithMetadata):
# Fulfilled when sale was applied to product in the line
sale_id = models.CharField(max_length=255, null=True, blank=True)
+ # The date time when the line should refresh its prices.
+ # It depends on channel.draft_order_line_price_freeze_period setting.
+ draft_base_price_expire_at = models.DateTimeField(blank=True, null=True)
+
objects = OrderLineManager()
class Meta(ModelWithMetadata.Meta):
diff --git a/saleor/order/tests/benchmark/test_fetch_order_prices.py b/saleor/order/tests/benchmark/test_fetch_order_prices.py
index dcb51f1d98..e980a630cd 100644
--- a/saleor/order/tests/benchmark/test_fetch_order_prices.py
+++ b/saleor/order/tests/benchmark/test_fetch_order_prices.py
@@ -1,144 +1,22 @@
-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
@pytest.mark.django_db
@pytest.mark.count_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(44):
- 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(
+def test_fetch_order_prices(
order_with_lines,
- catalogue_promotion_without_rules,
plugins_manager,
- product_variant_list,
django_assert_num_queries,
+ tax_configuration_flat_rates,
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)
+ order.status = OrderStatus.UNCONFIRMED
- 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(44):
+ # when & then
+ with django_assert_num_queries(32):
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/fixtures/draft_order.py b/saleor/order/tests/fixtures/draft_order.py
index 6f3a3c3ef4..809b1f28f7 100644
--- a/saleor/order/tests/fixtures/draft_order.py
+++ b/saleor/order/tests/fixtures/draft_order.py
@@ -6,9 +6,14 @@ import pytest
from django.conf import settings
from prices import Money, TaxedMoney, fixed_discount
+from ....core.prices import quantize_price
from ....core.taxes import zero_money
from ....discount import DiscountType, DiscountValueType, RewardType, RewardValueType
+from ....discount.interface import fetch_variant_rules_info
from ....discount.models import VoucherCode
+from ....discount.utils.order import (
+ create_order_line_discount_objects_for_catalogue_promotions,
+)
from ....discount.utils.voucher import (
create_or_update_discount_object_from_order_level_voucher,
)
@@ -179,6 +184,7 @@ def draft_order_and_promotions(
catalogue_promotion = catalogue_promotion_without_rules
variant_1 = line_1.variant
variant_2 = line_2.variant
+ catalogue_reward = Decimal(3)
rule_catalogue = catalogue_promotion.rules.create(
name="Catalogue rule fixed",
catalogue_predicate={
@@ -187,7 +193,7 @@ def draft_order_and_promotions(
}
},
reward_value_type=RewardValueType.FIXED,
- reward_value=Decimal(3),
+ reward_value=catalogue_reward,
)
rule_catalogue.channels.add(channel_USD)
@@ -199,10 +205,31 @@ def draft_order_and_promotions(
VariantChannelListingPromotionRule.objects.create(
variant_channel_listing=listing,
promotion_rule=rule_catalogue,
- discount_amount=Decimal(3),
+ discount_amount=catalogue_reward,
currency=currency,
)
+ # create catalogue discount
+ rules_info = fetch_variant_rules_info(listing, "en")
+ create_order_line_discount_objects_for_catalogue_promotions(
+ line_2, rules_info, channel_USD
+ )
+
+ # update base price with catalogue promotion
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - catalogue_reward
+ )
+ total = quantize_price(line_2.base_unit_price_amount * line_2.quantity, currency)
+ line_2.total_price_net_amount = total
+ line_2.total_price_gross_amount = quantize_price(total * Decimal("1.23"), currency)
+ line_2.save(
+ update_fields=[
+ "base_unit_price_amount",
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ ]
+ )
+
# prepare order promotion - subtotal
order_promotion = order_promotion_without_rules
rule_total = order_promotion.rules.create(
diff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.py
index b489bed773..dd0f52a00e 100644
--- a/saleor/order/tests/fixtures/order.py
+++ b/saleor/order/tests/fixtures/order.py
@@ -10,6 +10,7 @@ from prices import Money, TaxedMoney
from ....checkout.utils import get_prices_of_discounted_specific_product
from ....core import JobStatus
+from ....core.prices import quantize_price
from ....core.taxes import zero_money
from ....discount import DiscountType, RewardType, RewardValueType, VoucherType
from ....discount.models import NotApplicable, Voucher
@@ -517,6 +518,7 @@ def order_with_lines_and_catalogue_promotion(
order_with_lines, channel_USD, catalogue_promotion_without_rules
):
order = order_with_lines
+ currency = order.currency
promotion = catalogue_promotion_without_rules
line = order.lines.get(quantity=3)
variant = line.variant
@@ -525,7 +527,7 @@ def order_with_lines_and_catalogue_promotion(
name="Catalogue rule fixed",
catalogue_predicate={
"variantPredicate": {
- "ids": [graphene.Node.to_global_id("ProductVariant", variant)]
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant.id)]
}
},
reward_value_type=RewardValueType.FIXED,
@@ -539,7 +541,7 @@ def order_with_lines_and_catalogue_promotion(
listing.variantlistingpromotionrule.create(
promotion_rule=rule,
discount_amount=reward_value,
- currency=order.currency,
+ currency=currency,
)
line.discounts.create(
@@ -547,8 +549,23 @@ def order_with_lines_and_catalogue_promotion(
value_type=RewardValueType.FIXED,
value=reward_value,
amount_value=reward_value * line.quantity,
- currency=order.currency,
+ currency=currency,
promotion_rule=rule,
+ reason=f"Promotion: {graphene.Node.to_global_id('Promotion', promotion.id)}",
+ )
+
+ line.base_unit_price_amount = (
+ line.undiscounted_base_unit_price_amount - reward_value
+ )
+ total = quantize_price(line.base_unit_price_amount * line.quantity, currency)
+ line.total_price_net_amount = total
+ line.total_price_gross_amount = quantize_price(total * Decimal("1.23"), currency)
+ line.save(
+ update_fields=[
+ "base_unit_price_amount",
+ "total_price_net_amount",
+ "total_price_gross_amount",
+ ]
)
return order
diff --git a/saleor/order/tests/fixtures/order_line.py b/saleor/order/tests/fixtures/order_line.py
index b3a95b3a1e..96e58a3906 100644
--- a/saleor/order/tests/fixtures/order_line.py
+++ b/saleor/order/tests/fixtures/order_line.py
@@ -3,6 +3,7 @@ from decimal import Decimal
import pytest
from prices import Money, TaxedMoney
+from ....discount import DiscountType
from ....warehouse.models import Allocation, Stock
from ... import OrderOrigin
from ...fetch import OrderLineInfo
@@ -46,6 +47,9 @@ def order_line_on_promotion(order_line, catalogue_promotion):
channel = order_line.order.channel
reward_value = Decimal("1.0")
rule = catalogue_promotion.rules.first()
+ rule.reward_value = reward_value
+ rule.save(update_fields=["reward_value"])
+
variant_channel_listing = variant.channel_listings.get(channel=channel)
variant_channel_listing.discounted_price_amount = (
@@ -85,6 +89,18 @@ def order_line_on_promotion(order_line, catalogue_promotion):
order_line.unit_discount_amount = reward_value
order_line.save()
+
+ order_line.discounts.create(
+ type=DiscountType.PROMOTION,
+ promotion_rule=rule,
+ value_type=rule.reward_value_type,
+ value=reward_value,
+ amount_value=reward_value * order_line.quantity,
+ currency=channel.currency_code,
+ reason="Catalogue promotion reason",
+ unique_type=DiscountType.PROMOTION,
+ )
+
return order_line
diff --git a/saleor/order/tests/test_apply_order_discount.py b/saleor/order/tests/test_calculate_prices.py
similarity index 91%
rename from saleor/order/tests/test_apply_order_discount.py
rename to saleor/order/tests/test_calculate_prices.py
index 03d8315a60..ad18133e80 100644
--- a/saleor/order/tests/test_apply_order_discount.py
+++ b/saleor/order/tests/test_calculate_prices.py
@@ -7,13 +7,13 @@ from ...core.prices import quantize_price
from ...core.taxes import zero_money
from ...discount import DiscountType, DiscountValueType
from ...order.base_calculations import (
- apply_order_discounts,
apply_subtotal_discount_to_order_lines,
+ calculate_prices,
)
from ..models import OrderLine
-def test_apply_order_discounts_voucher_entire_order(order_with_lines, voucher):
+def test_calculate_prices_voucher_entire_order(order_with_lines, voucher):
# given
order = order_with_lines
lines = order.lines.all()
@@ -36,7 +36,7 @@ def test_apply_order_discounts_voucher_entire_order(order_with_lines, voucher):
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == shipping_price
@@ -53,7 +53,7 @@ def test_apply_order_discounts_voucher_entire_order(order_with_lines, voucher):
assert order_discount.amount_value == discount_amount
-def test_apply_order_discounts_voucher_entire_order_exceed_subtotal(
+def test_calculate_prices_voucher_entire_order_exceed_subtotal(
order_with_lines, voucher
):
# given
@@ -80,7 +80,7 @@ def test_apply_order_discounts_voucher_entire_order_exceed_subtotal(
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == shipping_price
@@ -95,7 +95,7 @@ def test_apply_order_discounts_voucher_entire_order_exceed_subtotal(
assert order_discount.amount_value == subtotal.amount
-def test_apply_order_discounts_voucher_entire_order_percentage(
+def test_calculate_prices_voucher_entire_order_percentage(
order_with_lines, voucher_percentage
):
# given
@@ -120,7 +120,7 @@ def test_apply_order_discounts_voucher_entire_order_percentage(
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == shipping_price
@@ -135,7 +135,7 @@ def test_apply_order_discounts_voucher_entire_order_percentage(
assert order_discount.amount_value == quantize_price(subtotal.amount / 2, currency)
-def test_apply_order_discounts_manual_discount(order_with_lines):
+def test_calculate_prices_manual_discount(order_with_lines):
# given
order = order_with_lines
lines = order.lines.all()
@@ -160,7 +160,7 @@ def test_apply_order_discounts_manual_discount(order_with_lines):
subtotal_share = 1 - shipping_share
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == shipping_price - shipping_share * Money(
@@ -179,9 +179,7 @@ def test_apply_order_discounts_manual_discount(order_with_lines):
assert order_discount.amount_value == discount_amount
-def test_apply_order_discounts_shipping_voucher(
- order_with_lines, voucher_free_shipping
-):
+def test_calculate_prices_shipping_voucher(order_with_lines, voucher_free_shipping):
# given
order = order_with_lines
lines = order.lines.all()
@@ -204,14 +202,14 @@ def test_apply_order_discounts_shipping_voucher(
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == shipping_price
assert discounted_subtotal == subtotal
-def test_apply_order_discounts_zero_discount(order_with_lines):
+def test_calculate_prices_zero_discount(order_with_lines):
# given
order = order_with_lines
lines = order.lines.all()
@@ -232,13 +230,13 @@ def test_apply_order_discounts_zero_discount(order_with_lines):
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_subtotal + discounted_shipping_price == undiscounted_total
-def test_apply_order_discounts_subtotal_zero(order_with_lines):
+def test_calculate_prices_subtotal_zero(order_with_lines):
# given
order = order_with_lines
lines = order.lines.all()
@@ -257,13 +255,13 @@ def test_apply_order_discounts_subtotal_zero(order_with_lines):
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_subtotal + discounted_shipping_price == zero_money(currency)
-def test_apply_order_discounts_manual_discount_no_lines(order):
+def test_calculate_prices_manual_discount_no_lines(order):
# given
lines = order.lines.all()
assert not lines
@@ -279,13 +277,13 @@ def test_apply_order_discounts_manual_discount_no_lines(order):
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_subtotal + discounted_shipping_price == zero_money(currency)
-def test_apply_order_discounts_manual_discount_exceed_total(order_with_lines):
+def test_calculate_prices_manual_discount_exceed_total(order_with_lines):
# given
order = order_with_lines
lines = order.lines.all()
@@ -309,7 +307,7 @@ def test_apply_order_discounts_manual_discount_exceed_total(order_with_lines):
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == zero_money(currency)
@@ -324,7 +322,7 @@ def test_apply_order_discounts_manual_discount_exceed_total(order_with_lines):
assert order_discount.amount_value == undiscounted_total.amount
-def test_apply_order_discounts_manual_discount_percentage(order_with_lines):
+def test_calculate_prices_manual_discount_percentage(order_with_lines):
# given
order = order_with_lines
lines = order.lines.all()
@@ -347,7 +345,7 @@ def test_apply_order_discounts_manual_discount_percentage(order_with_lines):
)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
discounted_total = discounted_subtotal + discounted_shipping_price
@@ -363,7 +361,7 @@ def test_apply_order_discounts_manual_discount_percentage(order_with_lines):
assert order_discount.amount_value == discount_amount
-def test_apply_order_discounts_voucher_entire_order_and_manual_discount_fixed(
+def test_calculate_prices_voucher_entire_order_and_manual_discount_fixed(
order_with_lines, voucher
):
# given
@@ -410,7 +408,7 @@ def test_apply_order_discounts_voucher_entire_order_and_manual_discount_fixed(
expected_shipping -= Money(shipping_discount, currency)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == expected_shipping
@@ -432,7 +430,7 @@ def test_apply_order_discounts_voucher_entire_order_and_manual_discount_fixed(
assert manual_order_discount.amount_value == manual_discount_amount
-def test_apply_order_discounts_manual_discount_fixed_and_voucher_entire_order(
+def test_calculate_prices_manual_discount_fixed_and_voucher_entire_order(
order_with_lines, voucher
):
# given
@@ -479,7 +477,7 @@ def test_apply_order_discounts_manual_discount_fixed_and_voucher_entire_order(
expected_subtotal -= Money(voucher_discount_amount, currency)
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == expected_shipping
@@ -496,7 +494,7 @@ def test_apply_order_discounts_manual_discount_fixed_and_voucher_entire_order(
assert manual_order_discount.amount_value == manual_discount_amount
-def test_apply_order_discounts_voucher_entire_order_and_manual_discount_percentage(
+def test_calculate_prices_voucher_entire_order_and_manual_discount_percentage(
order_with_lines,
voucher_percentage,
):
@@ -545,7 +543,7 @@ def test_apply_order_discounts_voucher_entire_order_and_manual_discount_percenta
manual_discount = manual_discount_subtotal + manual_discount_shipping
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == expected_shipping
@@ -562,7 +560,7 @@ def test_apply_order_discounts_voucher_entire_order_and_manual_discount_percenta
assert manual_order_discount.amount_value == manual_discount.amount
-def test_apply_order_discounts_manual_discount_percentage_and_voucher_entire_order(
+def test_calculate_prices_manual_discount_percentage_and_voucher_entire_order(
order_with_lines,
voucher_percentage,
):
@@ -611,7 +609,7 @@ def test_apply_order_discounts_manual_discount_percentage_and_voucher_entire_ord
expected_subtotal -= voucher_discount
# when
- discounted_subtotal, discounted_shipping_price = apply_order_discounts(order, lines)
+ discounted_subtotal, discounted_shipping_price = calculate_prices(order, lines)
# then
assert discounted_shipping_price == expected_shipping
diff --git a/saleor/order/tests/test_calculations.py b/saleor/order/tests/test_calculations.py
index 4ca255485e..e0a86faea6 100644
--- a/saleor/order/tests/test_calculations.py
+++ b/saleor/order/tests/test_calculations.py
@@ -628,7 +628,7 @@ def test_recalculate_with_plugin_prices_entered_with_taxes(
assert tax_rate == line.tax_rate
-def test_recalculate_prices_total_shipping_price_changed(
+def test_calculate_prices_total_shipping_price_changed(
draft_order, order_lines, shipping_method_weight_based
):
"""Test that discounts are properly updated when shipping price changes."""
@@ -666,15 +666,9 @@ def test_recalculate_prices_total_shipping_price_changed(
"shipping_method_name",
]
)
- tax_calculation_strategy = get_tax_calculation_strategy_for_order(order)
# when
- calculations._recalculate_prices(
- order,
- get_plugins_manager(allow_replica=True),
- order_lines,
- tax_calculation_strategy=tax_calculation_strategy,
- )
+ calculations.calculate_prices(order, order_lines)
# then
order_discount.refresh_from_db()
@@ -684,7 +678,7 @@ def test_recalculate_prices_total_shipping_price_changed(
assert order_discount.amount == order.undiscounted_total.net
-def test_recalculate_prices_line_quantity_changed(
+def test_calculate_prices_line_quantity_changed(
draft_order, order_lines, shipping_method_weight_based
):
"""Test that discounts are properly updated when line quantities change."""
@@ -704,15 +698,9 @@ def test_recalculate_prices_line_quantity_changed(
line = order_lines.first()
line.quantity += 1
line.save(update_fields=["quantity"])
- tax_calculation_strategy = get_tax_calculation_strategy_for_order(order)
# when
- calculations._recalculate_prices(
- order,
- get_plugins_manager(allow_replica=True),
- order_lines,
- tax_calculation_strategy=tax_calculation_strategy,
- )
+ calculations.calculate_prices(order, order_lines)
# then
order_discount.refresh_from_db()
@@ -1580,7 +1568,7 @@ def test_fetch_order_data_calls_inactive_plugin(
@pytest.mark.parametrize("tax_app_id", [None, "test.app"])
-def test_recalculate_prices_empty_tax_data_logging_address(
+def test_calculate_taxes_empty_tax_data_logging_address(
tax_app_id, draft_order, order_lines, address, caplog
):
# given
@@ -1614,9 +1602,7 @@ def test_recalculate_prices_empty_tax_data_logging_address(
tax_calculation_strategy = get_tax_calculation_strategy_for_order(order)
# when
- calculations._recalculate_prices(
- order, manager, order_lines, tax_calculation_strategy=tax_calculation_strategy
- )
+ calculations.calculate_taxes(order, manager, order_lines, tax_calculation_strategy)
# then
assert (
diff --git a/saleor/order/tests/test_fetch.py b/saleor/order/tests/test_fetch.py
index 889bb1dba3..bfb1b8cf99 100644
--- a/saleor/order/tests/test_fetch.py
+++ b/saleor/order/tests/test_fetch.py
@@ -17,6 +17,7 @@ def test_fetch_draft_order_lines_info(
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]
+ catalogue_discount = line_2.discounts.get()
manual_discount = line_1.discounts.create(
value=Decimal(1),
@@ -34,13 +35,61 @@ def test_fetch_draft_order_lines_info(
)
# when
- with django_assert_num_queries(12):
+ with django_assert_num_queries(8):
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.discounts == [manual_discount]
+ assert line_info_1.channel == channel
+ assert line_info_1.voucher is None
+
+ variant_2 = line_2.variant
+ assert line_info_2.variant == variant_2
+ assert line_info_2.discounts == [catalogue_discount]
+ assert line_info_2.channel == channel
+ assert line_info_2.voucher is None
+
+
[email protected]_queries(autouse=False)
+def test_fetch_draft_order_lines_info_extended(
+ 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(14):
+ lines_info = fetch_draft_order_lines_info(order, fetch_actual_prices=True)
+
+ # 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 (
@@ -62,7 +111,7 @@ def test_fetch_draft_order_lines_info(
channel=channel, variant=variant_2
).first()
)
- assert line_info_2.discounts == []
+ assert len(line_info_2.discounts) == 1
assert line_info_2.channel == channel
assert line_info_2.voucher is None
rule_info_2 = line_info_2.rules_info[0]
@@ -93,88 +142,14 @@ def test_editable_order_line_info_variant_discounted_price(
order_line_info = EditableOrderLineInfo(
line=order_line,
variant=variant,
- channel_listing=variant_channel_listing,
- product=product,
- product_type=product_type,
- collections=[],
- discounts=discounts,
- rules_info=[],
- channel=channel,
- voucher=None,
- voucher_code=None,
- )
- # then
- assert order_line_info.variant_discounted_price == expected_discounted_variant_price
-
-
-def test_editable_order_line_info_variant_discounted_price_without_listing(
- order_with_lines_and_catalogue_promotion,
-):
- # given
- order_line = order_with_lines_and_catalogue_promotion.lines.get(quantity=3)
- order = order_with_lines_and_catalogue_promotion
- channel = order.channel
- variant = order_line.variant
- variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
- product = variant.product
- product_type = product.product_type
- discounts = order_line.discounts.all()
-
- expected_discounted_variant_price = variant_channel_listing.discounted_price
- assert variant_channel_listing.discounted_price != variant_channel_listing.price
-
- variant.channel_listings.all().delete()
-
- # when
- order_line_info = EditableOrderLineInfo(
- line=order_line,
- variant=variant,
- channel_listing=None,
- product=product,
- product_type=product_type,
- collections=[],
- discounts=discounts,
- rules_info=[],
- channel=channel,
- voucher=None,
- voucher_code=None,
- )
- # then
- assert order_line_info.variant_discounted_price == expected_discounted_variant_price
-
-
-def test_editable_order_line_info_variant_discounted_price_when_listing_without_price(
- order_with_lines_and_catalogue_promotion,
-):
- # given
- order_line = order_with_lines_and_catalogue_promotion.lines.get(quantity=3)
- order = order_with_lines_and_catalogue_promotion
- channel = order.channel
- variant = order_line.variant
- variant_channel_listing = variant.channel_listings.get(channel_id=channel.id)
- product = variant.product
- product_type = product.product_type
- discounts = order_line.discounts.all()
-
- expected_discounted_variant_price = variant_channel_listing.discounted_price
- assert variant_channel_listing.discounted_price != variant_channel_listing.price
-
- variant_channel_listing.discounted_price_amount = None
- variant_channel_listing.save(update_fields=["discounted_price_amount"])
-
- # when
- order_line_info = EditableOrderLineInfo(
- line=order_line,
- variant=variant,
- channel_listing=variant_channel_listing,
product=product,
product_type=product_type,
collections=[],
discounts=discounts,
- rules_info=[],
channel=channel,
voucher=None,
voucher_code=None,
+ voucher_denormalized_info=None,
)
# then
assert order_line_info.variant_discounted_price == expected_discounted_variant_price
diff --git a/saleor/order/tests/test_fetch_order_prices.py b/saleor/order/tests/test_fetch_order_prices.py
index 4e797ad44e..5b06a43b19 100644
--- a/saleor/order/tests/test_fetch_order_prices.py
+++ b/saleor/order/tests/test_fetch_order_prices.py
@@ -3,7 +3,7 @@ from decimal import Decimal
import graphene
import pytest
-from ...core.prices import Money, quantize_price
+from ...core.prices import quantize_price
from ...core.taxes import zero_money
from ...discount import DiscountType, DiscountValueType, VoucherType
from ...discount.models import (
@@ -11,22 +11,23 @@ from ...discount.models import (
OrderLineDiscount,
PromotionRule,
)
+from ...discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
+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 ...tests import race_condition
from ...tests.utils import round_down, round_up
from .. import OrderStatus, calculations
[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,
tax_configuration_flat_rates,
):
# given
- if create_new_discounts:
- OrderLineDiscount.objects.all().delete()
-
order = order_with_lines_and_catalogue_promotion
order.status = OrderStatus.UNCONFIRMED
channel = order.channel
@@ -840,6 +841,7 @@ def test_fetch_order_prices_manual_discount_and_order_discount_flat_rates(
plugins_manager,
tax_configuration_flat_rates,
):
+ """Manual order discount do not combine with order promotions."""
# given
order = order_with_lines_and_order_promotion
order.status = OrderStatus.UNCONFIRMED
@@ -976,6 +978,7 @@ def test_fetch_order_prices_manual_discount_and_gift_discount_flat_rates(
plugins_manager,
tax_configuration_flat_rates,
):
+ """Manual order discount do not combine with order promotions."""
# given
order = order_with_lines_and_gift_promotion
order.status = OrderStatus.UNCONFIRMED
@@ -1283,60 +1286,7 @@ def test_fetch_order_prices_manual_discount_and_catalogue_discount_flat_rates(
)
-def test_fetch_order_prices_manual_line_discount_and_catalogue_discount_flat_rates(
- order_with_lines_and_catalogue_promotion,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- order = order_with_lines_and_catalogue_promotion
- order.status = OrderStatus.UNCONFIRMED
-
- 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 - manual_discount_value
- )
- 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
-
- 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_voucher_specific_product_fixed(
+def test_fetch_order_prices_manual_order_discount_voucher_specific_product(
order_with_lines,
voucher_specific_product_type,
plugins_manager,
@@ -1349,9 +1299,10 @@ def test_fetch_order_prices_voucher_specific_product_fixed(
tax_rate = Decimal("1.23")
voucher_listing = voucher.channel_listings.get(channel=order.channel)
- unit_discount_amount = Decimal("5")
+ unit_discount_amount = Decimal("2")
voucher_listing.discount_value = unit_discount_amount
voucher_listing.save(update_fields=["discount_value"])
+
voucher.discount_value_type = DiscountValueType.FIXED
voucher.save(update_fields=["discount_value_type"])
@@ -1360,6 +1311,16 @@ def test_fetch_order_prices_voucher_specific_product_fixed(
voucher.variants.add(discounted_line.variant)
order.voucher = voucher
order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # create manual order discount
+ order_discount_amount = Decimal("10")
+ order_discount = order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=order_discount_amount,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ )
shipping_price = order.shipping_price.net
currency = order.currency
@@ -1374,22 +1335,32 @@ def test_fetch_order_prices_voucher_specific_product_fixed(
# then
discounted_line, line_1 = lines
- discount_amount = unit_discount_amount * discounted_line.quantity
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
+ voucher_discount_amount = unit_discount_amount * discounted_line.quantity
+ assert order.total_gross_amount == quantize_price(
+ (
+ subtotal.amount
+ + shipping_price.amount
+ - voucher_discount_amount
+ - order_discount_amount
+ )
+ * tax_rate,
+ currency,
)
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ shipping_discount = shipping_price - order.shipping_price_net
+ subtotal_order_discount = order_discount_amount - shipping_discount.amount
+ assert order.subtotal_gross_amount == quantize_price(
+ (subtotal.amount - subtotal_order_discount - voucher_discount_amount)
+ * tax_rate,
+ currency,
+ )
+ assert order.undiscounted_total_gross == quantize_price(
+ (subtotal + shipping_price) * tax_rate, currency
)
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+ assert order.shipping_price_gross == quantize_price(
+ (shipping_price - shipping_discount) * tax_rate, currency
+ )
+ assert order.base_shipping_price == shipping_price
+ assert order.undiscounted_base_shipping_price == shipping_price
assert (
discounted_line.base_unit_price_amount
@@ -1397,7 +1368,7 @@ def test_fetch_order_prices_voucher_specific_product_fixed(
)
assert (
discounted_line.total_price_gross_amount
- == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
+ == discounted_line.unit_price_gross_amount * discounted_line.quantity
)
assert (
discounted_line.undiscounted_total_price_gross_amount
@@ -1412,7 +1383,7 @@ def test_fetch_order_prices_voucher_specific_product_fixed(
assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
assert (
line_1.total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
)
assert (
line_1.undiscounted_total_price_gross_amount
@@ -1422,52 +1393,58 @@ def test_fetch_order_prices_voucher_specific_product_fixed(
assert line_1.unit_discount_type is None
assert line_1.unit_discount_reason is None
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == order_discount_amount
+
assert discounted_line.discounts.count() == 1
line_discount = discounted_line.discounts.first()
- assert line_discount.amount_value == discount_amount
+ assert line_discount.amount_value == voucher_discount_amount
assert line_discount.value_type == DiscountValueType.FIXED
assert line_discount.type == DiscountType.VOUCHER
assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == discount_amount
+ assert line_discount.value == unit_discount_amount
-def test_fetch_order_prices_voucher_specific_product_discount_line_object_updated(
+def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_order(
order_with_lines,
- voucher_specific_product_type,
+ voucher,
plugins_manager,
tax_configuration_flat_rates,
):
# given
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
- voucher = voucher_specific_product_type
tax_rate = Decimal("1.23")
voucher_listing = voucher.channel_listings.get(channel=order.channel)
- unit_discount_amount = Decimal("5")
- voucher_listing.discount_value = unit_discount_amount
+ discount_amount = Decimal("3")
+ voucher_listing.discount_value = discount_amount
voucher_listing.save(update_fields=["discount_value"])
+
+ voucher.apply_once_per_order = True
voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["discount_value_type"])
+ voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
lines = order.lines.all()
- discounted_line, line_1 = lines
- voucher.variants.add(discounted_line.variant)
order.voucher = voucher
order.voucher_code = voucher.codes.first().code
+ order.save(update_fields=["voucher", "voucher_code"])
+ create_or_update_voucher_discount_objects_for_order(order)
- line_discount = discounted_line.discounts.create(
+ # create manual order discount
+ order_discount_amount = Decimal("8")
+ order_discount = order.discounts.create(
value_type=DiscountValueType.FIXED,
- value=Decimal("0"),
- name="Manual line discount",
- type=DiscountType.VOUCHER,
+ value=order_discount_amount,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
)
shipping_price = order.shipping_price.net
currency = order.currency
- subtotal = zero_money(currency)
+ undiscounted_subtotal = zero_money(currency)
for line in lines:
- subtotal += line.base_unit_price * line.quantity
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
# when
order, lines = calculations.fetch_order_prices_if_expired(
@@ -1476,30 +1453,43 @@ def test_fetch_order_prices_voucher_specific_product_discount_line_object_update
# then
discounted_line, line_1 = lines
- discount_amount = unit_discount_amount * discounted_line.quantity
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
+ voucher_discount_amount = discount_amount
+ order.refresh_from_db()
+ assert order.total_net_amount == quantize_price(
+ (
+ undiscounted_subtotal.amount
+ + shipping_price.amount
+ - voucher_discount_amount
+ - order_discount_amount
+ ),
+ currency,
)
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ assert order.total_gross_amount == (
+ discounted_line.total_price_gross_amount
+ + line_1.total_price_gross_amount
+ + order.shipping_price_gross_amount
+ )
+ assert order.undiscounted_total_gross == quantize_price(
+ (undiscounted_subtotal + shipping_price) * tax_rate, currency
+ )
+ shipping_discount = shipping_price - order.shipping_price_net
+ assert order.shipping_price_gross == quantize_price(
+ (shipping_price - shipping_discount) * tax_rate, currency
)
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
+ assert order.base_shipping_price == shipping_price
+ assert order.undiscounted_base_shipping_price == shipping_price
+ unit_discount_amount = discount_amount / discounted_line.quantity
assert (
discounted_line.base_unit_price_amount
== discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
)
assert (
- discounted_line.total_price_gross_amount
- == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
+ quantize_price(
+ discounted_line.total_price_gross_amount / discounted_line.quantity,
+ currency,
+ )
+ == discounted_line.unit_price_gross_amount
)
assert (
discounted_line.undiscounted_total_price_gross_amount
@@ -1514,7 +1504,7 @@ def test_fetch_order_prices_voucher_specific_product_discount_line_object_update
assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
assert (
line_1.total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
+ == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
)
assert (
line_1.undiscounted_total_price_gross_amount
@@ -1524,45 +1514,98 @@ def test_fetch_order_prices_voucher_specific_product_discount_line_object_update
assert line_1.unit_discount_type is None
assert line_1.unit_discount_reason is None
+ order_discount.refresh_from_db()
+ assert order_discount.amount_value == order_discount_amount
+
assert discounted_line.discounts.count() == 1
- line_discount.refresh_from_db()
- assert line_discount.amount_value == discount_amount
+ line_discount = discounted_line.discounts.first()
+ assert line_discount.amount_value == voucher_discount_amount
assert line_discount.value_type == DiscountValueType.FIXED
assert line_discount.type == DiscountType.VOUCHER
assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == discount_amount
+ assert line_discount.value == voucher_discount_amount
+
+
+def test_fetch_order_prices_order_promotion_discount_race_condition(
+ order_with_lines_and_order_promotion,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines_and_order_promotion
+ order.status = OrderStatus.UNCONFIRMED
+ OrderDiscount.objects.all().delete()
+
+ # when
+ def call_before_creating_order_promotion_line_discount(*args, **kwargs):
+ calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ with race_condition.RunBefore(
+ "saleor.discount.utils.promotion._handle_order_promotion",
+ call_before_creating_order_promotion_line_discount,
+ ):
+ calculations.fetch_order_prices_if_expired(order, plugins_manager, None, True)
+
+ # then
+ assert OrderDiscount.objects.count() == 1
-def test_fetch_order_prices_voucher_specific_product_percentage(
+def test_fetch_order_prices_voucher_shipping_and_manual_discount_fixed(
order_with_lines,
- voucher_specific_product_type,
+ voucher,
plugins_manager,
tax_configuration_flat_rates,
):
# given
+ voucher.type = VoucherType.SHIPPING
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.save(update_fields=["type", "discount_value_type"])
+
order = order_with_lines
order.status = OrderStatus.UNCONFIRMED
- voucher = voucher_specific_product_type
tax_rate = Decimal("1.23")
voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_value = Decimal("10")
- voucher_listing.discount_value = discount_value
+ voucher_discount_amount = Decimal("4")
+ voucher_listing.discount_value = voucher_discount_amount
voucher_listing.save(update_fields=["discount_value"])
- voucher.discount_value_type = DiscountValueType.PERCENTAGE
- voucher.save(update_fields=["discount_value_type"])
- lines = order.lines.all()
- discounted_line, line_1 = lines
- voucher.variants.add(discounted_line.variant)
order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
+ code = voucher.codes.first().code
+ order.voucher_code = code
+ create_or_update_voucher_discount_objects_for_order(order)
- shipping_price = order.shipping_price.net
+ undiscounted_shipping_price = order.shipping_price.net.amount
+ base_shipping_price = Decimal(undiscounted_shipping_price - voucher_discount_amount)
currency = order.currency
- subtotal = zero_money(currency)
+ undiscounted_subtotal = Decimal(0)
+ lines = order.lines.all()
for line in lines:
- subtotal += line.base_unit_price * line.quantity
+ undiscounted_subtotal += line.base_unit_price_amount * line.quantity
+
+ # create manual order discount
+ manual_discount_amount = Decimal("10")
+ manual_discount = order.discounts.create(
+ value_type=DiscountValueType.FIXED,
+ value=manual_discount_amount,
+ name="Manual order discount",
+ type=DiscountType.MANUAL,
+ currency=currency,
+ )
+
+ total_with_shipping_voucher_discount = undiscounted_subtotal + base_shipping_price
+ subtotal_manual_reward_portion = round(
+ (undiscounted_subtotal / total_with_shipping_voucher_discount)
+ * manual_discount_amount,
+ 2,
+ )
+ shipping_manual_reward_portion = round(
+ manual_discount_amount - subtotal_manual_reward_portion, 2
+ )
+
+ expected_subtotal = undiscounted_subtotal - subtotal_manual_reward_portion
+ expected_shipping = base_shipping_price - shipping_manual_reward_portion
+ expected_total = expected_subtotal + expected_shipping
# when
order, lines = calculations.fetch_order_prices_if_expired(
@@ -1570,1345 +1613,29 @@ def test_fetch_order_prices_voucher_specific_product_percentage(
)
# then
- discounted_line, line_1 = lines
- discount_amount = (
- discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * discount_value
- / 100
- )
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
- )
+ assert OrderDiscount.objects.count() == 2
+ voucher_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()
+ assert voucher_discount.voucher == voucher
+ assert voucher_discount.voucher_code == code
assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
+ voucher_discount.amount_value
+ == undiscounted_shipping_price - base_shipping_price
)
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
- unit_discount_amount = discount_amount / discounted_line.quantity
+ manual_discount.refresh_from_db()
+ assert manual_discount.amount.amount == manual_discount_amount
+
+ assert order.undiscounted_base_shipping_price_amount == undiscounted_shipping_price
+ assert order.base_shipping_price_amount == base_shipping_price
+ assert order.shipping_price_net_amount == expected_shipping
+ assert order.shipping_price_gross.amount == round(expected_shipping * tax_rate, 2)
+ assert order.subtotal_net_amount == expected_subtotal
+ assert order.subtotal_gross_amount == round(expected_subtotal * tax_rate, 2)
+ assert order.total_net_amount == expected_total
+ assert order.total_gross_amount == round(expected_total * tax_rate, 2)
assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
- )
- assert (
- discounted_line.total_price_gross_amount
- == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == unit_discount_amount
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- assert discounted_line.discounts.count() == 1
- line_discount = discounted_line.discounts.first()
- assert line_discount.amount_value == discount_amount
- # TODO: should be from voucher probably
- assert line_discount.value_type == DiscountValueType.FIXED
- assert line_discount.type == DiscountType.VOUCHER
- assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == discount_amount
-
-
-def test_fetch_order_prices_voucher_apply_once_per_order_fixed(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_amount = Decimal("5")
- voucher_listing.discount_value = discount_amount
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.apply_once_per_order = True
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
-
- lines = order.lines.all()
- order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- discounted_line, line_1 = lines
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
- )
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
-
- unit_discount_amount = discount_amount / discounted_line.quantity
- assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
- )
- assert (
- discounted_line.total_price_gross_amount
- == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == unit_discount_amount
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- assert discounted_line.discounts.count() == 1
- line_discount = discounted_line.discounts.first()
- assert line_discount.amount_value == discount_amount
- assert line_discount.value_type == DiscountValueType.FIXED
- assert line_discount.type == DiscountType.VOUCHER
- assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == discount_amount
-
-
-def test_fetch_order_prices_voucher_apply_once_per_order_percentage(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_value = Decimal("10")
- voucher_listing.discount_value = discount_value
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.apply_once_per_order = True
- voucher.discount_value_type = DiscountValueType.PERCENTAGE
- voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
-
- lines = order.lines.all()
- order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- discounted_line, line_1 = lines
- discount_amount = (
- discounted_line.undiscounted_base_unit_price_amount * discount_value / 100
- )
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
- )
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
-
- unit_discount_amount = discount_amount / discounted_line.quantity
- assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
- )
- assert (
- discounted_line.total_price_gross_amount
- == discounted_line.base_unit_price_amount * discounted_line.quantity * tax_rate
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == unit_discount_amount
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- assert discounted_line.discounts.count() == 1
- line_discount = discounted_line.discounts.first()
- assert line_discount.amount_value == discount_amount
- assert line_discount.value_type == DiscountValueType.FIXED
- assert line_discount.type == DiscountType.VOUCHER
- assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == discount_amount
-
-
-def test_fetch_order_prices_manual_order_discount_voucher_specific_product(
- order_with_lines,
- voucher_specific_product_type,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- voucher = voucher_specific_product_type
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- unit_discount_amount = Decimal("2")
- voucher_listing.discount_value = unit_discount_amount
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["discount_value_type"])
-
- lines = order.lines.all()
- discounted_line, line_1 = lines
- voucher.variants.add(discounted_line.variant)
- order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
-
- # create manual order discount
- order_discount_amount = Decimal("10")
- order_discount = order.discounts.create(
- value_type=DiscountValueType.FIXED,
- value=order_discount_amount,
- name="Manual order discount",
- type=DiscountType.MANUAL,
- )
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- discounted_line, line_1 = lines
- voucher_discount_amount = unit_discount_amount * discounted_line.quantity
- assert order.total_gross_amount == quantize_price(
- (
- subtotal.amount
- + shipping_price.amount
- - voucher_discount_amount
- - order_discount_amount
- )
- * tax_rate,
- currency,
- )
- shipping_discount = shipping_price - order.shipping_price_net
- subtotal_order_discount = order_discount_amount - shipping_discount.amount
- assert order.subtotal_gross_amount == quantize_price(
- (subtotal.amount - subtotal_order_discount - voucher_discount_amount)
- * tax_rate,
- currency,
- )
- assert order.undiscounted_total_gross == quantize_price(
- (subtotal + shipping_price) * tax_rate, currency
- )
- assert order.shipping_price_gross == quantize_price(
- (shipping_price - shipping_discount) * tax_rate, currency
- )
- assert order.base_shipping_price == shipping_price
- assert order.undiscounted_base_shipping_price == shipping_price
-
- assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
- )
- assert (
- discounted_line.total_price_gross_amount
- == discounted_line.unit_price_gross_amount * discounted_line.quantity
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == unit_discount_amount
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_gross_amount
- == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- order_discount.refresh_from_db()
- assert order_discount.amount_value == order_discount_amount
-
- assert discounted_line.discounts.count() == 1
- line_discount = discounted_line.discounts.first()
- assert line_discount.amount_value == voucher_discount_amount
- assert line_discount.value_type == DiscountValueType.FIXED
- assert line_discount.type == DiscountType.VOUCHER
- assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == voucher_discount_amount
-
-
-def test_fetch_order_prices_manual_order_discount_and_voucher_apply_once_per_order(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_amount = Decimal("3")
- voucher_listing.discount_value = discount_amount
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.apply_once_per_order = True
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
-
- lines = order.lines.all()
- order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
- order.save(update_fields=["voucher", "voucher_code"])
-
- # create manual order discount
- order_discount_amount = Decimal("8")
- order_discount = order.discounts.create(
- value_type=DiscountValueType.FIXED,
- value=order_discount_amount,
- name="Manual order discount",
- type=DiscountType.MANUAL,
- )
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- discounted_line, line_1 = lines
- voucher_discount_amount = discount_amount
- order.refresh_from_db()
- assert order.total_net_amount == quantize_price(
- (
- subtotal.amount
- + shipping_price.amount
- - voucher_discount_amount
- - order_discount_amount
- ),
- currency,
- )
- assert order.total_gross_amount == (
- discounted_line.total_price_gross_amount
- + line_1.total_price_gross_amount
- + order.shipping_price_gross_amount
- )
- assert order.undiscounted_total_gross == quantize_price(
- (subtotal + shipping_price) * tax_rate, currency
- )
- shipping_discount = shipping_price - order.shipping_price_net
- assert order.shipping_price_gross == quantize_price(
- (shipping_price - shipping_discount) * tax_rate, currency
- )
- assert order.base_shipping_price == shipping_price
- assert order.undiscounted_base_shipping_price == shipping_price
-
- unit_discount_amount = discount_amount / discounted_line.quantity
- assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount - unit_discount_amount
- )
- assert (
- quantize_price(
- discounted_line.total_price_gross_amount / discounted_line.quantity,
- currency,
- )
- == discounted_line.unit_price_gross_amount
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == unit_discount_amount
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == f"Voucher code: {order.voucher_code}"
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_gross_amount
- == order.subtotal_gross_amount - discounted_line.total_price_gross_amount
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- order_discount.refresh_from_db()
- assert order_discount.amount_value == order_discount_amount
-
- assert discounted_line.discounts.count() == 1
- line_discount = discounted_line.discounts.first()
- assert line_discount.amount_value == voucher_discount_amount
- assert line_discount.value_type == DiscountValueType.FIXED
- assert line_discount.type == DiscountType.VOUCHER
- assert line_discount.reason == f"Voucher code: {order.voucher_code}"
- assert line_discount.value == voucher_discount_amount
-
-
-def test_fetch_order_prices_manual_line_discount_voucher_specific_product(
- order_with_lines,
- voucher_specific_product_type,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- """Manual line discount should not stack with other line discounts."""
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- voucher = voucher_specific_product_type
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- voucher_discount_value = Decimal("2")
- voucher_listing.discount_value = voucher_discount_value
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["discount_value_type"])
-
- lines = order.lines.all()
- discounted_line, line_1 = lines
- voucher.variants.add(discounted_line.variant)
- order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
-
- # create manual order line discount
- manual_line_discount_value = Decimal("3")
- manual_line_discount = discounted_line.discounts.create(
- value_type=DiscountValueType.FIXED,
- value=manual_line_discount_value,
- name="Manual line discount",
- type=DiscountType.MANUAL,
- reason="Manual line discount",
- )
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- discounted_line.refresh_from_db()
- line_1.refresh_from_db()
-
- manual_discount_amount = manual_line_discount_value * discounted_line.quantity
- assert (
- order.total_net_amount
- == subtotal.amount + shipping_price.amount - manual_discount_amount
- )
- assert (
- order.total_gross_amount
- == (subtotal.amount + shipping_price.amount - manual_discount_amount) * tax_rate
- )
- assert order.subtotal_net_amount == subtotal.amount - manual_discount_amount
- assert (
- order.subtotal_gross_amount
- == (subtotal.amount - manual_discount_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.base_shipping_price == shipping_price
-
- assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount
- - manual_line_discount_value
- )
- assert (
- discounted_line.total_price_net_amount
- == discounted_line.unit_price_net_amount * discounted_line.quantity
- )
- assert (
- discounted_line.total_price_gross_amount
- == discounted_line.unit_price_net_amount * discounted_line.quantity * tax_rate
- )
- assert (
- discounted_line.undiscounted_total_price_net_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == manual_line_discount_value
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == manual_line_discount.reason
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_net_amount
- == order.subtotal_net_amount - discounted_line.total_price_net_amount
- )
- assert (
- line_1.total_price_gross_amount
- == (order.subtotal_net_amount - discounted_line.total_price_net_amount)
- * tax_rate
- )
- assert (
- line_1.undiscounted_total_price_net_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- assert discounted_line.discounts.count() == 1
-
- manual_line_discount.refresh_from_db()
- assert manual_line_discount.amount_value == manual_discount_amount
- assert manual_line_discount.type == DiscountType.MANUAL
-
-
-def test_fetch_order_prices_manual_line_discount_and_voucher_apply_once_per_order(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- """Manual line discount should not stack with other line discounts."""
- # given
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- voucher_discount_value = Decimal("3")
- voucher_listing.discount_value = voucher_discount_value
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.apply_once_per_order = True
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["discount_value_type", "apply_once_per_order"])
-
- lines = order.lines.all()
- discounted_line, line_1 = lines
- order.voucher = voucher
- order.voucher_code = voucher.codes.first().code
-
- # create manual order line discount
- manual_line_discount_value = Decimal("3")
- manual_line_discount = discounted_line.discounts.create(
- value_type=DiscountValueType.FIXED,
- value=manual_line_discount_value,
- name="Manual line discount",
- type=DiscountType.MANUAL,
- reason="Manual line discount",
- )
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- discounted_line.refresh_from_db()
- line_1.refresh_from_db()
-
- manual_discount_amount = manual_line_discount_value * discounted_line.quantity
- assert (
- order.total_net_amount
- == subtotal.amount + shipping_price.amount - manual_discount_amount
- )
- assert (
- order.total_gross_amount
- == (subtotal.amount + shipping_price.amount - manual_discount_amount) * tax_rate
- )
- assert order.subtotal_net_amount == subtotal.amount - manual_discount_amount
- assert (
- order.subtotal_gross_amount
- == (subtotal.amount - manual_discount_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.base_shipping_price == shipping_price
-
- assert (
- discounted_line.base_unit_price_amount
- == discounted_line.undiscounted_base_unit_price_amount
- - manual_line_discount_value
- )
- assert (
- discounted_line.total_price_net_amount
- == discounted_line.unit_price_net_amount * discounted_line.quantity
- )
- assert (
- discounted_line.total_price_gross_amount
- == discounted_line.unit_price_net_amount * discounted_line.quantity * tax_rate
- )
- assert (
- discounted_line.undiscounted_total_price_net_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- )
- assert (
- discounted_line.undiscounted_total_price_gross_amount
- == discounted_line.undiscounted_base_unit_price_amount
- * discounted_line.quantity
- * tax_rate
- )
- assert discounted_line.unit_discount_amount == manual_line_discount_value
- assert discounted_line.unit_discount_type == DiscountValueType.FIXED
- assert discounted_line.unit_discount_reason == manual_line_discount.reason
-
- assert line_1.base_unit_price_amount == line_1.undiscounted_base_unit_price_amount
- assert (
- line_1.total_price_net_amount
- == order.subtotal_net_amount - discounted_line.total_price_net_amount
- )
- assert (
- line_1.total_price_gross_amount
- == (order.subtotal_net_amount - discounted_line.total_price_net_amount)
- * tax_rate
- )
- assert (
- line_1.undiscounted_total_price_net_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity
- )
- assert (
- line_1.undiscounted_total_price_gross_amount
- == line_1.undiscounted_base_unit_price_amount * line_1.quantity * tax_rate
- )
- assert line_1.unit_discount_amount == 0
- assert line_1.unit_discount_type is None
- assert line_1.unit_discount_reason is None
-
- assert discounted_line.discounts.count() == 1
-
- manual_line_discount.refresh_from_db()
- assert manual_line_discount.amount_value == manual_discount_amount
- assert manual_line_discount.type == DiscountType.MANUAL
-
-
-def test_fetch_order_prices_catalogue_discount_race_condition(
- order_with_lines_and_catalogue_promotion,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- order = order_with_lines_and_catalogue_promotion
- order.status = OrderStatus.UNCONFIRMED
- 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 race_condition.RunBefore(
- "saleor.discount.utils.promotion."
- "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
-
-
-def test_fetch_order_prices_voucher_entire_order_fixed(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- assert voucher.type == VoucherType.ENTIRE_ORDER
- assert voucher.discount_value_type == DiscountValueType.FIXED
-
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_amount = Decimal("35")
- voucher_listing.discount_value = discount_amount
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.name = "Voucher name"
- voucher.save(update_fields=["name"])
-
- order.voucher = voucher
- code = voucher.codes.first().code
- order.voucher_code = code
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- lines = order.lines.all()
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- assert OrderDiscount.objects.count() == 1
- discount = order.discounts.first()
- assert discount.voucher == voucher
- assert discount.value_type == voucher.discount_value_type
- assert discount.value == discount_amount
- assert discount.amount_value == discount_amount
- assert discount.currency == currency
- assert discount.reason == f"Voucher code: {code}"
- assert discount.name == voucher.name
- assert discount.type == DiscountType.VOUCHER
- assert discount.voucher_code == code
- # TODO (SHOPX-914): set translated voucher name
- assert discount.translated_name == ""
-
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
- )
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
-
- 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]
-
- 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 = discount_amount * line_1_base_total / base_total
- line_2_order_discount_portion = discount_amount - line_1_order_discount_portion
-
- 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_unit_price_net_amount == variant_1_undiscounted_unit_price
- )
- assert line_1.total_price_net_amount == line_1_total_net_amount
- 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
-
- 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_unit_price_net_amount == variant_2_undiscounted_unit_price
- )
- assert line_2.total_price_net_amount == line_2_total_net_amount
- assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
- assert line_2.unit_price_net_amount == line_2_total_net_amount / line_2.quantity
-
-
-def test_fetch_order_prices_voucher_entire_order_multiple_lines(
- order,
- voucher,
- plugins_manager,
- order_lines_generator,
- product_list,
- tax_configuration_flat_rates,
-):
- # given
- assert voucher.type == VoucherType.ENTIRE_ORDER
- assert voucher.discount_value_type == DiscountValueType.FIXED
-
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_amount = Decimal("3")
- voucher_listing.discount_value = discount_amount
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.name = "Voucher name"
- voucher.save(update_fields=["name"])
-
- code = voucher.codes.first().code
- order.voucher = voucher
- order.voucher_code = code
-
- shipping_price = order.shipping_price.net
- currency = order.currency
-
- variant_list = [product.variants.first() for product in product_list[:3]]
- unit_prices = [7, 33, 25]
- quantities = [1, 1, 1]
- lines = order_lines_generator(order, variant_list, unit_prices, quantities)
-
- subtotal = Money(sum(unit_prices), currency)
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- assert OrderDiscount.objects.count() == 1
- discount = order.discounts.first()
- assert discount.voucher == voucher
- assert discount.value_type == voucher.discount_value_type
- assert discount.value == discount_amount
- assert discount.amount_value == discount_amount
- assert discount.currency == currency
- assert discount.reason == f"Voucher code: {code}"
- assert discount.name == voucher.name
- assert discount.type == DiscountType.VOUCHER
- assert discount.voucher_code == code
- # TODO (SHOPX-914): set translated voucher name
- assert discount.translated_name == ""
-
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount - discount_amount
- assert order.subtotal_gross_amount == (subtotal.amount - discount_amount) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
- )
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
-
- remaining_discount = discount_amount
- for idx, line in enumerate(lines):
- line.refresh_from_db()
- idx = variant_list.index(line.variant)
- base_price = unit_prices[idx]
- line_base_total = base_price
- if idx < len(lines) - 1:
- line_order_discount_portion = quantize_price(
- discount_amount * line_base_total / subtotal.amount, currency
- )
- remaining_discount -= line_order_discount_portion
- else:
- line_order_discount_portion = remaining_discount
-
- line_total_net_amount = (
- line.undiscounted_total_price_net_amount - line_order_discount_portion
- )
- assert line.undiscounted_total_price_net_amount == base_price
- assert line.undiscounted_unit_price_net_amount == base_price
- assert line.total_price_net_amount == line_total_net_amount
- assert line.base_unit_price_amount == base_price
- assert line.unit_price_net_amount == line_total_net_amount
-
-
-def test_fetch_order_prices_voucher_entire_order_percentage(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- assert voucher.type == VoucherType.ENTIRE_ORDER
- voucher.discount_value_type = DiscountValueType.PERCENTAGE
- voucher.save(update_fields=["discount_value_type"])
-
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_value = Decimal("50")
- voucher_listing.discount_value = discount_value
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.name = "Voucher name"
- voucher.save(update_fields=["name"])
-
- order.voucher = voucher
- code = voucher.codes.first().code
- order.voucher_code = code
-
- shipping_price = order.shipping_price.net
- currency = order.currency
- subtotal = zero_money(currency)
- lines = order.lines.all()
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- assert OrderDiscount.objects.count() == 1
- discount = order.discounts.first()
- assert discount.voucher == voucher
- assert discount.value_type == voucher.discount_value_type
- assert discount.value == discount_value
- assert discount.amount_value == Decimal(subtotal.amount / 2)
- assert discount.currency == currency
- assert discount.reason == f"Voucher code: {code}"
- assert discount.name == voucher.name
- assert discount.type == DiscountType.VOUCHER
- assert discount.voucher_code == code
- # TODO (SHOPX-914): set translated voucher name
- assert discount.translated_name == ""
-
- assert order.base_shipping_price == shipping_price
- assert order.shipping_price_net == shipping_price
- assert order.shipping_price_gross == shipping_price * tax_rate
- assert order.subtotal_net_amount == Decimal(subtotal.amount / 2)
- assert order.subtotal_gross_amount == Decimal(subtotal.amount / 2) * tax_rate
- assert (
- order.total_net_amount
- == order.subtotal_net_amount + order.base_shipping_price_amount
- )
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + order.base_shipping_price_amount) * tax_rate
- )
- assert order.undiscounted_total_net == subtotal + shipping_price
- assert order.undiscounted_total_gross == (subtotal + shipping_price) * tax_rate
-
- 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]
-
- 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 / 2,
- currency,
- )
- assert (
- line_1.undiscounted_total_price_net_amount
- == variant_1_undiscounted_unit_price * line_1.quantity
- )
- assert (
- line_1.undiscounted_unit_price_net_amount == variant_1_undiscounted_unit_price
- )
- assert line_1.total_price_net_amount == line_1_total_net_amount
- 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
-
- 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 / 2,
- currency,
- )
- assert (
- line_2.undiscounted_total_price_net_amount
- == variant_2_undiscounted_unit_price * line_2.quantity
- )
- assert (
- line_2.undiscounted_unit_price_net_amount == variant_2_undiscounted_unit_price
- )
- assert line_2.total_price_net_amount == line_2_total_net_amount
- assert line_2.base_unit_price_amount == variant_2_undiscounted_unit_price
- assert line_2.unit_price_net_amount == line_2_total_net_amount / line_2.quantity
-
-
-def test_fetch_order_prices_voucher_shipping_fixed(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- voucher.type = VoucherType.SHIPPING
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["type", "discount_value_type"])
-
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_value = Decimal("5")
- voucher_listing.discount_value = discount_value
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.name = "Voucher shipping"
- voucher.save(update_fields=["name"])
-
- order.voucher = voucher
- code = voucher.codes.first().code
- order.voucher_code = code
-
- undiscounted_shipping_price = order.shipping_price.net.amount
- expected_shipping_price = Decimal(undiscounted_shipping_price - discount_value)
- currency = order.currency
- subtotal = zero_money(currency)
- lines = order.lines.all()
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- assert OrderDiscount.objects.count() == 1
- discount = order.discounts.first()
- assert discount.voucher == voucher
- assert discount.value_type == voucher.discount_value_type
- assert discount.value == discount_value
- assert (
- discount.amount_value == undiscounted_shipping_price - expected_shipping_price
- )
- assert discount.reason == f"Voucher code: {code}"
- assert discount.name == voucher.name
- assert discount.type == DiscountType.VOUCHER
- assert discount.voucher_code == code
- # TODO (SHOPX-914): set translated voucher name
- assert discount.translated_name == ""
-
- assert order.undiscounted_base_shipping_price_amount == undiscounted_shipping_price
- assert order.base_shipping_price_amount == expected_shipping_price
- assert order.shipping_price_net_amount == expected_shipping_price
- assert order.shipping_price_gross.amount == expected_shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount
- assert order.subtotal_gross_amount == subtotal.amount * tax_rate
- assert order.total_net_amount == order.subtotal_net_amount + expected_shipping_price
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + expected_shipping_price) * tax_rate
- )
- assert (
- order.undiscounted_total_net_amount
- == subtotal.amount + undiscounted_shipping_price
- )
- assert (
- order.undiscounted_total_gross_amount
- == (subtotal.amount + undiscounted_shipping_price) * tax_rate
- )
-
-
-def test_fetch_order_prices_voucher_shipping_percentage(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- voucher.type = VoucherType.SHIPPING
- voucher.discount_value_type = DiscountValueType.PERCENTAGE
- voucher.save(update_fields=["type", "discount_value_type"])
-
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- discount_value = Decimal("50")
- voucher_listing.discount_value = discount_value
- voucher_listing.save(update_fields=["discount_value"])
-
- voucher.name = "Voucher shipping"
- voucher.save(update_fields=["name"])
-
- order.voucher = voucher
- code = voucher.codes.first().code
- order.voucher_code = code
-
- undiscounted_shipping_price = order.shipping_price.net.amount
- expected_shipping_price = Decimal(undiscounted_shipping_price / 2)
- currency = order.currency
- subtotal = zero_money(currency)
- lines = order.lines.all()
- for line in lines:
- subtotal += line.base_unit_price * line.quantity
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- assert OrderDiscount.objects.count() == 1
- discount = order.discounts.first()
- assert discount.voucher == voucher
- assert discount.value_type == voucher.discount_value_type
- assert discount.value == discount_value
- assert (
- discount.amount_value == undiscounted_shipping_price - expected_shipping_price
- )
- assert discount.reason == f"Voucher code: {code}"
- assert discount.name == voucher.name
- assert discount.type == DiscountType.VOUCHER
- assert discount.voucher_code == code
- # TODO (SHOPX-914): set translated voucher name
- assert discount.translated_name == ""
-
- assert order.undiscounted_base_shipping_price.amount == undiscounted_shipping_price
- assert order.base_shipping_price.amount == expected_shipping_price
- assert order.shipping_price_net_amount == expected_shipping_price
- assert order.shipping_price_gross.amount == expected_shipping_price * tax_rate
- assert order.subtotal_net_amount == subtotal.amount
- assert order.subtotal_gross_amount == subtotal.amount * tax_rate
- assert order.total_net_amount == order.subtotal_net_amount + expected_shipping_price
- assert (
- order.total_gross_amount
- == (order.subtotal_net_amount + expected_shipping_price) * tax_rate
- )
- assert (
- order.undiscounted_total_net_amount
- == subtotal.amount + undiscounted_shipping_price
- )
- assert (
- order.undiscounted_total_gross_amount
- == (subtotal.amount + undiscounted_shipping_price) * tax_rate
- )
-
-
-def test_fetch_order_prices_voucher_shipping_and_manual_discount_fixed(
- order_with_lines,
- voucher,
- plugins_manager,
- tax_configuration_flat_rates,
-):
- # given
- voucher.type = VoucherType.SHIPPING
- voucher.discount_value_type = DiscountValueType.FIXED
- voucher.save(update_fields=["type", "discount_value_type"])
-
- order = order_with_lines
- order.status = OrderStatus.UNCONFIRMED
- tax_rate = Decimal("1.23")
-
- voucher_listing = voucher.channel_listings.get(channel=order.channel)
- voucher_discount_amount = Decimal("4")
- voucher_listing.discount_value = voucher_discount_amount
- voucher_listing.save(update_fields=["discount_value"])
-
- order.voucher = voucher
- code = voucher.codes.first().code
- order.voucher_code = code
-
- undiscounted_shipping_price = order.shipping_price.net.amount
- base_shipping_price = Decimal(undiscounted_shipping_price - voucher_discount_amount)
- currency = order.currency
- undiscounted_subtotal = Decimal(0)
- lines = order.lines.all()
- for line in lines:
- undiscounted_subtotal += line.base_unit_price_amount * line.quantity
-
- # create manual order discount
- manual_discount_amount = Decimal("10")
- manual_discount = order.discounts.create(
- value_type=DiscountValueType.FIXED,
- value=manual_discount_amount,
- name="Manual order discount",
- type=DiscountType.MANUAL,
- currency=currency,
- )
-
- total_with_shipping_voucher_discount = undiscounted_subtotal + base_shipping_price
- subtotal_manual_reward_portion = round(
- (undiscounted_subtotal / total_with_shipping_voucher_discount)
- * manual_discount_amount,
- 2,
- )
- shipping_manual_reward_portion = round(
- manual_discount_amount - subtotal_manual_reward_portion, 2
- )
-
- expected_subtotal = undiscounted_subtotal - subtotal_manual_reward_portion
- expected_shipping = base_shipping_price - shipping_manual_reward_portion
- expected_total = expected_subtotal + expected_shipping
-
- # when
- order, lines = calculations.fetch_order_prices_if_expired(
- order, plugins_manager, None, True
- )
-
- # then
- assert OrderDiscount.objects.count() == 2
- voucher_discount = order.discounts.filter(type=DiscountType.VOUCHER).first()
- assert voucher_discount.voucher == voucher
- assert voucher_discount.voucher_code == code
- assert (
- voucher_discount.amount_value
- == undiscounted_shipping_price - base_shipping_price
- )
-
- manual_discount.refresh_from_db()
- assert manual_discount.amount.amount == manual_discount_amount
-
- assert order.undiscounted_base_shipping_price_amount == undiscounted_shipping_price
- assert order.base_shipping_price_amount == base_shipping_price
- assert order.shipping_price_net_amount == expected_shipping
- assert order.shipping_price_gross.amount == round(expected_shipping * tax_rate, 2)
- assert order.subtotal_net_amount == expected_subtotal
- assert order.subtotal_gross_amount == round(expected_subtotal * tax_rate, 2)
- assert order.total_net_amount == expected_total
- assert order.total_gross_amount == round(expected_total * tax_rate, 2)
- assert (
- order.undiscounted_total_net_amount
- == undiscounted_subtotal + undiscounted_shipping_price
+ order.undiscounted_total_net_amount
+ == undiscounted_subtotal + undiscounted_shipping_price
)
assert order.undiscounted_total_gross_amount == round(
(undiscounted_subtotal + undiscounted_shipping_price) * tax_rate, 2
@@ -2938,6 +1665,7 @@ def test_fetch_order_prices_voucher_shipping_and_manual_discount_percentage(
order.voucher = voucher
code = voucher.codes.first().code
order.voucher_code = code
+ create_or_update_voucher_discount_objects_for_order(order)
undiscounted_shipping_price = order.shipping_price.net.amount
base_shipping_price = Decimal(undiscounted_shipping_price - voucher_discount_amount)
@@ -3032,6 +1760,7 @@ def test_fetch_order_prices_voucher_shipping_and_manual_discount_fixed_exceed_to
order.voucher = voucher
code = voucher.codes.first().code
order.voucher_code = code
+ create_or_update_voucher_discount_objects_for_order(order)
undiscounted_shipping_price = order.shipping_price.net.amount
base_shipping_price = Decimal(undiscounted_shipping_price - voucher_discount_amount)
@@ -3225,3 +1954,102 @@ def test_fetch_order_prices_catalogue_discount_prices_entered_with_tax_tax_exemp
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
+
+
+def test_fetch_order_prices_removing_catalogue_promotion_doesnt_remove_discount(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ currency = order.currency
+ order.status = OrderStatus.UNCONFIRMED
+ channel = order.channel
+ line_1, line_2 = order.lines.all()
+ catalogue_discount = line_1.discounts.get()
+ assert catalogue_discount.type == DiscountType.PROMOTION
+
+ rule = catalogue_discount.promotion_rule
+ promotion = rule.promotion
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ catalogue_reward_value = rule.reward_value
+ catalogue_reward_value_type = rule.reward_value_type
+ catalogue_unit_discount_amount = catalogue_reward_value
+
+ tax_rate = Decimal("1.23")
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ line_1_base_unit_price = (
+ variant_1_undiscounted_unit_price - catalogue_unit_discount_amount
+ )
+ line_1 = lines[0]
+ assert line_1.base_unit_price_amount == line_1_base_unit_price
+
+ # when
+ promotion.delete()
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+ order, lines = calculations.fetch_order_prices_if_expired(
+ order, plugins_manager, None, True
+ )
+
+ # then
+ variant_1_listing.refresh_from_db()
+ assert (
+ variant_1_listing.discounted_price_amount == variant_1_undiscounted_unit_price
+ )
+ assert OrderLineDiscount.objects.count() == 1
+ assert not OrderDiscount.objects.exists()
+
+ line_1, line_2 = lines
+ catalogue_discount.refresh_from_db()
+ catalogue_discount_amount = catalogue_unit_discount_amount * line_1.quantity
+ assert catalogue_discount.amount_value == catalogue_discount_amount
+ assert catalogue_discount.value == catalogue_reward_value
+ assert catalogue_discount.value_type == catalogue_reward_value_type
+ assert catalogue_discount.type == DiscountType.PROMOTION
+ assert catalogue_discount.reason == f"Promotion: {promotion_id}"
+ assert catalogue_discount.promotion_rule_id is None
+
+ variant_1 = line_1.variant
+ variant_1_listing = variant_1.channel_listings.get(channel=channel)
+ variant_1_undiscounted_unit_price = variant_1_listing.price_amount
+ assert (
+ line_1.undiscounted_base_unit_price_amount == variant_1_undiscounted_unit_price
+ )
+
+ 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
+ )
+
+ line_1_base_unit_price = (
+ variant_1_undiscounted_unit_price - catalogue_unit_discount_amount
+ )
+ assert line_1.base_unit_price_amount == line_1_base_unit_price
+ assert line_1.unit_price_net_amount == line_1_base_unit_price
+ assert line_1.unit_price_gross_amount == quantize_price(
+ line_1_base_unit_price * tax_rate, currency
+ )
+ assert (
+ line_1.total_price_net_amount == line_1.unit_price_net_amount * line_1.quantity
+ )
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
diff --git a/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py b/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
new file mode 100644
index 0000000000..1e6f2609fe
--- /dev/null
+++ b/saleor/order/tests/test_fetch_order_prices_line_price_expiration.py
@@ -0,0 +1,1756 @@
+from datetime import timedelta
+from decimal import Decimal
+
+import graphene
+import pytest
+from django.utils import timezone
+
+from ...core.prices import quantize_price
+from ...core.taxes import zero_money
+from ...discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from ...discount.models import (
+ OrderLineDiscount,
+ Promotion,
+ PromotionRule,
+)
+from ...discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
+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 .. import OrderStatus
+from ..calculations import fetch_order_prices_if_expired
+from ..models import OrderLine
+
+
+def test_fetch_order_prices_lines_expired_base_prices(
+ order_with_lines, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ line_1, line_2 = order.lines.all()
+ currency = order.currency
+ variant_1, variant_2 = line_1.variant, line_2.variant
+ tax_rate = Decimal("1.23")
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # expire order lines
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ OrderLine.objects.bulk_update([line_1, line_2], ["draft_base_price_expire_at"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.total_price_net_amount == new_variant_1_price * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == new_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == new_variant_2_price
+ assert line_2.total_price_net_amount == new_variant_2_price * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert order.subtotal_net_amount == undiscounted_subtotal
+ assert order.subtotal_gross_amount == quantize_price(
+ undiscounted_subtotal * tax_rate, currency
+ )
+ assert order.total_net_amount == undiscounted_subtotal + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_single_line_expired_base_prices(
+ order_with_lines, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # expire line 1
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_1.save(update_fields=["draft_base_price_expire_at"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.total_price_net_amount == new_variant_1_price * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == initial_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == initial_variant_2_price
+ assert line_2.total_price_net_amount == initial_variant_2_price * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert order.subtotal_net_amount == undiscounted_subtotal
+ assert order.subtotal_gross_amount == quantize_price(
+ undiscounted_subtotal * tax_rate, currency
+ )
+ assert order.total_net_amount == undiscounted_subtotal + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_lines_expired_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ channel = order.channel
+ currency = order.currency
+ promotion = Promotion.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ rule_1 = promotion.rules.get()
+ initial_reward_value_1 = rule_1.reward_value
+ initial_reward_value_type_1 = rule_1.reward_value_type
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ variant_2 = line_2.variant
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ discount_1 = line_1.discounts.first()
+ assert discount_1.value == initial_reward_value_1
+ assert discount_1.value_type == initial_reward_value_type_1
+ assert discount_1.amount_value == initial_reward_value_1 * line_1.quantity
+
+ # expire order lines
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ OrderLine.objects.bulk_update([line_1, line_2], ["draft_base_price_expire_at"])
+
+ # prepare new catalog promotion rule for variant 2
+ initial_reward_value_2 = Decimal(5)
+ initial_reward_value_type_2 = DiscountValueType.FIXED
+ rule_2 = promotion.rules.create(
+ name="Rule 2",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=initial_reward_value_type_2,
+ reward_value=initial_reward_value_2,
+ )
+ rule_2.channels.add(channel)
+
+ listing_2 = variant_2.channel_listings.get(channel=channel)
+ listing_2.discounted_price_amount = listing_2.price_amount - initial_reward_value_2
+ listing_2.save(update_fields=["discounted_price_amount"])
+ listing_2.variantlistingpromotionrule.create(
+ promotion_rule=rule_2,
+ discount_amount=initial_reward_value_2,
+ currency=currency,
+ )
+
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=initial_reward_value_2,
+ amount_value=initial_reward_value_2 * line_2.quantity,
+ currency=currency,
+ promotion_rule=rule_2,
+ reason=f"Promotion: {promotion_id}",
+ )
+
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - initial_reward_value_2
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # update promotion rules
+ new_reward_value_1 = Decimal(50)
+ new_reward_value_type_1 = RewardValueType.PERCENTAGE
+ rule_1.reward_value = new_reward_value_1
+ rule_1.reward_value_type = new_reward_value_type_1
+ rule_1.save(update_fields=["reward_value", "reward_value_type"])
+
+ new_reward_value_2 = Decimal(30)
+ new_reward_value_type_2 = RewardValueType.PERCENTAGE
+ rule_2.reward_value = new_reward_value_2
+ rule_2.reward_value_type = new_reward_value_type_2
+ rule_2.save(update_fields=["reward_value", "reward_value_type"])
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ # both lines should have price refreshed
+ undiscounted_unit_price_1 = line_1.undiscounted_base_unit_price_amount
+ expected_unit_price_1 = undiscounted_unit_price_1 * (1 - new_reward_value_1 / 100)
+ expected_unit_discount_1 = undiscounted_unit_price_1 - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ undiscounted_unit_price_2 = line_2.undiscounted_base_unit_price_amount
+ expected_unit_price_2 = undiscounted_unit_price_2 * (1 - new_reward_value_2 / 100)
+ expected_unit_discount_2 = undiscounted_unit_price_2 - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == undiscounted_unit_price_1
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == undiscounted_unit_price_1 * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == new_reward_value_1
+ assert discount_1.value_type == new_reward_value_type_1
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == undiscounted_unit_price_2
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == undiscounted_unit_price_2 * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == new_reward_value_2
+ assert discount_2.value_type == new_reward_value_type_2
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal
+ - expected_discount_amount_1
+ - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_single_line_expired_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+ plugins_manager,
+ tax_configuration_flat_rates,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ channel = order.channel
+ currency = order.currency
+ promotion = Promotion.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ rule_1 = promotion.rules.get()
+ initial_reward_value_1 = rule_1.reward_value
+ initial_reward_value_type_1 = rule_1.reward_value_type
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ variant_2 = line_2.variant
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ discount_1 = line_1.discounts.first()
+ assert discount_1.value == initial_reward_value_1
+ assert discount_1.value_type == initial_reward_value_type_1
+ assert discount_1.amount_value == initial_reward_value_1 * line_1.quantity
+
+ # expire line 1
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_1.save(update_fields=["draft_base_price_expire_at"])
+
+ # prepare new catalog promotion rule for variant 2
+ initial_reward_value_2 = Decimal(5)
+ initial_reward_value_type_2 = DiscountValueType.FIXED
+ rule_2 = promotion.rules.create(
+ name="Rule 2",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=initial_reward_value_type_2,
+ reward_value=initial_reward_value_2,
+ )
+ rule_2.channels.add(channel)
+
+ listing_2 = variant_2.channel_listings.get(channel=channel)
+ listing_2.discounted_price_amount = listing_2.price_amount - initial_reward_value_2
+ listing_2.save(update_fields=["discounted_price_amount"])
+ listing_2.variantlistingpromotionrule.create(
+ promotion_rule=rule_2,
+ discount_amount=initial_reward_value_2,
+ currency=currency,
+ )
+
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=initial_reward_value_2,
+ amount_value=initial_reward_value_2 * line_2.quantity,
+ currency=currency,
+ promotion_rule=rule_2,
+ reason=f"Promotion: {promotion_id}",
+ )
+
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - initial_reward_value_2
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # update promotion rules
+ new_reward_value_1 = Decimal(50)
+ new_reward_value_type_1 = RewardValueType.PERCENTAGE
+ rule_1.reward_value = new_reward_value_1
+ rule_1.reward_value_type = new_reward_value_type_1
+ rule_1.save(update_fields=["reward_value", "reward_value_type"])
+
+ new_reward_value_2 = Decimal(30)
+ new_reward_value_type_2 = RewardValueType.PERCENTAGE
+ rule_2.reward_value = new_reward_value_2
+ rule_2.reward_value_type = new_reward_value_type_2
+ rule_2.save(update_fields=["reward_value", "reward_value_type"])
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ undiscounted_unit_price_1 = line_1.undiscounted_base_unit_price_amount
+ expected_unit_price_1 = undiscounted_unit_price_1 * (1 - new_reward_value_1 / 100)
+ expected_unit_discount_1 = undiscounted_unit_price_1 - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ # line 2 prices shouldn't be refreshed
+ undiscounted_unit_price_2 = line_2.undiscounted_base_unit_price_amount
+ expected_unit_price_2 = undiscounted_unit_price_2 - initial_reward_value_2
+ expected_unit_discount_2 = initial_reward_value_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == undiscounted_unit_price_1
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == undiscounted_unit_price_1 * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == new_reward_value_1
+ assert discount_1.value_type == new_reward_value_type_1
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == undiscounted_unit_price_2
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == undiscounted_unit_price_2 * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == initial_reward_value_2
+ assert discount_2.value_type == initial_reward_value_type_2
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal
+ - expected_discount_amount_1
+ - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_lines_expired_new_catalogue_discount(
+ order_with_lines, catalogue_promotion, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ channel = order.channel
+ currency = order.currency
+ promotion = catalogue_promotion
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ variant_2 = line_2.variant
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare new catalog promotion rule for variant 2
+ promotion.rules.all().delete()
+ reward_value = Decimal(5)
+ reward_value_type = DiscountValueType.FIXED
+ rule = promotion.rules.create(
+ name="Rule 1",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=reward_value_type,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel)
+
+ listing_2 = variant_2.channel_listings.get(channel=channel)
+ listing_2.discounted_price_amount = listing_2.price_amount - reward_value
+ listing_2.save(update_fields=["discounted_price_amount"])
+ listing_2.variantlistingpromotionrule.create(
+ promotion_rule=rule,
+ discount_amount=reward_value,
+ currency=currency,
+ )
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ # expire order lines
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ OrderLine.objects.bulk_update([line_1, line_2], ["draft_base_price_expire_at"])
+
+ undiscounted_unit_price_1 = line_1.undiscounted_base_unit_price_amount
+ expected_unit_price_1 = undiscounted_unit_price_1
+ expected_unit_discount_1 = 0
+
+ # line 2 should have catalog discount applied
+ undiscounted_unit_price_2 = line_2.undiscounted_base_unit_price_amount
+ expected_unit_price_2 = undiscounted_unit_price_2 - reward_value
+ expected_unit_discount_2 = reward_value
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == undiscounted_unit_price_1
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == undiscounted_unit_price_1 * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason is None
+
+ assert not line_1.discounts.exists()
+
+ assert line_2.undiscounted_base_unit_price_amount == undiscounted_unit_price_2
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == undiscounted_unit_price_2 * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount = line_2.discounts.get()
+ assert discount.value == reward_value
+ assert discount.value_type == reward_value_type
+ assert discount.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_lines_expired_manual_line_discount(
+ order_with_lines, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # add manual discount to line 1
+ discount_1_reward_value = Decimal(20)
+ discount_1_unit_amount = discount_1_reward_value / 100 * initial_variant_1_price
+ discount_1_amount = discount_1_unit_amount * line_1.quantity
+ discount_1_reason = "Manual discount 1"
+ discount_1 = line_1.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_1_reward_value,
+ amount_value=discount_1_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ reason=discount_1_reason,
+ )
+ line_1.base_unit_price_amount = (
+ line_1.undiscounted_base_unit_price_amount - discount_1_unit_amount
+ )
+ line_1.save(update_fields=["base_unit_price_amount"])
+
+ # add manual discount to line 2
+ discount_2_reward_value = Decimal(10)
+ discount_2_unit_amount = discount_2_reward_value / 100 * initial_variant_2_price
+ discount_2_amount = discount_2_unit_amount * line_2.quantity
+ discount_2_reason = "Manual discount 2"
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_2_reward_value,
+ amount_value=discount_2_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ reason=discount_2_reason,
+ )
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - discount_2_unit_amount
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # expire order lines
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ OrderLine.objects.bulk_update([line_1, line_2], ["draft_base_price_expire_at"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # both lines should have price refreshed
+ expected_unit_price_1 = new_variant_1_price * (1 - discount_1_reward_value / 100)
+ expected_unit_discount_1 = new_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ expected_unit_price_2 = new_variant_2_price * (1 - discount_2_reward_value / 100)
+ expected_unit_discount_2 = new_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == discount_1_reason
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == discount_1_reward_value
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == new_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == discount_2_reason
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == discount_2_reward_value
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal
+ - expected_discount_amount_1
+ - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_single_line_expired_manual_line_discount(
+ order_with_lines, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # add manual discount to line 1
+ discount_1_reward_value = Decimal(20)
+ discount_1_unit_amount = discount_1_reward_value / 100 * initial_variant_1_price
+ initial_discount_1_amount = discount_1_unit_amount * line_1.quantity
+ discount_1_reason = "Manual discount 1"
+ discount_1 = line_1.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_1_reward_value,
+ amount_value=initial_discount_1_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ reason=discount_1_reason,
+ )
+ line_1.base_unit_price_amount = (
+ line_1.undiscounted_base_unit_price_amount - discount_1_unit_amount
+ )
+ line_1.save(update_fields=["base_unit_price_amount"])
+
+ # add manual discount to line 2
+ discount_2_reward_value = Decimal(10)
+ discount_2_unit_amount = discount_2_reward_value / 100 * initial_variant_2_price
+ initial_discount_2_amount = discount_2_unit_amount * line_2.quantity
+ discount_2_reason = "Manual discount 2"
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_2_reward_value,
+ amount_value=initial_discount_2_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ reason=discount_2_reason,
+ )
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - discount_2_unit_amount
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # expire line 2
+ now = timezone.now()
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.save(update_fields=["draft_base_price_expire_at"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # line 1 prices shouldn't be refreshed
+ expected_unit_price_1 = initial_variant_1_price * (
+ 1 - discount_1_reward_value / 100
+ )
+ expected_unit_discount_1 = initial_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ expected_unit_price_2 = new_variant_2_price * (1 - discount_2_reward_value / 100)
+ expected_unit_discount_2 = new_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == initial_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == initial_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == discount_1_reason
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == discount_1_reward_value
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+ assert (
+ discount_1.amount.amount
+ == expected_discount_amount_1
+ == initial_discount_1_amount
+ )
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == new_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == discount_2_reason
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == discount_2_reward_value
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal
+ - expected_discount_amount_1
+ - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_lines_expired_specific_product_voucher(
+ order_with_lines, voucher, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ tax_rate = Decimal("1.23")
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare specific product voucher which cover both line variants
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.set([line_1.variant, line_2.variant])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ line_1, line_2 = order.lines.all()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount * line_1.quantity
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ discount_2 = line_2.discounts.get()
+ discount_amount_2 = initial_voucher_unit_discount * line_2.quantity
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_2.value == initial_voucher_unit_discount
+ assert discount_2.amount_value == discount_amount_2
+
+ # expire order lines
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ OrderLine.objects.bulk_update([line_1, line_2], ["draft_base_price_expire_at"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(2)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(4)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # both lines should have price refreshed
+ expected_unit_price_1 = new_variant_1_price * (1 - new_voucher_unit_discount / 100)
+ expected_unit_discount_1 = new_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ expected_unit_price_2 = new_variant_2_price * (1 - new_voucher_unit_discount / 100)
+ expected_unit_discount_2 = new_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == new_voucher_unit_discount
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == new_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal
+ - expected_discount_amount_1
+ - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_single_line_expired_specific_product_voucher(
+ order_with_lines, voucher, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ currency = order.currency
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare specific product voucher which cover both line variants
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.set([line_1.variant, line_2.variant])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ line_1, line_2 = order.lines.all()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount * line_1.quantity
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ discount_2 = line_2.discounts.get()
+ discount_amount_2 = initial_voucher_unit_discount * line_2.quantity
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_2.value == initial_voucher_unit_discount
+ assert discount_2.amount_value == discount_amount_2
+
+ # expire line 1
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_1.save(update_fields=["draft_base_price_expire_at"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(2)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(4)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ expected_unit_price_1 = new_variant_1_price * (1 - new_voucher_unit_discount / 100)
+ expected_unit_discount_1 = new_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ # line 2 prices shouldn't be refreshed
+ expected_unit_price_2 = initial_variant_2_price - initial_voucher_unit_discount
+ expected_unit_discount_2 = initial_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.total_price_net_amount == expected_unit_price_1 * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == new_voucher_unit_discount
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == initial_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == initial_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.FIXED
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount
+ == undiscounted_subtotal
+ - expected_discount_amount_1
+ - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_lines_expired_apply_once_per_order_voucher(
+ order_with_lines, voucher, plugins_manager, tax_configuration_flat_rates
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # expire order lines
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ OrderLine.objects.bulk_update([line_1, line_2], ["draft_base_price_expire_at"])
+
+ # change variant 1 pricing to be higher than variant 2
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(6)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing to be lower than variant 1
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(8)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is not the cheapest anymore, so should not have discount applied
+ assert new_variant_1_price > new_variant_2_price
+ expected_unit_discount_1 = 0
+
+ # line 2 is now the cheapest and should have the price discounted by voucher
+ expected_discount_amount_2 = new_variant_2_price * (new_voucher_unit_discount / 100)
+ expected_unit_discount_2 = expected_discount_amount_2 / line_2.quantity
+ expected_unit_price_2 = new_variant_2_price - expected_unit_discount_2
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.total_price_net_amount == new_variant_1_price * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason is None
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+ assert not line_1.discounts.exists()
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == new_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_2 = line_2.discounts.get()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_single_line_expired_apply_once_per_order_voucher_new_cheapest(
+ order_with_lines, voucher, plugins_manager, tax_configuration_flat_rates
+):
+ # Updating expired line 2, which price has changed and is now the cheapest,
+ # should apply the voucher discount to the new cheapest line 2
+ # and delete the discount from line 1
+
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_2 = line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # expire line 2
+ now = timezone.now()
+ line_2.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_2.save(update_fields=["draft_base_price_expire_at"])
+
+ # change variant 2 pricing to be lower than variant 1
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_1_price - Decimal(1)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is not the cheapest anymore, so should not have discount applied
+ assert initial_variant_1_price > new_variant_2_price
+ expected_unit_discount_1 = 0
+
+ # line 2 is now the cheapest and should have the price discounted by voucher
+ expected_discount_amount_2 = new_variant_2_price * (new_voucher_unit_discount / 100)
+ expected_unit_discount_2 = expected_discount_amount_2 / line_2.quantity
+ expected_unit_price_2 = new_variant_2_price - expected_unit_discount_2
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == initial_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == initial_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == initial_variant_1_price
+ assert line_1.total_price_net_amount == initial_variant_1_price * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason is None
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+ assert not line_1.discounts.exists()
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == new_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_2 = line_2.discounts.get()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
+
+
+def test_fetch_order_prices_single_line_expired_apply_once_per_order_voucher_old_cheapest(
+ order_with_lines, voucher, plugins_manager, tax_configuration_flat_rates
+):
+ # Updating expired line 1, which price has changed and is not the cheapest anymore,
+ # should apply the voucher discount to the new cheapest line 2 ,
+ # even though line_2 hasn't expired
+
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ tax_rate = Decimal("1.23")
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1 = line_1.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing to be higher than variant 2
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_2_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # expire line 1
+ now = timezone.now()
+ line_1.draft_base_price_expire_at = now - timedelta(hours=1)
+ line_1.save(update_fields=["draft_base_price_expire_at"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is not the cheapest anymore, so should not have discount applied
+ assert new_variant_1_price > initial_variant_2_price
+ expected_unit_discount_1 = 0
+
+ # line 2 is now the cheapest and should have the price discounted by voucher,
+ # even though line_2 hasn't expired
+ expected_discount_amount_2 = initial_variant_2_price * (
+ new_voucher_unit_discount / 100
+ )
+ expected_unit_discount_2 = expected_discount_amount_2 / line_2.quantity
+ expected_unit_price_2 = initial_variant_2_price - expected_unit_discount_2
+
+ # when
+ order, lines = fetch_order_prices_if_expired(
+ order, plugins_manager, lines=None, force_update=False
+ )
+
+ # then
+ line_1, line_2 = lines
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert (
+ line_1.undiscounted_total_price_net_amount
+ == new_variant_1_price * line_1.quantity
+ )
+ assert line_1.undiscounted_total_price_gross_amount == quantize_price(
+ line_1.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.total_price_net_amount == new_variant_1_price * line_1.quantity
+ assert line_1.total_price_gross_amount == quantize_price(
+ line_1.total_price_net_amount * tax_rate, currency
+ )
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason is None
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+ assert not line_1.discounts.exists()
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert (
+ line_2.undiscounted_total_price_net_amount
+ == initial_variant_2_price * line_2.quantity
+ )
+ assert line_2.undiscounted_total_price_gross_amount == quantize_price(
+ line_2.undiscounted_total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.total_price_net_amount == expected_unit_price_2 * line_2.quantity
+ assert line_2.total_price_gross_amount == quantize_price(
+ line_2.total_price_net_amount * tax_rate, currency
+ )
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
+
+ discount_2 = line_2.discounts.get()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+ undiscounted_subtotal = Decimal(0)
+ for line in lines:
+ undiscounted_subtotal += (
+ line.undiscounted_base_unit_price.amount * line.quantity
+ )
+ shipping_price = order.undiscounted_base_shipping_price_amount
+
+ assert (
+ order.subtotal_net_amount == undiscounted_subtotal - expected_discount_amount_2
+ )
+ assert order.subtotal_gross_amount == quantize_price(
+ order.subtotal_net_amount * tax_rate, currency
+ )
+ assert order.total_net_amount == order.subtotal_net_amount + shipping_price
+ assert order.total_gross_amount == quantize_price(
+ order.total_net_amount * tax_rate, currency
+ )
diff --git a/saleor/order/tests/test_fetch_order_prices_tax_app.py b/saleor/order/tests/test_fetch_order_prices_tax_app.py
index f4bdff291f..59d34d299d 100644
--- a/saleor/order/tests/test_fetch_order_prices_tax_app.py
+++ b/saleor/order/tests/test_fetch_order_prices_tax_app.py
@@ -8,9 +8,13 @@ from ...core.prices import quantize_price
from ...core.taxes import TaxData, TaxLineData
from ...discount import DiscountType, DiscountValueType, VoucherType
from ...discount.models import OrderDiscount, OrderLineDiscount, PromotionRule
+from ...discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from ...plugins.avatax.tests.conftest import plugin_configuration # noqa: F401
from .. import OrderStatus
from ..calculations import fetch_order_prices_if_expired
+from ..utils import update_discount_for_order_line
@pytest.fixture
@@ -396,12 +400,6 @@ def test_fetch_order_prices_order_discount_tax_app(
line_1_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1_undiscounted_unit_price_net - line_1_unit_price_net, currency
- # )
-
assert (
line_2.undiscounted_total_price_net_amount
== line_2_undiscounted_total_price_net
@@ -428,12 +426,6 @@ def test_fetch_order_prices_order_discount_tax_app(
line_2_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
- # assert line_2.unit_discount_amount == quantize_price(
- # line_2_undiscounted_unit_price_net - line_2_unit_price_net, currency
- # )
-
def test_fetch_order_prices_order_discount_tax_app_prices_entered_with_taxes(
order_with_lines_and_order_promotion,
@@ -585,12 +577,6 @@ def test_fetch_order_prices_order_discount_tax_app_prices_entered_with_taxes(
line_1_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1_undiscounted_unit_price_gross - line_1_unit_price_gross, currency
- # )
-
assert line_2.undiscounted_total_price_net_amount == quantize_price(
line_2_undiscounted_total_price_net, currency
)
@@ -620,12 +606,6 @@ def test_fetch_order_prices_order_discount_tax_app_prices_entered_with_taxes(
line_2_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
- # assert line_2.unit_discount_amount == quantize_price(
- # line_2_undiscounted_unit_price_gross - line_2_unit_price_gross, currency
- # )
-
def test_fetch_order_prices_gift_discount_tax_app(
order_with_lines_and_gift_promotion,
@@ -882,16 +862,6 @@ def test_fetch_order_prices_catalogue_and_order_discounts_tax_app(
line_1.unit_price_net_amount * tax_rate, currency
)
- # TODO shopx-1531
- # assert line_1.unit_discount_reason == order_discount.reason
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1_order_discount_portion / line_1.quantity, currency
- # )
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1.undiscounted_unit_price_net_amount - line_1.unit_price_net_amount,
- # currency,
- # )
-
assert catalogue_discount.line == line_2
assert catalogue_discount.amount_value == rule_catalogue_reward * line_2.quantity
assert catalogue_discount.value == rule_catalogue_reward
@@ -938,15 +908,6 @@ def test_fetch_order_prices_catalogue_and_order_discounts_tax_app(
line_2.unit_price_net_amount * tax_rate, currency
)
- # TODO shopx-1531
- # assert line_2.unit_discount_reason == "; ".join(
- # [catalogue_discount.reason, order_discount.reason]
- # )
- # assert line_2.unit_discount_amount == quantize_price(
- # line_2.undiscounted_unit_price_net_amount - line_2.unit_price_net_amount,
- # currency,
- # )
-
shipping_price = order.shipping_price_net_amount
total_net_amount = quantize_price(
order.undiscounted_total_net_amount
@@ -998,6 +959,7 @@ def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app
order.voucher = voucher
order.voucher_code = voucher.codes.first().code
order.save(update_fields=["voucher", "voucher_code"])
+ create_or_update_voucher_discount_objects_for_order(order)
# create manual order discount
manual_reward = Decimal("10")
@@ -1138,7 +1100,9 @@ def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app
== line_1_undiscounted_unit_price_gross
)
- assert line_1.base_unit_price_amount == line_1_base_unit_price
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1_base_unit_price, currency
+ )
assert line_1.total_price_net_amount == line_1_total_price_net
assert line_1.total_price_gross_amount == line_1_total_price_gross
assert line_1.unit_price_net_amount == quantize_price(
@@ -1148,15 +1112,6 @@ def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app
line_1_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert (
- # line_1.unit_discount_reason
- # == f"Voucher code: {order.voucher_code}; {manual_discount_reason}"
- # )
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1_undiscounted_unit_price_net - line_1_unit_price_net, currency
- # )
-
assert (
line_2.undiscounted_total_price_net_amount
== line_2_undiscounted_total_price_net
@@ -1183,12 +1138,6 @@ def test_fetch_order_prices_manual_order_discount_and_line_level_voucher_tax_app
line_2_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_2.unit_discount_reason == manual_discount_reason
- # assert line_2.unit_discount_amount == quantize_price(
- # line_2_undiscounted_unit_price_net - line_2_unit_price_net, currency
- # )
-
manual_discount.refresh_from_db()
assert manual_discount.amount.amount == manual_reward
voucher_discount = line_1.discounts.get()
@@ -1216,15 +1165,16 @@ def test_fetch_order_prices_manual_line_discount_and_entire_order_voucher_tax_ap
order.voucher = voucher
code = voucher.codes.first().code
order.voucher_code = code
+ create_or_update_voucher_discount_objects_for_order(order)
manual_line_discount_value = Decimal("50")
manual_discount_reason = "Manual line discount"
- manual_line_discount = line_1.discounts.create(
+ update_discount_for_order_line(
+ line_1,
+ order=order,
+ reason=manual_discount_reason,
value_type=DiscountValueType.PERCENTAGE,
value=manual_line_discount_value,
- name="Manual line discount",
- type=DiscountType.MANUAL,
- reason=manual_discount_reason,
)
app_tax_rate = Decimal(10)
@@ -1364,15 +1314,6 @@ def test_fetch_order_prices_manual_line_discount_and_entire_order_voucher_tax_ap
line_1_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert (
- # line_1.unit_discount_reason
- # == f"{manual_discount_reason}; Voucher code: {order.voucher_code}"
- # )
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1_undiscounted_unit_price_net - line_1_unit_price_net, currency
- # )
-
assert (
line_2.undiscounted_total_price_net_amount
== line_2_undiscounted_total_price_net
@@ -1399,13 +1340,7 @@ def test_fetch_order_prices_manual_line_discount_and_entire_order_voucher_tax_ap
line_2_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_2.unit_discount_reason == f"Voucher code: {order.voucher_code}"
- # assert line_2.unit_discount_amount == quantize_price(
- # line_2_undiscounted_unit_price_net - line_2_unit_price_net, currency
- # )
-
- manual_line_discount.refresh_from_db()
+ manual_line_discount = line_1.discounts.get()
assert manual_line_discount.amount.amount == manual_line_discount_amount
voucher_discount = order.discounts.get()
assert voucher_discount.amount.amount == voucher_reward
@@ -1432,6 +1367,7 @@ def test_fetch_order_prices_shipping_voucher_and_manual_discount_tax_app(
order.voucher = voucher
code = voucher.codes.first().code
order.voucher_code = code
+ create_or_update_voucher_discount_objects_for_order(order)
manual_discount_value = Decimal("10")
manual_discount_reason = "Manual discount reason"
@@ -1580,12 +1516,6 @@ def test_fetch_order_prices_shipping_voucher_and_manual_discount_tax_app(
line_1_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_1.unit_discount_reason == manual_discount_reason
- # assert line_1.unit_discount_amount == quantize_price(
- # line_1_undiscounted_unit_price_net - line_1_unit_price_net, currency
- # )
-
assert (
line_2.undiscounted_total_price_net_amount
== line_2_undiscounted_total_price_net
@@ -1612,12 +1542,6 @@ def test_fetch_order_prices_shipping_voucher_and_manual_discount_tax_app(
line_2_unit_price_gross, currency
)
- # TODO shopx-1531
- # assert line_2.unit_discount_reason == manual_discount_reason
- # assert line_2.unit_discount_amount == quantize_price(
- # line_2_undiscounted_unit_price_net - line_2_unit_price_net, currency
- # )
-
manual_discount = order.discounts.get(type=DiscountType.MANUAL)
assert manual_discount.amount.amount == manual_discount_amount
@@ -1648,6 +1572,7 @@ def test_fetch_order_prices_entire_order_voucher_no_tax_data_tax_app(
order.voucher = voucher
code = voucher.codes.first().code
order.voucher_code = code
+ create_or_update_voucher_discount_objects_for_order(order)
line_1_undiscounted_unit_price_net = line_1.undiscounted_unit_price_net_amount
line_2_undiscounted_unit_price_net = line_2.undiscounted_unit_price_net_amount
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index d8b23b2c28..e02331d17e 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -657,7 +657,7 @@ def test_order_weight_change_line_quantity(staff_user, lines_info):
line_info,
new_quantity,
line_info.quantity,
- order.channel,
+ order,
get_plugins_manager(allow_replica=False),
)
assert order.weight == _calculate_order_weight_from_lines(order)
@@ -746,7 +746,7 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):
lines_info[1],
lines_info[1].quantity,
0,
- order.channel,
+ order,
get_plugins_manager(allow_replica=False),
)
change_order_line_quantity(
@@ -755,7 +755,7 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):
lines_info[0],
lines_info[0].quantity,
0,
- order.channel,
+ order,
get_plugins_manager(allow_replica=False),
)
assert order.get_total_quantity() == 0
@@ -775,7 +775,7 @@ def test_change_order_line_quantity_changes_total_prices(
line_info,
line_info.quantity,
new_quantity,
- order.channel,
+ order,
get_plugins_manager(allow_replica=False),
)
assert line_info.line.total_price == line_info.line.unit_price * new_quantity
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index ddb5225030..e909d214c2 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -6,13 +6,11 @@ from prices import Money, TaxedMoney
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...discount import DiscountType, DiscountValueType
-from ...discount.interface import VariantPromotionRuleInfo
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCardEvent
from ...graphql.order.utils import OrderLineData
from ...payment import TransactionEventType
from ...plugins.manager import get_plugins_manager
-from ...product.models import VariantChannelListingPromotionRule
from .. import OrderGrantedRefundStatus, OrderStatus
from ..events import OrderEvents
from ..fetch import OrderLineInfo
@@ -22,7 +20,6 @@ from ..utils import (
add_variant_to_order,
calculate_order_granted_refund_status,
change_order_line_quantity,
- create_order_line_discounts,
get_order_country,
get_total_order_discount_excluding_shipping,
get_valid_shipping_methods_for_order,
@@ -75,7 +72,7 @@ def test_change_quantity_generates_proper_event(
line_info,
previous_quantity,
new_quantity,
- order_with_lines.channel,
+ order_with_lines,
get_plugins_manager(allow_replica=False),
)
@@ -127,7 +124,7 @@ def test_change_quantity_update_line_fields(
line_info,
line.quantity,
new_quantity,
- order_with_lines.channel,
+ order_with_lines,
get_plugins_manager(allow_replica=False),
)
@@ -580,95 +577,6 @@ def test_get_order_country_use_channel_country(order):
assert country == order.channel.default_country
-def test_create_order_line_discounts(
- order_line,
- catalogue_promotion,
- promotion_translation_fr,
- promotion_rule_translation_fr,
-):
- # given
- promotion = catalogue_promotion
- rules = promotion.rules.all()
- rule_1 = rules[0]
- rule_2 = rules[1]
-
- order = order_line.order
- variant = order_line.variant
- variant_channel_listing = variant.channel_listings.get(
- channel_id=order_line.order.channel_id
- )
-
- (
- listing_promotion_rule_1,
- listing_promotion_rule_2,
- ) = VariantChannelListingPromotionRule.objects.bulk_create(
- [
- VariantChannelListingPromotionRule(
- variant_channel_listing=variant_channel_listing,
- promotion_rule=rule_1,
- discount_amount=Decimal("10.0"),
- currency=order.currency,
- ),
- VariantChannelListingPromotionRule(
- variant_channel_listing=variant_channel_listing,
- promotion_rule=rule_2,
- discount_amount=Decimal("5.0"),
- currency=order.currency,
- ),
- ]
- )
-
- promotion_rule_translation_fr.promotion_rule = rule_1
- promotion_rule_translation_fr.save(update_fields=["promotion_rule"])
-
- rules_info = [
- VariantPromotionRuleInfo(
- rule=rule_1,
- variant_listing_promotion_rule=listing_promotion_rule_1,
- promotion=promotion,
- promotion_translation=promotion_translation_fr,
- rule_translation=promotion_rule_translation_fr,
- ),
- VariantPromotionRuleInfo(
- rule=rule_2,
- variant_listing_promotion_rule=listing_promotion_rule_2,
- promotion=promotion,
- promotion_translation=promotion_translation_fr,
- rule_translation=None,
- ),
- ]
-
- # when
- line_discounts = create_order_line_discounts(order_line, rules_info)
-
- # then
- assert len(line_discounts) == 2
- discount_1, discount_2 = line_discounts
-
- for discount in [discount_1, discount_2]:
- assert discount.line == order_line
- assert discount.type == DiscountType.PROMOTION
- assert discount.currency == order.currency
- assert discount.reason is None
-
- assert discount_1.amount_value == listing_promotion_rule_1.discount_amount
- assert discount_1.value_type == rule_1.reward_value_type
- assert discount_1.value == rule_1.reward_value
- assert discount_1.name == f"{promotion.name}: {rule_1.name}"
- assert (
- discount_1.translated_name
- == f"{promotion_translation_fr.name}: {promotion_rule_translation_fr.name}"
- )
- assert discount_1.promotion_rule == rule_1
-
- assert discount_2.amount_value == listing_promotion_rule_2.discount_amount
- assert discount_2.value_type == rule_2.reward_value_type
- assert discount_2.value == rule_2.reward_value
- assert discount_2.name == f"{promotion.name}: {rule_2.name}"
- assert discount_2.translated_name == f"{promotion_translation_fr.name}"
- assert discount_2.promotion_rule == rule_2
-
-
@pytest.mark.parametrize(
("expected_granted_status", "event_type"),
[
diff --git a/saleor/order/tests/test_refresh_all_order_base_prices_and_discounts.py b/saleor/order/tests/test_refresh_all_order_base_prices_and_discounts.py
new file mode 100644
index 0000000000..4e3c7b7636
--- /dev/null
+++ b/saleor/order/tests/test_refresh_all_order_base_prices_and_discounts.py
@@ -0,0 +1,612 @@
+from datetime import timedelta
+from decimal import Decimal
+
+import graphene
+import pytest
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ...core.prices import quantize_price
+from ...core.taxes import zero_money
+from ...discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from ...discount.models import OrderLineDiscount, Promotion, PromotionRule
+from ...discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
+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 .. import OrderStatus
+from ..calculations import refresh_all_order_base_prices_and_discounts
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_all_order_base_prices(order_with_lines):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ expire_period = order.channel.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+ expected_expire_time = timezone.now() + timedelta(hours=expire_period)
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.draft_base_price_expire_at == expected_expire_time
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert line_2.base_unit_price_amount == new_variant_2_price
+ assert line_1.draft_base_price_expire_at == expected_expire_time
+
+
+def test_refresh_all_order_base_prices_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ channel = order.channel
+ currency = order.currency
+ promotion = Promotion.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ rule_1 = promotion.rules.get()
+ initial_reward_value_1 = rule_1.reward_value
+ initial_reward_value_type_1 = rule_1.reward_value_type
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ variant_2 = line_2.variant
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ discount_1 = line_1.discounts.first()
+ assert discount_1.value == initial_reward_value_1
+ assert discount_1.value_type == initial_reward_value_type_1
+ assert discount_1.amount_value == initial_reward_value_1 * line_1.quantity
+
+ # prepare new catalog promotion rule for variant 2
+ initial_reward_value_2 = Decimal(5)
+ initial_reward_value_type_2 = DiscountValueType.FIXED
+ rule_2 = promotion.rules.create(
+ name="Rule 2",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=initial_reward_value_type_2,
+ reward_value=initial_reward_value_2,
+ )
+ rule_2.channels.add(channel)
+
+ listing_2 = variant_2.channel_listings.get(channel=channel)
+ listing_2.discounted_price_amount = listing_2.price_amount - initial_reward_value_2
+ listing_2.save(update_fields=["discounted_price_amount"])
+ listing_2.variantlistingpromotionrule.create(
+ promotion_rule=rule_2,
+ discount_amount=initial_reward_value_2,
+ currency=currency,
+ )
+
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=initial_reward_value_2,
+ amount_value=initial_reward_value_2 * line_2.quantity,
+ currency=currency,
+ promotion_rule=rule_2,
+ reason=f"Promotion: {promotion_id}",
+ )
+
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - initial_reward_value_2
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # update promotion rules
+ new_reward_value_1 = Decimal(50)
+ new_reward_value_type_1 = RewardValueType.PERCENTAGE
+ rule_1.reward_value = new_reward_value_1
+ rule_1.reward_value_type = new_reward_value_type_1
+ rule_1.save(update_fields=["reward_value", "reward_value_type"])
+
+ new_reward_value_2 = Decimal(30)
+ new_reward_value_type_2 = RewardValueType.PERCENTAGE
+ rule_2.reward_value = new_reward_value_2
+ rule_2.reward_value_type = new_reward_value_type_2
+ rule_2.save(update_fields=["reward_value", "reward_value_type"])
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ # both lines should have price refreshed
+ undiscounted_unit_price_1 = line_1.undiscounted_base_unit_price_amount
+ expected_unit_price_1 = undiscounted_unit_price_1 * (1 - new_reward_value_1 / 100)
+ expected_unit_discount_1 = undiscounted_unit_price_1 - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ undiscounted_unit_price_2 = line_2.undiscounted_base_unit_price_amount
+ expected_unit_price_2 = undiscounted_unit_price_2 * (1 - new_reward_value_2 / 100)
+ expected_unit_discount_2 = undiscounted_unit_price_2 - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == undiscounted_unit_price_1
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ assert line_2.undiscounted_base_unit_price_amount == undiscounted_unit_price_2
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == new_reward_value_1
+ assert discount_1.value_type == new_reward_value_type_1
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == new_reward_value_2
+ assert discount_2.value_type == new_reward_value_type_2
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+
+def test_refresh_all_order_base_prices_new_catalogue_discount(
+ order_with_lines, catalogue_promotion
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ channel = order.channel
+ currency = order.currency
+ promotion = catalogue_promotion
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ variant_2 = line_2.variant
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ # prepare new catalog promotion rule for variant 2
+ promotion.rules.all().delete()
+ reward_value = Decimal(5)
+ reward_value_type = DiscountValueType.FIXED
+ rule = promotion.rules.create(
+ name="Rule 1",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=reward_value_type,
+ reward_value=reward_value,
+ )
+ rule.channels.add(channel)
+
+ listing_2 = variant_2.channel_listings.get(channel=channel)
+ listing_2.discounted_price_amount = listing_2.price_amount - reward_value
+ listing_2.save(update_fields=["discounted_price_amount"])
+ listing_2.variantlistingpromotionrule.create(
+ promotion_rule=rule,
+ discount_amount=reward_value,
+ currency=currency,
+ )
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ undiscounted_unit_price_1 = line_1.undiscounted_base_unit_price_amount
+ expected_unit_price_1 = undiscounted_unit_price_1
+ expected_unit_discount_1 = 0
+
+ # line 2 should have catalog discount applied
+ undiscounted_unit_price_2 = line_2.undiscounted_base_unit_price_amount
+ expected_unit_price_2 = undiscounted_unit_price_2 - reward_value
+ expected_unit_discount_2 = reward_value
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == undiscounted_unit_price_1
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason is None
+
+ assert line_2.undiscounted_base_unit_price_amount == undiscounted_unit_price_2
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ assert not line_1.discounts.exists()
+
+ discount = line_2.discounts.get()
+ assert discount.value == reward_value
+ assert discount.value_type == reward_value_type
+ assert discount.amount.amount == expected_discount_amount_2
+
+
+def test_refresh_all_order_base_prices_manual_line_discount(order_with_lines):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # add manual discount to line 1
+ discount_1_reward_value = Decimal(20)
+ discount_1_unit_amount = discount_1_reward_value / 100 * initial_variant_1_price
+ discount_1_amount = discount_1_unit_amount * line_1.quantity
+ discount_1 = line_1.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_1_reward_value,
+ amount_value=discount_1_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ )
+ line_1.base_unit_price_amount = (
+ line_1.undiscounted_base_unit_price_amount - discount_1_unit_amount
+ )
+ line_1.save(update_fields=["base_unit_price_amount"])
+
+ # add manual discount to line 2
+ discount_2_reward_value = Decimal(10)
+ discount_2_unit_amount = discount_2_reward_value / 100 * initial_variant_2_price
+ discount_2_amount = discount_2_unit_amount * line_2.quantity
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_2_reward_value,
+ amount_value=discount_2_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ )
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - discount_2_unit_amount
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # both lines should have price refreshed
+ expected_unit_price_1 = new_variant_1_price * (1 - discount_1_reward_value / 100)
+ expected_unit_discount_1 = new_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ expected_unit_price_2 = new_variant_2_price * (1 - discount_2_reward_value / 100)
+ expected_unit_discount_2 = new_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ discount_1.refresh_from_db()
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ discount_2.refresh_from_db()
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+
+def test_refresh_all_order_base_prices_specific_product_voucher(
+ order_with_lines, voucher
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare specific product voucher which cover both line variants
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.set([line_1.variant, line_2.variant])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ line_1, line_2 = order.lines.all()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount * line_1.quantity
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ discount_2 = line_2.discounts.get()
+ discount_amount_2 = initial_voucher_unit_discount * line_2.quantity
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_2.value == initial_voucher_unit_discount
+ assert discount_2.amount_value == discount_amount_2
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(2)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(4)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # both lines should have price refreshed
+ expected_unit_price_1 = new_variant_1_price * (1 - new_voucher_unit_discount / 100)
+ expected_unit_discount_1 = new_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ expected_unit_price_2 = new_variant_2_price * (1 - new_voucher_unit_discount / 100)
+ expected_unit_discount_2 = new_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ discount_1.refresh_from_db()
+ assert discount_1.amount.amount == expected_discount_amount_1
+ assert discount_1.value == new_voucher_unit_discount
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+
+ discount_2.refresh_from_db()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+
+def test_refresh_all_order_base_prices_apply_once_per_order_voucher(
+ order_with_lines, voucher
+):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing to be higher than variant 2
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(6)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing to be lower than variant 1
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(8)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is not the cheapest anymore, so should not have discount applied
+ assert new_variant_1_price > new_variant_2_price
+ expected_unit_discount_1 = 0
+
+ # line 2 is now the cheapest and should have the price discounted by voucher
+ expected_discount_amount_2 = new_variant_2_price * (new_voucher_unit_discount / 100)
+ expected_unit_discount_2 = expected_discount_amount_2 / line_2.quantity
+ expected_unit_price_2 = new_variant_2_price - expected_unit_discount_2
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+ assert not line_1.discounts.exists()
+
+ discount_2 = line_2.discounts.get()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+
+def test_refresh_all_order_base_prices_non_draft_order(order_with_lines):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # when
+ refresh_all_order_base_prices_and_discounts(order)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == initial_variant_1_price
+ assert line_1.base_unit_price_amount == initial_variant_1_price
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert line_2.base_unit_price_amount == initial_variant_2_price
+
+
+def test_refresh_all_order_base_prices_no_lines_no_error(order_with_lines):
+ # given
+ order = order_with_lines
+ order.lines.all().delete()
+
+ # when & then
+ refresh_all_order_base_prices_and_discounts(order)
diff --git a/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py b/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py
new file mode 100644
index 0000000000..f22c767dc5
--- /dev/null
+++ b/saleor/order/tests/test_refresh_order_base_prices_and_discounts.py
@@ -0,0 +1,745 @@
+from datetime import timedelta
+from decimal import Decimal
+
+import graphene
+import pytest
+from django.utils import timezone
+from freezegun import freeze_time
+
+from ...core.prices import quantize_price
+from ...core.taxes import zero_money
+from ...discount import DiscountType, DiscountValueType, RewardValueType, VoucherType
+from ...discount.models import OrderLineDiscount, Promotion, PromotionRule
+from ...discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
+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 .. import OrderStatus
+from ..calculations import refresh_order_base_prices_and_discounts
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_order_base_prices(order_with_lines):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ expire_period = order.channel.draft_order_line_price_freeze_period
+ assert expire_period is not None
+ assert expire_period > 0
+ expected_expire_time = timezone.now() + timedelta(hours=expire_period)
+
+ line_ids_to_refresh = [line_1.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.draft_base_price_expire_at == expected_expire_time
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert line_2.base_unit_price_amount == initial_variant_2_price
+ assert line_2.draft_base_price_expire_at is None
+
+
+def test_refresh_order_base_prices_catalogue_discount(
+ order_with_lines_and_catalogue_promotion,
+):
+ # given
+ order = order_with_lines_and_catalogue_promotion
+ order.status = OrderStatus.DRAFT
+ channel = order.channel
+ currency = order.currency
+ promotion = Promotion.objects.get()
+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)
+ rule_1 = promotion.rules.get()
+ initial_reward_value_1 = rule_1.reward_value
+ initial_reward_value_type_1 = rule_1.reward_value_type
+
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ variant_2 = line_2.variant
+ undiscounted_subtotal = zero_money(currency)
+ for line in lines:
+ undiscounted_subtotal += line.undiscounted_base_unit_price * line.quantity
+
+ discount_1 = line_1.discounts.first()
+ assert discount_1.value == initial_reward_value_1
+ assert discount_1.value_type == initial_reward_value_type_1
+ assert discount_1.amount_value == initial_reward_value_1 * line_1.quantity
+
+ # prepare new catalog promotion rule for variant 2
+ initial_reward_value_2 = Decimal(5)
+ initial_reward_value_type_2 = DiscountValueType.FIXED
+ rule_2 = promotion.rules.create(
+ name="Rule 2",
+ catalogue_predicate={
+ "variantPredicate": {
+ "ids": [graphene.Node.to_global_id("ProductVariant", variant_2.id)]
+ }
+ },
+ reward_value_type=initial_reward_value_type_2,
+ reward_value=initial_reward_value_2,
+ )
+ rule_2.channels.add(channel)
+
+ listing_2 = variant_2.channel_listings.get(channel=channel)
+ listing_2.discounted_price_amount = listing_2.price_amount - initial_reward_value_2
+ listing_2.save(update_fields=["discounted_price_amount"])
+ listing_2.variantlistingpromotionrule.create(
+ promotion_rule=rule_2,
+ discount_amount=initial_reward_value_2,
+ currency=currency,
+ )
+
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.PROMOTION,
+ value_type=RewardValueType.FIXED,
+ value=initial_reward_value_2,
+ amount_value=initial_reward_value_2 * line_2.quantity,
+ currency=currency,
+ promotion_rule=rule_2,
+ reason=f"Promotion: {promotion_id}",
+ )
+
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - initial_reward_value_2
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # update promotion rules
+ new_reward_value_1 = Decimal(50)
+ new_reward_value_type_1 = RewardValueType.PERCENTAGE
+ rule_1.reward_value = new_reward_value_1
+ rule_1.reward_value_type = new_reward_value_type_1
+ rule_1.save(update_fields=["reward_value", "reward_value_type"])
+
+ new_reward_value_2 = Decimal(30)
+ new_reward_value_type_2 = RewardValueType.PERCENTAGE
+ rule_2.reward_value = new_reward_value_2
+ rule_2.reward_value_type = new_reward_value_type_2
+ rule_2.save(update_fields=["reward_value", "reward_value_type"])
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ undiscounted_unit_price_1 = line_1.undiscounted_base_unit_price_amount
+ expected_unit_price_1 = undiscounted_unit_price_1 * (1 - new_reward_value_1 / 100)
+ expected_unit_discount_1 = undiscounted_unit_price_1 - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ # line 2 prices shouldn't be refreshed
+ undiscounted_unit_price_2 = line_2.undiscounted_base_unit_price_amount
+ expected_unit_price_2 = undiscounted_unit_price_2 - initial_reward_value_2
+ expected_unit_discount_2 = initial_reward_value_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ line_ids_to_refresh = [line_1.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == undiscounted_unit_price_1
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+ assert line_1.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ assert line_2.undiscounted_base_unit_price_amount == undiscounted_unit_price_2
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+ assert line_2.unit_discount_reason == f"Promotion: {promotion_id}"
+
+ discount_1.refresh_from_db()
+ assert discount_1.value == new_reward_value_1
+ assert discount_1.value_type == new_reward_value_type_1
+ assert discount_1.amount.amount == expected_discount_amount_1
+
+ discount_2.refresh_from_db()
+ assert discount_2.value == initial_reward_value_2
+ assert discount_2.value_type == initial_reward_value_type_2
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+
+def test_refresh_order_base_prices_manual_line_discount(order_with_lines):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # add manual discount to line 1
+ discount_1_reward_value = Decimal(20)
+ discount_1_unit_amount = discount_1_reward_value / 100 * initial_variant_1_price
+ initial_discount_1_amount = discount_1_unit_amount * line_1.quantity
+ discount_1 = line_1.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_1_reward_value,
+ amount_value=initial_discount_1_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ )
+ line_1.base_unit_price_amount = (
+ line_1.undiscounted_base_unit_price_amount - discount_1_unit_amount
+ )
+ line_1.save(update_fields=["base_unit_price_amount"])
+
+ # add manual discount to line 2
+ discount_2_reward_value = Decimal(10)
+ discount_2_unit_amount = discount_2_reward_value / 100 * initial_variant_2_price
+ initial_discount_2_amount = discount_2_unit_amount * line_2.quantity
+ discount_2 = line_2.discounts.create(
+ type=DiscountType.MANUAL,
+ value_type=DiscountValueType.PERCENTAGE,
+ value=discount_2_reward_value,
+ amount_value=initial_discount_2_amount,
+ currency=currency,
+ unique_type=DiscountType.MANUAL,
+ )
+ line_2.base_unit_price_amount = (
+ line_2.undiscounted_base_unit_price_amount - discount_2_unit_amount
+ )
+ line_2.save(update_fields=["base_unit_price_amount"])
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # line 1 prices shouldn't be refreshed
+ expected_unit_price_1 = initial_variant_1_price * (
+ 1 - discount_1_reward_value / 100
+ )
+ expected_unit_discount_1 = initial_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ expected_unit_price_2 = new_variant_2_price * (1 - discount_2_reward_value / 100)
+ expected_unit_discount_2 = new_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ line_ids_to_refresh = [line_2.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == initial_variant_1_price
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ discount_1.refresh_from_db()
+ assert (
+ discount_1.amount.amount
+ == expected_discount_amount_1
+ == initial_discount_1_amount
+ )
+
+ discount_2.refresh_from_db()
+ assert discount_2.amount.amount == expected_discount_amount_2
+
+
+def test_refresh_order_base_prices_specific_product_voucher(order_with_lines, voucher):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare specific product voucher which cover both line variants
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.SPECIFIC_PRODUCT
+ voucher.save(update_fields=["discount_value_type", "type"])
+ voucher.variants.set([line_1.variant, line_2.variant])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ line_1, line_2 = order.lines.all()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount * line_1.quantity
+ assert (
+ line_1.base_unit_price_amount
+ == line_1.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ discount_2 = line_2.discounts.get()
+ discount_amount_2 = initial_voucher_unit_discount * line_2.quantity
+ assert (
+ line_2.base_unit_price_amount
+ == line_2.undiscounted_base_unit_price_amount - initial_voucher_unit_discount
+ )
+ assert discount_2.value == initial_voucher_unit_discount
+ assert discount_2.amount_value == discount_amount_2
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(2)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(4)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ expected_unit_price_1 = new_variant_1_price * (1 - new_voucher_unit_discount / 100)
+ expected_unit_discount_1 = new_variant_1_price - expected_unit_price_1
+ expected_discount_amount_1 = expected_unit_discount_1 * line_1.quantity
+
+ # line 2 prices shouldn't be refreshed
+ expected_unit_price_2 = initial_variant_2_price - initial_voucher_unit_discount
+ expected_unit_discount_2 = initial_variant_2_price - expected_unit_price_2
+ expected_discount_amount_2 = expected_unit_discount_2 * line_2.quantity
+
+ line_ids_to_refresh = [line_1.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ discount_1.refresh_from_db()
+ assert discount_1.amount.amount == expected_discount_amount_1
+ assert discount_1.value == new_voucher_unit_discount
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+
+ discount_2.refresh_from_db()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == initial_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.FIXED
+
+
+def test_refresh_order_base_prices_apply_once_per_order_voucher_new_cheapest(
+ order_with_lines, voucher
+):
+ # Requesting an update of the line 2, which price has changed and is now the
+ # cheapest, should apply the voucher discount to the new cheapest line 2 and delete
+ # the discount from line 1, even if we didn't request update for line 1
+
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_2 = line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # change variant 2 pricing to be lower than variant 1
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_1_price - Decimal(1)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is not the cheapest anymore, so should not have discount applied
+ assert initial_variant_1_price > new_variant_2_price
+ expected_unit_discount_1 = 0
+
+ # line 2 is now the cheapest and should have the price discounted by voucher
+ expected_discount_amount_2 = new_variant_2_price * (new_voucher_unit_discount / 100)
+ expected_unit_discount_2 = expected_discount_amount_2 / line_2.quantity
+ expected_unit_price_2 = new_variant_2_price - expected_unit_discount_2
+
+ line_ids_to_refresh = [line_2.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == initial_variant_1_price
+ assert line_1.base_unit_price_amount == initial_variant_1_price
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == new_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+ assert not line_1.discounts.exists()
+
+ discount_2 = line_2.discounts.get()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+
+def test_refresh_order_base_prices_apply_once_per_order_voucher_old_cheapest(
+ order_with_lines, voucher
+):
+ # Requesting an update of the line 1, which price has changed and is not the
+ # cheapest anymore, should apply the voucher discount to the new cheapest line 2,
+ # even if we didn't request to update prices for the line 2
+
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1 = line_1.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing to be higher than variant 2
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_2_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is not the cheapest anymore, so should not have discount applied
+ assert new_variant_1_price > initial_variant_2_price
+ expected_unit_discount_1 = 0
+
+ # line 2 is now the cheapest and should have the price discounted by voucher, even there was no request to update
+ # this line
+ expected_discount_amount_2 = initial_variant_2_price * (
+ new_voucher_unit_discount / 100
+ )
+ expected_unit_discount_2 = expected_discount_amount_2 / line_2.quantity
+ expected_unit_price_2 = initial_variant_2_price - expected_unit_discount_2
+
+ line_ids_to_refresh = [line_1.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == new_variant_1_price
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ with pytest.raises(OrderLineDiscount.DoesNotExist):
+ discount_1.refresh_from_db()
+ assert not line_1.discounts.exists()
+
+ discount_2 = line_2.discounts.get()
+ assert discount_2.amount.amount == expected_discount_amount_2
+ assert discount_2.value == new_voucher_unit_discount
+ assert discount_2.value_type == DiscountValueType.PERCENTAGE
+
+
+def test_refresh_order_base_prices_apply_once_per_order_voucher_same_cheapest(
+ order_with_lines, voucher
+):
+ # Requesting an update of the line 1, which price has changed
+ # and is still the cheapest, should update voucher discount
+
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ currency = order.currency
+ line_1, line_2 = order.lines.all()
+ variant_1 = line_1.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # prepare apply once per order voucher
+ voucher.discount_value_type = DiscountValueType.FIXED
+ voucher.type = VoucherType.ENTIRE_ORDER
+ voucher.apply_once_per_order = True
+ voucher.save(update_fields=["discount_value_type", "type", "apply_once_per_order"])
+
+ voucher_listing = voucher.channel_listings.get()
+ initial_voucher_unit_discount = Decimal(1)
+ voucher_listing.discount_value = initial_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+
+ # apply voucher
+ order.voucher = voucher
+ order.voucher_code = voucher.codes.first().code
+ create_or_update_voucher_discount_objects_for_order(order)
+
+ # line 1 is the cheapest so should have the discount applied
+ assert initial_variant_1_price < initial_variant_2_price
+ line_1.refresh_from_db()
+ discount_1 = line_1.discounts.get()
+ discount_amount_1 = initial_voucher_unit_discount
+ unit_discount_amount_1 = discount_amount_1 / line_1.quantity
+ assert quantize_price(line_1.base_unit_price_amount, currency) == quantize_price(
+ line_1.undiscounted_base_unit_price_amount - unit_discount_amount_1, currency
+ )
+ assert discount_1.value == initial_voucher_unit_discount
+ assert discount_1.amount_value == discount_amount_1
+
+ assert not line_2.discounts.exists()
+ assert line_2.base_unit_price_amount == line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing but keep it the cheapest
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price - Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change voucher reward value and type
+ new_voucher_unit_discount = Decimal(25)
+ voucher_listing.discount_value = new_voucher_unit_discount
+ voucher_listing.save(update_fields=["discount_value"])
+ voucher.discount_value_type = DiscountValueType.PERCENTAGE
+ voucher.save(update_fields=["discount_value_type"])
+
+ # line 1 is still the cheapest so should have discount applied
+ assert new_variant_1_price < initial_variant_2_price
+ expected_discount_amount_1 = new_variant_1_price * (new_voucher_unit_discount / 100)
+ expected_unit_discount_1 = expected_discount_amount_1 / line_1.quantity
+ expected_unit_price_1 = new_variant_1_price - expected_unit_discount_1
+
+ # line 2 shouldn't have any discounts applied
+ expected_unit_discount_2 = 0
+ expected_unit_price_2 = initial_variant_2_price
+
+ line_ids_to_refresh = [line_1.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == new_variant_1_price
+ assert line_1.base_unit_price_amount == expected_unit_price_1
+ assert line_1.unit_discount_amount == expected_unit_discount_1
+
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert line_2.base_unit_price_amount == expected_unit_price_2
+ assert line_2.unit_discount_amount == expected_unit_discount_2
+
+ discount_1.refresh_from_db()
+ assert discount_1.amount.amount == expected_discount_amount_1
+ assert discount_1.value == new_voucher_unit_discount
+ assert discount_1.value_type == DiscountValueType.PERCENTAGE
+
+ assert not line_2.discounts.exists()
+
+
+def test_refresh_order_base_prices_non_draft_order(order_with_lines):
+ # given
+ order = order_with_lines
+ order.status = OrderStatus.UNCONFIRMED
+ order.save(update_fields=["status"])
+
+ line_1, line_2 = order.lines.all()
+ variant_1, variant_2 = line_1.variant, line_2.variant
+
+ initial_variant_1_price = line_1.undiscounted_base_unit_price_amount
+ initial_variant_2_price = line_2.undiscounted_base_unit_price_amount
+
+ # change variant 1 pricing
+ channel_listing_1 = variant_1.channel_listings.get()
+ assert initial_variant_1_price == channel_listing_1.price_amount
+ assert initial_variant_1_price == channel_listing_1.discounted_price_amount
+ new_variant_1_price = initial_variant_1_price + Decimal(1)
+ channel_listing_1.price_amount = new_variant_1_price
+ channel_listing_1.discounted_price_amount = new_variant_1_price
+ channel_listing_1.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ # change variant 2 pricing
+ channel_listing_2 = variant_2.channel_listings.get()
+ assert initial_variant_2_price == channel_listing_2.price_amount
+ assert initial_variant_2_price == channel_listing_2.discounted_price_amount
+ new_variant_2_price = initial_variant_2_price - Decimal(2)
+ channel_listing_2.price_amount = new_variant_2_price
+ channel_listing_2.discounted_price_amount = new_variant_2_price
+ channel_listing_2.save(update_fields=["price_amount", "discounted_price_amount"])
+
+ line_ids_to_refresh = [line_1.id, line_2.id]
+
+ # when
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
+
+ # then
+ line_1, line_2 = order.lines.all()
+ assert line_1.undiscounted_base_unit_price_amount == initial_variant_1_price
+ assert line_1.base_unit_price_amount == initial_variant_1_price
+ assert line_2.undiscounted_base_unit_price_amount == initial_variant_2_price
+ assert line_2.base_unit_price_amount == initial_variant_2_price
+
+
+def test_refresh_order_base_prices_no_lines_no_error(order_with_lines):
+ # given
+ order = order_with_lines
+ lines = order.lines.all()
+ line_1, line_2 = lines
+ line_ids_to_refresh = [line_1.id, line_2.id]
+ lines.delete()
+
+ # when & then
+ refresh_order_base_prices_and_discounts(order, line_ids_to_refresh)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 499b1dacf8..a5e7b85b8d 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,5 +1,6 @@
import logging
from collections.abc import Iterable
+from datetime import datetime, timedelta
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
@@ -24,12 +25,22 @@ from ..core.weight import zero_weight
from ..discount import DiscountType, DiscountValueType
from ..discount.models import OrderDiscount, OrderLineDiscount, VoucherType
from ..discount.utils.manual_discount import apply_discount_to_value
+from ..discount.utils.order import (
+ create_order_line_discount_objects_for_catalogue_promotions,
+ update_catalogue_promotion_discount_amount_for_order,
+)
from ..discount.utils.promotion import (
- get_discount_name,
- get_discount_translated_name,
get_sale_id,
prepare_promotion_discount_reason,
)
+from ..discount.utils.voucher import (
+ create_or_update_discount_object_from_order_level_voucher,
+ create_or_update_line_discount_objects_from_voucher,
+ create_or_update_voucher_discount_objects_for_order,
+ is_line_level_voucher,
+ is_order_level_voucher,
+ is_shipping_voucher,
+)
from ..giftcard import events as gift_card_events
from ..giftcard.models import GiftCard
from ..giftcard.search import mark_gift_cards_search_index_as_dirty
@@ -67,13 +78,17 @@ if TYPE_CHECKING:
from ..app.models import App
from ..channel.models import Channel
from ..checkout.fetch import CheckoutInfo
- from ..discount.interface import VariantPromotionRuleInfo
+ from ..graphql.order.utils import OrderLineData
from ..payment.models import Payment, TransactionItem
from ..plugins.manager import PluginsManager
logger = logging.getLogger(__name__)
+def order_qs_select_for_update():
+ return Order.objects.order_by("id").select_for_update(of=(["self"]))
+
+
def order_lines_qs_select_for_update():
return OrderLine.objects.order_by("pk").select_for_update(of=["self"])
@@ -237,6 +252,7 @@ def create_order_line(
variant = line_data.variant
quantity = line_data.quantity
price_override = line_data.price_override
+ is_price_overridden = price_override is not None
rules_info = line_data.rules_info
product = variant.product
@@ -261,7 +277,6 @@ def create_order_line(
total_price = unit_price * quantity
undiscounted_total_price = undiscounted_unit_price * quantity
- tax_class = None
if product.tax_class_id:
tax_class = product.tax_class
else:
@@ -276,6 +291,13 @@ def create_order_line(
translated_product_name = ""
if translated_variant_name == variant_name:
translated_variant_name = ""
+
+ price_expiration_date = (
+ calculate_draft_order_line_price_expiration_date(channel, order.status)
+ if is_price_overridden is False
+ else None
+ )
+
line = order.lines.create(
product_name=product_name,
variant_name=variant_name,
@@ -293,18 +315,23 @@ def create_order_line(
total_price=total_price,
undiscounted_total_price=undiscounted_total_price,
variant=variant,
- is_price_overridden=price_override is not None,
+ is_price_overridden=is_price_overridden,
+ draft_base_price_expire_at=price_expiration_date,
**get_tax_class_kwargs_for_order_line(tax_class),
)
unit_discount = line.undiscounted_unit_price - line.unit_price
if unit_discount.gross:
if rules_info:
- line_discounts = create_order_line_discounts(line, rules_info)
+ line_discounts = (
+ create_order_line_discount_objects_for_catalogue_promotions(
+ line, rules_info, channel
+ )
+ )
promotion = rules_info[0].promotion
line.sale_id = get_sale_id(promotion)
line.unit_discount_reason = (
- prepare_promotion_discount_reason(promotion, line.sale_id)
+ prepare_promotion_discount_reason(rules_info[0].promotion)
if line_discounts
else None
)
@@ -344,44 +371,22 @@ def create_order_line(
manager=manager,
)
- return line
-
-
-def create_order_line_discounts(
- line: "OrderLine", rules_info: Iterable["VariantPromotionRuleInfo"]
-) -> Iterable["OrderLineDiscount"]:
- line_discounts_to_create: list[OrderLineDiscount] = []
- for rule_info in rules_info:
- rule = rule_info.rule
- if not rule_info.variant_listing_promotion_rule:
- continue
- rule_discount_amount = rule_info.variant_listing_promotion_rule.discount_amount
- line_discounts_to_create.append(
- OrderLineDiscount(
- line=line,
- type=DiscountType.PROMOTION,
- value_type=rule.reward_value_type,
- value=rule.reward_value,
- amount_value=rule_discount_amount,
- currency=line.currency,
- name=get_discount_name(rule, rule_info.promotion),
- translated_name=get_discount_translated_name(rule_info),
- reason=None,
- promotion_rule=rule,
- )
+ if is_line_level_voucher(order.voucher):
+ create_or_update_voucher_discount_objects_for_order(
+ order, use_denormalized_data=True
)
- return OrderLineDiscount.objects.bulk_create(line_discounts_to_create)
+ return line
@traced_atomic_transaction()
def add_variant_to_order(
- order,
- line_data,
- user,
- app,
- manager,
- allocate_stock=False,
+ order: Order,
+ line_data: "OrderLineData",
+ user: Optional["User"],
+ app: Optional["App"],
+ manager: "PluginsManager",
+ allocate_stock: bool = False,
) -> OrderLine:
"""Add total_quantity of variant to order.
@@ -389,7 +394,8 @@ def add_variant_to_order(
"""
channel = order.channel
- if line_data.line_id:
+ is_new_line = not line_data.line_id
+ if not is_new_line:
line = order.lines.get(pk=line_data.line_id)
old_quantity = line.quantity
new_quantity = old_quantity + line_data.quantity
@@ -406,7 +412,7 @@ def add_variant_to_order(
line_info,
old_quantity,
new_quantity,
- channel,
+ order,
manager=manager,
send_event=False,
update_fields=update_fields,
@@ -459,7 +465,7 @@ def update_line_base_unit_prices_with_custom_price(
line.undiscounted_base_unit_price_amount = price_override
line.undiscounted_unit_price_gross_amount = price_override
line.undiscounted_unit_price_net_amount = price_override
-
+ line.draft_base_price_expire_at = None
update_fields.extend(
[
"is_price_overridden",
@@ -467,6 +473,7 @@ def update_line_base_unit_prices_with_custom_price(
"base_unit_price_amount",
"undiscounted_unit_price_gross_amount",
"undiscounted_unit_price_net_amount",
+ "draft_base_price_expire_at",
]
)
@@ -572,18 +579,20 @@ def _update_allocations_for_line(
def change_order_line_quantity(
- user,
- app,
- line_info,
+ user: Optional["User"],
+ app: Optional["App"],
+ line_info: OrderLineInfo,
old_quantity: int,
new_quantity: int,
- channel: "Channel",
+ order: "Order",
manager: "PluginsManager",
- send_event=True,
- update_fields=None,
+ send_event: bool = True,
+ update_fields: list[str] | None = None,
):
"""Change the quantity of ordered items in a order line."""
line = line_info.line
+ channel = order.channel
+ currency = channel.currency_code
if new_quantity:
if line.order.is_unconfirmed():
_update_allocations_for_line(
@@ -592,9 +601,9 @@ def change_order_line_quantity(
line.quantity = new_quantity
total_price_net_amount = line.quantity * line.unit_price_net_amount
total_price_gross_amount = line.quantity * line.unit_price_gross_amount
- line.total_price_net_amount = total_price_net_amount.quantize(Decimal("0.001"))
- line.total_price_gross_amount = total_price_gross_amount.quantize(
- Decimal("0.001")
+ line.total_price_net_amount = quantize_price(total_price_net_amount, currency)
+ line.total_price_gross_amount = quantize_price(
+ total_price_gross_amount, currency
)
undiscounted_total_price_gross_amount = (
line.quantity * line.undiscounted_unit_price_gross_amount
@@ -602,11 +611,11 @@ def change_order_line_quantity(
undiscounted_total_price_net_amount = (
line.quantity * line.undiscounted_unit_price_net_amount
)
- line.undiscounted_total_price_gross_amount = (
- undiscounted_total_price_gross_amount.quantize(Decimal("0.001"))
+ line.undiscounted_total_price_gross_amount = quantize_price(
+ undiscounted_total_price_gross_amount, currency
)
- line.undiscounted_total_price_net_amount = (
- undiscounted_total_price_net_amount.quantize(Decimal("0.001"))
+ line.undiscounted_total_price_net_amount = quantize_price(
+ undiscounted_total_price_net_amount, currency
)
fields = [
"quantity",
@@ -619,6 +628,19 @@ def change_order_line_quantity(
update_fields.extend(fields)
else:
line.save(update_fields=fields)
+
+ if catalogue_discount := line.discounts.filter(
+ type=DiscountType.PROMOTION
+ ).first():
+ update_catalogue_promotion_discount_amount_for_order(
+ catalogue_discount, line, new_quantity, currency
+ )
+
+ if is_line_level_voucher(order.voucher):
+ create_or_update_voucher_discount_objects_for_order(
+ order, use_denormalized_data=True
+ )
+
else:
delete_order_line(line_info, manager)
@@ -844,24 +866,30 @@ def create_order_discount_for_order(
new_amount = quantize_price((current_total - gross_total).gross, currency)
kwargs = {} if not type else {"type": type}
- order_discount = order.discounts.create(
- value_type=value_type,
- value=value,
- reason=reason,
- amount=new_amount, # type: ignore[misc]
- **kwargs,
- )
+ with transaction.atomic():
+ # Manual order discount does not stack with other order-level discounts
+ order.discounts.exclude(voucher__type=VoucherType.SHIPPING).delete()
+ order_discount = order.discounts.create(
+ value_type=value_type,
+ value=value,
+ reason=reason,
+ amount=new_amount, # type: ignore[misc]
+ **kwargs,
+ )
+
return order_discount
def remove_order_discount_from_order(order: Order, order_discount: OrderDiscount):
"""Remove the order discount from order and update the prices."""
- discount_amount = order_discount.amount
order_discount.delete()
- order.total += discount_amount
- order.save(update_fields=["total_net_amount", "total_gross_amount", "updated_at"])
+ # Manual discounts take precedence over vouchers, overriding them when applied.
+ # However, this does not entirely dissociate the voucher from the order.
+ # If the manual discount is removed, the voucher is reevaluated.
+ if order.voucher:
+ create_or_update_discount_object_from_order_level_voucher(order)
def update_discount_for_order_line(
@@ -872,9 +900,6 @@ def update_discount_for_order_line(
value: Decimal | None,
):
"""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
@@ -943,7 +968,7 @@ def _update_manual_order_line_discount_object(
for discount in discounts:
if discount.type == DiscountType.MANUAL and not discount_to_update:
discount_to_update = discount
- elif discount.type != DiscountType.VOUCHER:
+ else:
discount_to_delete_ids.append(discount.pk)
if discount_to_delete_ids:
@@ -1007,6 +1032,20 @@ def remove_discount_from_order_line(order_line: OrderLine, order: "Order"):
)
order_line.discounts.all().delete()
+ # Manual discounts take precedence over vouchers, overriding them when applied.
+ # However, this does not entirely dissociate the voucher from the order.
+ # If the manual discount is removed, the voucher is reevaluated.
+ voucher = order.voucher
+ if (
+ voucher
+ and not is_order_level_voucher(voucher)
+ and not is_shipping_voucher(voucher)
+ ):
+ lines_info = fetch_draft_order_lines_info(order)
+ create_or_update_line_discount_objects_from_voucher(lines_info)
+ lines = [line_info.line for line_info in lines_info]
+ OrderLine.objects.bulk_update(lines, ["base_unit_price_amount"])
+
def update_order_charge_status(order: Order, granted_refund_amount: Decimal):
"""Update the current charge status for the order.
@@ -1305,16 +1344,6 @@ def order_info_for_logs(order: Order, lines: Iterable[OrderLine]):
"total_price_net_amount": line_info.line.total_price_net_amount,
"total_price_gross_amount": line_info.line.total_price_gross_amount,
"has_voucher_code": bool(line_info.line.voucher_code),
- "variant_listing_price": (
- line_info.channel_listing.price_amount
- if line_info.channel_listing
- else None
- ),
- "variant_listing_discounted_price": (
- line_info.channel_listing.discounted_price_amount
- if line_info.channel_listing
- else None
- ),
"unit_discount_amount": line_info.line.unit_discount_amount,
"unit_discount_type": line_info.line.unit_discount_type,
"unit_discount_reason": line_info.line.unit_discount_reason,
@@ -1377,3 +1406,16 @@ def store_user_addresses_from_draft_order(order, manager):
order.save(
update_fields=["draft_save_billing_address", "draft_save_shipping_address"]
)
+
+
+def calculate_draft_order_line_price_expiration_date(
+ channel: "Channel", order_status: str
+) -> datetime | None:
+ """Calculate datetime, when order line base prices should be refreshed."""
+ if order_status != OrderStatus.DRAFT:
+ return None
+ freeze_period = channel.draft_order_line_price_freeze_period
+ if freeze_period is not None and freeze_period > 0:
+ now = timezone.now()
+ return now + timedelta(hours=freeze_period)
+ return None
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index c358492c47..0644231f99 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -195,10 +195,7 @@ def update_variant_relations_for_active_promotion_rules_task():
# in the promotion as dirty
existing_variant_relation = _get_existing_rule_variant_list(rules)
- new_rule_to_variant_list = fetch_variants_for_promotion_rules(
- rules=rules,
- database_connection_name=settings.DATABASE_CONNECTION_REPLICA_NAME,
- )
+ new_rule_to_variant_list = fetch_variants_for_promotion_rules(rules=rules)
channel_to_product_map = _get_channel_to_products_map(
existing_variant_relation + new_rule_to_variant_list
)
diff --git a/saleor/product/tests/fixtures/variant.py b/saleor/product/tests/fixtures/variant.py
index 9812c9175f..2f998eecff 100644
--- a/saleor/product/tests/fixtures/variant.py
+++ b/saleor/product/tests/fixtures/variant.py
@@ -121,7 +121,7 @@ def variant_on_promotion(
variant_channel_listing = product_variant.channel_listings.get(channel=channel_USD)
variant_channel_listing.discounted_price_amount = (
- variant_channel_listing.price_amount - reward_value
+ variant_channel_listing.price_amount - discount_amount
)
variant_channel_listing.save(update_fields=["discounted_price_amount"])
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
index e9878ed01b..23766dc04d 100644
--- a/saleor/product/utils/variants.py
+++ b/saleor/product/utils/variants.py
@@ -53,10 +53,7 @@ def get_variant_selection_attributes(
]
-def fetch_variants_for_promotion_rules(
- rules: QuerySet[PromotionRule],
- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
-):
+def fetch_variants_for_promotion_rules(rules: QuerySet[PromotionRule]):
from ...graphql.discount.utils import get_variants_for_catalogue_predicate
PromotionRuleVariant = PromotionRule.variants.through
diff --git a/saleor/tax/tests/test_order_calculations.py b/saleor/tax/tests/test_order_calculations.py
index 00483cb757..8b1d5d4282 100644
--- a/saleor/tax/tests/test_order_calculations.py
+++ b/saleor/tax/tests/test_order_calculations.py
@@ -8,7 +8,7 @@ from ...core.prices import quantize_price
from ...core.taxes import zero_money, zero_taxed_money
from ...discount import DiscountType, DiscountValueType
from ...order import OrderStatus
-from ...order.base_calculations import apply_order_discounts
+from ...order.base_calculations import calculate_prices
from ...order.calculations import fetch_order_prices_if_expired
from ...order.models import OrderLine
from ...order.utils import get_order_country
@@ -164,7 +164,7 @@ def test_calculations_calculate_order_total_voucher(order_with_lines_untaxed, vo
amount_value=10,
voucher=voucher,
)
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
# when
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
@@ -193,7 +193,7 @@ def test_calculations_calculate_order_total_with_manual_discount(
currency=order.currency,
amount_value=10,
)
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
# when
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
@@ -248,7 +248,7 @@ def test_calculations_calculate_order_total_with_discount_for_subtotal_and_shipp
currency=order.currency,
amount_value=75,
)
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
# when
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
@@ -313,7 +313,7 @@ def test_calculations_calculate_order_total_with_manual_discount_and_voucher(
amount_value=10,
voucher=voucher,
)
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
# when
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
@@ -340,7 +340,7 @@ def test_calculate_order_shipping(order_line, shipping_zone):
order.undiscounted_base_shipping_price = base_shipping_price
order.save()
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
# when
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
@@ -400,7 +400,7 @@ def test_calculate_order_shipping_voucher_on_shipping(
shipping_channel_listings = method.channel_listings.get(channel=channel)
shipping_price = shipping_channel_listings.price
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
# when
update_order_prices_with_flat_rates(order, lines, prices_entered_with_tax)
@@ -516,7 +516,7 @@ def test_update_taxes_for_order_lines_voucher_on_entire_order(
)
# when
- apply_order_discounts(order, lines)
+ calculate_prices(order, lines)
lines, _ = update_taxes_for_order_lines(
order, lines, country_code, Decimal(23), prices_entered_with_tax
)
diff --git a/saleor/tests/e2e/orders/discounts/test_manual_order_discount_and_voucher.py b/saleor/tests/e2e/orders/discounts/test_manual_order_discount_and_voucher.py
index 5d7b8bfc6c..18040b26f7 100644
--- a/saleor/tests/e2e/orders/discounts/test_manual_order_discount_and_voucher.py
+++ b/saleor/tests/e2e/orders/discounts/test_manual_order_discount_and_voucher.py
@@ -205,7 +205,7 @@ def test_manual_order_discount_with_entire_order_voucher_CORE_0940(
assert order_data["voucher"]["codes"]["edges"][0]["node"]["code"] == voucher_code
assert order_data["voucher"]["codes"]["edges"][0]["node"]["used"] == 1
- # Step 3 - dd manual order discountA
+ # Step 3 - Add manual order discount
# Manual discount should override voucher
manual_discount_amount = Decimal(20)
manual_discount_reason = "Staff discount"
diff --git a/saleor/tests/e2e/orders/test_draft_order_update_uses_denormalized_prices.py b/saleor/tests/e2e/orders/test_draft_order_update_uses_denormalized_prices.py
new file mode 100644
index 0000000000..9176bd7ded
--- /dev/null
+++ b/saleor/tests/e2e/orders/test_draft_order_update_uses_denormalized_prices.py
@@ -0,0 +1,353 @@
+from decimal import Decimal
+
+import pytest
+
+from ....core.prices import quantize_price
+from ....discount.models import 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 .. import DEFAULT_ADDRESS
+from ..product.utils import create_product_variant_channel_listing
+from ..product.utils.preparing_product import prepare_product
+from ..promotions.utils import (
+ create_promotion,
+ create_promotion_rule,
+ update_promotion_rule,
+)
+from ..shipping_zone.utils import (
+ create_shipping_method,
+ create_shipping_method_channel_listing,
+)
+from ..shop.utils import prepare_shop
+from ..taxes.utils import update_country_tax_rates
+from ..utils import assign_permissions
+from .utils import (
+ draft_order_create,
+ draft_order_update,
+ order_line_delete,
+ order_lines_create,
+)
+
+
+def test_draft_order_update_uses_denormalized_prices_CORE_0251(
+ e2e_staff_api_client,
+ shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+ permission_manage_orders,
+):
+ permissions = [
+ *shop_permissions,
+ permission_manage_product_types_and_attributes,
+ permission_manage_discounts,
+ permission_manage_orders,
+ ]
+ assign_permissions(e2e_staff_api_client, permissions)
+
+ tax_settings = {
+ "charge_taxes": True,
+ "tax_calculation_strategy": "FLAT_RATES",
+ "prices_entered_with_tax": False,
+ }
+ initial_shipping_price = Decimal(10)
+ currency = "USD"
+ shop_data, _tax_config = prepare_shop(
+ e2e_staff_api_client,
+ channels=[
+ {
+ "shipping_zones": [
+ {
+ "countries": ["US"],
+ "shipping_methods": [
+ {
+ "name": "Inpost",
+ "add_channels": {"price": initial_shipping_price},
+ }
+ ],
+ },
+ ],
+ "order_settings": {
+ "includeDraftOrderInVoucherUsage": True,
+ },
+ }
+ ],
+ tax_settings=tax_settings,
+ )
+ channel_id = shop_data[0]["id"]
+ warehouse_id = shop_data[0]["warehouse_id"]
+ shipping_zone_id = shop_data[0]["shipping_zones"][0]["id"]
+ initial_shipping_method_id = shop_data[0]["shipping_zones"][0]["shipping_methods"][
+ 0
+ ]["id"]
+
+ tax_rate = Decimal("1.1")
+ update_country_tax_rates(
+ e2e_staff_api_client,
+ "US",
+ [{"rate": (tax_rate - 1) * 100}],
+ )
+
+ (
+ product_id,
+ variant_id,
+ initial_variant_price,
+ ) = prepare_product(
+ e2e_staff_api_client, warehouse_id, channel_id, variant_price=Decimal(20)
+ )
+ initial_variant_price = Decimal(initial_variant_price)
+
+ promotion_name = "Promotion Fixed"
+ initial_discount_reward = Decimal(5)
+ discount_type = "FIXED"
+ promotion_rule_name = "rule for product"
+ promotion_type = "CATALOGUE"
+
+ promotion_data = create_promotion(
+ e2e_staff_api_client, promotion_name, promotion_type
+ )
+ promotion_id = promotion_data["id"]
+
+ catalogue_predicate = {"productPredicate": {"ids": [product_id]}}
+ input = {
+ "promotion": promotion_id,
+ "channels": [channel_id],
+ "name": promotion_rule_name,
+ "cataloguePredicate": catalogue_predicate,
+ "rewardValue": initial_discount_reward,
+ "rewardValueType": discount_type,
+ }
+ promotion_rule = create_promotion_rule(
+ e2e_staff_api_client,
+ input,
+ )
+ promotion_rule_id = promotion_rule["id"]
+
+ # update prices
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ # Step 1 - Create a draft order for a product with fixed promotion
+ initial_quantity = Decimal(2)
+ input = {
+ "channelId": channel_id,
+ "billingAddress": DEFAULT_ADDRESS,
+ "shippingAddress": DEFAULT_ADDRESS,
+ "shippingMethod": initial_shipping_method_id,
+ "lines": [{"variantId": variant_id, "quantity": initial_quantity}],
+ }
+ data = draft_order_create(e2e_staff_api_client, input)
+
+ undisocunted_unit_price = initial_variant_price
+ unit_price = undisocunted_unit_price - initial_discount_reward
+ undiscounted_line_total = quantize_price(
+ undisocunted_unit_price * initial_quantity, currency
+ )
+ line_total = quantize_price(unit_price * initial_quantity, currency)
+ undiscounted_total = undiscounted_line_total + initial_shipping_price
+ total = line_total + initial_shipping_price
+
+ order_data = data["order"]
+ order_id = order_data["id"]
+ assert not order_data["discounts"]
+ assert order_data["shippingPrice"]["net"]["amount"] == initial_shipping_price
+ assert order_data["shippingPrice"]["gross"]["amount"] == quantize_price(
+ initial_shipping_price * tax_rate, currency
+ )
+ assert order_data["total"]["net"]["amount"] == total
+ assert order_data["total"]["gross"]["amount"] == quantize_price(
+ total * tax_rate, currency
+ )
+ assert order_data["undiscountedTotal"]["net"]["amount"] == undiscounted_total
+ assert order_data["undiscountedTotal"]["gross"]["amount"] == quantize_price(
+ undiscounted_total * tax_rate, currency
+ )
+
+ assert len(order_data["lines"]) == 1
+ line_data = order_data["lines"][0]
+ line_id = line_data["id"]
+ assert line_data["unitPrice"]["net"]["amount"] == unit_price
+ assert line_data["unitPrice"]["gross"]["amount"] == quantize_price(
+ unit_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedUnitPrice"]["net"]["amount"] == undisocunted_unit_price
+ )
+ assert line_data["undiscountedUnitPrice"]["gross"]["amount"] == quantize_price(
+ undisocunted_unit_price * tax_rate, currency
+ )
+ assert line_data["totalPrice"]["net"]["amount"] == line_total
+ assert line_data["totalPrice"]["gross"]["amount"] == quantize_price(
+ line_total * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedTotalPrice"]["net"]["amount"] == undiscounted_line_total
+ )
+ assert line_data["undiscountedTotalPrice"]["gross"]["amount"] == quantize_price(
+ undiscounted_line_total * tax_rate, currency
+ )
+ assert line_data["unitDiscount"]["amount"] == initial_discount_reward
+ assert line_data["unitDiscountReason"] == f"Promotion: {promotion_id}"
+
+ # Step 2 - Update channel listing for variant
+ new_variant_price = initial_variant_price - Decimal(2)
+ data = create_product_variant_channel_listing(
+ e2e_staff_api_client, variant_id, channel_id, new_variant_price
+ )
+ assert data["channelListings"][0]["price"]["amount"] != initial_variant_price
+ assert data["channelListings"][0]["channel"]["id"] == channel_id
+
+ # Step 3 - Update promotion rule reward
+ new_discount_reward = Decimal(7)
+ input = {"rewardValue": new_discount_reward}
+ update_promotion_rule(e2e_staff_api_client, promotion_rule_id, input)
+
+ fetch_variants_for_promotion_rules(PromotionRule.objects.all())
+ update_discounted_prices_for_promotion(Product.objects.all())
+
+ # Step 4 - Create new shipping method
+ data = create_shipping_method(e2e_staff_api_client, shipping_zone_id)
+ new_shipping_method_id = data["id"]
+
+ # Step 5 - Update new shipping method price
+ new_shipping_price = Decimal(15)
+ data = create_shipping_method_channel_listing(
+ e2e_staff_api_client,
+ new_shipping_method_id,
+ channel_id,
+ {"price": new_shipping_price},
+ )
+ assert data["channelListings"][0]["price"]["amount"] == new_shipping_price
+
+ # Step 6 - Update order shipping method what leads to price recalculation.
+ # Base variant prices shouldn't be updated
+ data = draft_order_update(
+ e2e_staff_api_client, order_id, {"shippingMethod": new_shipping_method_id}
+ )
+ undisocunted_unit_price = initial_variant_price
+ unit_price = undisocunted_unit_price - initial_discount_reward
+ undiscounted_line_total = quantize_price(
+ undisocunted_unit_price * initial_quantity, currency
+ )
+ line_total = quantize_price(unit_price * initial_quantity, currency)
+ undiscounted_total = undiscounted_line_total + new_shipping_price
+ total = line_total + new_shipping_price
+
+ order_data = data["order"]
+ assert not order_data["discounts"]
+ assert order_data["shippingPrice"]["net"]["amount"] == new_shipping_price
+ assert order_data["shippingPrice"]["gross"]["amount"] == quantize_price(
+ new_shipping_price * tax_rate, currency
+ )
+ assert order_data["total"]["net"]["amount"] == total
+ assert order_data["total"]["gross"]["amount"] == quantize_price(
+ total * tax_rate, currency
+ )
+ assert order_data["undiscountedTotal"]["net"]["amount"] == undiscounted_total
+ assert order_data["undiscountedTotal"]["gross"]["amount"] == quantize_price(
+ undiscounted_total * tax_rate, currency
+ )
+
+ assert len(order_data["lines"]) == 1
+ line_data = order_data["lines"][0]
+ assert line_data["unitPrice"]["net"]["amount"] == unit_price
+ assert line_data["unitPrice"]["gross"]["amount"] == quantize_price(
+ unit_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedUnitPrice"]["net"]["amount"] == undisocunted_unit_price
+ )
+ assert line_data["undiscountedUnitPrice"]["gross"]["amount"] == quantize_price(
+ undisocunted_unit_price * tax_rate, currency
+ )
+ assert line_data["totalPrice"]["net"]["amount"] == line_total
+ assert line_data["totalPrice"]["gross"]["amount"] == quantize_price(
+ line_total * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedTotalPrice"]["net"]["amount"] == undiscounted_line_total
+ )
+ assert line_data["undiscountedTotalPrice"]["gross"]["amount"] == quantize_price(
+ undiscounted_line_total * tax_rate, currency
+ )
+ assert line_data["unitDiscount"]["amount"] == initial_discount_reward
+ assert line_data["unitDiscountReason"] == f"Promotion: {promotion_id}"
+
+ # Step 7 - Delete the order line
+ data = order_line_delete(e2e_staff_api_client, line_id)
+
+ undiscounted_total = new_shipping_price
+ total = new_shipping_price
+
+ order_data = data["order"]
+ assert order_data["shippingPrice"]["net"]["amount"] == new_shipping_price
+ assert order_data["shippingPrice"]["gross"]["amount"] == quantize_price(
+ new_shipping_price * tax_rate, currency
+ )
+ assert order_data["total"]["net"]["amount"] == total
+ assert order_data["total"]["gross"]["amount"] == quantize_price(
+ total * tax_rate, currency
+ )
+ assert order_data["undiscountedTotal"]["net"]["amount"] == undiscounted_total
+ assert order_data["undiscountedTotal"]["gross"]["amount"] == quantize_price(
+ undiscounted_total * tax_rate, currency
+ )
+ assert not order_data["lines"]
+
+ # Step 8 - Add the order line again. Prices should be taken from current
+ # channel listing values
+ new_quantity = 3
+ lines = [
+ {"variantId": variant_id, "quantity": new_quantity},
+ ]
+ data = order_lines_create(e2e_staff_api_client, order_id, lines)
+
+ undisocunted_unit_price = new_variant_price
+ unit_price = undisocunted_unit_price - new_discount_reward
+ undiscounted_line_total = quantize_price(
+ undisocunted_unit_price * new_quantity, currency
+ )
+ line_total = quantize_price(unit_price * new_quantity, currency)
+ undiscounted_total = undiscounted_line_total + new_shipping_price
+ total = line_total + new_shipping_price
+
+ order_data = data["order"]
+ assert not order_data["discounts"]
+ assert order_data["shippingPrice"]["net"]["amount"] == new_shipping_price
+ assert order_data["shippingPrice"]["gross"]["amount"] == quantize_price(
+ new_shipping_price * tax_rate, currency
+ )
+ assert order_data["total"]["net"]["amount"] == total
+ assert Decimal(str(order_data["total"]["gross"]["amount"])) == quantize_price(
+ total * tax_rate, currency
+ )
+ assert order_data["undiscountedTotal"]["net"]["amount"] == undiscounted_total
+ assert Decimal(
+ str(order_data["undiscountedTotal"]["gross"]["amount"])
+ ) == quantize_price(undiscounted_total * tax_rate, currency)
+
+ assert len(order_data["lines"]) == 1
+ line_data = order_data["lines"][0]
+ assert line_data["unitPrice"]["net"]["amount"] == unit_price
+ assert Decimal(str(line_data["unitPrice"]["gross"]["amount"])) == quantize_price(
+ unit_price * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedUnitPrice"]["net"]["amount"] == undisocunted_unit_price
+ )
+ assert Decimal(
+ str(line_data["undiscountedUnitPrice"]["gross"]["amount"])
+ ) == quantize_price(undisocunted_unit_price * tax_rate, currency)
+ assert line_data["totalPrice"]["net"]["amount"] == line_total
+ assert Decimal(str(line_data["totalPrice"]["gross"]["amount"])) == quantize_price(
+ line_total * tax_rate, currency
+ )
+ assert (
+ line_data["undiscountedTotalPrice"]["net"]["amount"] == undiscounted_line_total
+ )
+ assert Decimal(
+ str(line_data["undiscountedTotalPrice"]["gross"]["amount"])
+ ) == quantize_price(undiscounted_line_total * tax_rate, currency)
+ assert line_data["unitDiscount"]["amount"] == new_discount_reward
+ assert line_data["unitDiscountReason"] == f"Promotion: {promotion_id}"
diff --git a/saleor/tests/e2e/orders/utils/draft_order_create.py b/saleor/tests/e2e/orders/utils/draft_order_create.py
index f10eeefccb..fa0979c907 100644
--- a/saleor/tests/e2e/orders/utils/draft_order_create.py
+++ b/saleor/tests/e2e/orders/utils/draft_order_create.py
@@ -46,6 +46,7 @@ mutation OrderDraftCreate($input: DraftOrderCreateInput!) {
... BaseTaxedMoney
}
lines {
+ id
productVariantId
quantity
undiscountedUnitPrice {
@@ -60,6 +61,10 @@ mutation OrderDraftCreate($input: DraftOrderCreateInput!) {
totalPrice {
... BaseTaxedMoney
}
+ unitDiscount {
+ amount
+ }
+ unitDiscountReason
}
}
}
diff --git a/saleor/tests/e2e/orders/utils/draft_order_update.py b/saleor/tests/e2e/orders/utils/draft_order_update.py
index b719cde4dd..4d3230d1ba 100644
--- a/saleor/tests/e2e/orders/utils/draft_order_update.py
+++ b/saleor/tests/e2e/orders/utils/draft_order_update.py
@@ -12,11 +12,20 @@ mutation DraftOrderUpdate($input: DraftOrderInput!, $id: ID!) {
id
lines {
id
- totalPrice {
- ...BaseTaxedMoney
+ undiscountedUnitPrice {
+ ... BaseTaxedMoney
}
unitPrice {
- ...BaseTaxedMoney
+ ... BaseTaxedMoney
+ }
+ undiscountedTotalPrice {
+ ... BaseTaxedMoney
+ }
+ totalPrice {
+ ... BaseTaxedMoney
+ }
+ unitDiscount {
+ amount
}
unitDiscountReason
}
diff --git a/saleor/tests/e2e/orders/utils/order_line_delete.py b/saleor/tests/e2e/orders/utils/order_line_delete.py
index 1754e1b5c7..4682956b52 100644
--- a/saleor/tests/e2e/orders/utils/order_line_delete.py
+++ b/saleor/tests/e2e/orders/utils/order_line_delete.py
@@ -21,6 +21,9 @@ mutation orderLineDelete($lineId: ID!) {
...BaseTaxedMoney
}
isShippingRequired
+ shippingPrice {
+ ...BaseTaxedMoney
+ }
lines {
id
quantity
diff --git a/saleor/tests/e2e/orders/utils/order_lines_create.py b/saleor/tests/e2e/orders/utils/order_lines_create.py
index a9f3d4dc07..b2ef5f01db 100644
--- a/saleor/tests/e2e/orders/utils/order_lines_create.py
+++ b/saleor/tests/e2e/orders/utils/order_lines_create.py
@@ -23,6 +23,9 @@ mutation orderLinesCreate($id: ID!, $input: [OrderLineCreateInput!]!) {
subtotal {
...BaseTaxedMoney
}
+ undiscountedTotal {
+ ...BaseTaxedMoney
+ }
isShippingRequired
lines {
id
@@ -43,9 +46,10 @@ mutation orderLinesCreate($id: ID!, $input: [OrderLineCreateInput!]!) {
amount
}
undiscountedUnitPrice {
- gross {
- amount
- }
+ ...BaseTaxedMoney
+ }
+ undiscountedTotalPrice {
+ ...BaseTaxedMoney
}
undiscountedTotalPrice {
gross {
diff --git a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
index 93a92b7347..d51820e2ed 100644
--- a/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
+++ b/saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_taxes.py
@@ -15,6 +15,9 @@ from ....discount import (
VoucherType,
)
from ....discount.models import PromotionRule
+from ....discount.utils.voucher import (
+ create_or_update_voucher_discount_objects_for_order,
+)
from ....graphql.core.utils import to_global_id_or_none
from ....order import OrderStatus
from ....order.calculations import fetch_order_prices_if_expired
@@ -924,6 +927,7 @@ def test_order_calculate_taxes_specific_product_voucher(
voucher_listing.discount_value = unit_discount_amount
voucher_listing.save(update_fields=["discount_value"])
voucher_specific_product_type.variants.add(order_line.variant)
+ create_or_update_voucher_discount_objects_for_order(order)
manager = get_plugins_manager(allow_replica=False)
fetch_order_prices_if_expired(order, manager, order.lines.all(), True)
@@ -1467,6 +1471,7 @@ def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_fixed(
assert voucher.type == VoucherType.SHIPPING
order.voucher = voucher
order.save(update_fields=["voucher_id"])
+ create_or_update_voucher_discount_objects_for_order(order)
manual_reward = Decimal(10)
create_order_discount_for_order(
@@ -1567,6 +1572,7 @@ def test_order_calculate_taxes_free_shipping_voucher_and_manual_discount_percent
assert voucher.type == VoucherType.SHIPPING
order.voucher = voucher
order.save(update_fields=["voucher_id"])
+ create_or_update_voucher_discount_objects_for_order(order)
total_amount -= shipping_price_amount
manual_reward = Decimal(10)